From e715ec27094da5d60e0113c3765b200a613f94e0 Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Mon, 7 Jun 2021 16:58:06 -0700 Subject: [PATCH] feat: Re-generated to pick up changes from googleapis-discovery with latest fixes (#60) This PR was generated using Autosynth. :rainbow: Synth log will be available here: https://source.cloud.google.com/results/invocations/0f625f7b-442c-437d-b302-e058ae94a188/targets - [ ] To automatically regenerate this PR, check this box. (May take up to 24 hours.) Source-Link: https://github.com/googleapis/googleapis-discovery/commit/6b01eb5607e6ba0b3b931905bd779b28dc89b933 Source-Link: https://github.com/googleapis/googleapis-discovery/commit/347a81778216747a59c3cea6c9c771fb8a9bf041 Source-Link: https://github.com/googleapis/googleapis-discovery/commit/0e4b428596ea29f1625472c06f60632018372d17 chore: add x-goog-api-client header to rest clients feat: Raise GoogleAPICallError on REST response errors feat: remove support for google-api-core < 1.26.0 --- .../.pre-commit-config.yaml | 2 +- .../docs/compute_v1/firewall_policies.rst | 10 + .../global_public_delegated_prefixes.rst | 10 + .../compute_v1/public_advertised_prefixes.rst | 10 + .../compute_v1/public_delegated_prefixes.rst | 10 + .../docs/compute_v1/region_instances.rst | 6 + .../docs/compute_v1/services.rst | 5 + packages/google-cloud-compute/docs/conf.py | 1 + .../docs/multiprocessing.rst | 4 +- .../google/cloud/compute/__init__.py | 214 + .../google/cloud/compute_v1/__init__.py | 168 + .../cloud/compute_v1/gapic_metadata.json | 250 + .../services/accelerator_types/client.py | 48 +- .../accelerator_types/transports/base.py | 31 +- .../accelerator_types/transports/rest.py | 33 +- .../compute_v1/services/addresses/client.py | 48 +- .../services/addresses/transports/base.py | 31 +- .../services/addresses/transports/rest.py | 53 +- .../compute_v1/services/autoscalers/client.py | 48 +- .../services/autoscalers/transports/base.py | 31 +- .../services/autoscalers/transports/rest.py | 73 +- .../services/backend_buckets/client.py | 48 +- .../backend_buckets/transports/base.py | 31 +- .../backend_buckets/transports/rest.py | 83 +- .../services/backend_services/client.py | 53 +- .../backend_services/transports/base.py | 31 +- .../backend_services/transports/rest.py | 113 +- .../compute_v1/services/disk_types/client.py | 48 +- .../services/disk_types/transports/base.py | 31 +- .../services/disk_types/transports/rest.py | 33 +- .../cloud/compute_v1/services/disks/client.py | 48 +- .../services/disks/transports/base.py | 31 +- .../services/disks/transports/rest.py | 133 +- .../services/external_vpn_gateways/client.py | 48 +- .../external_vpn_gateways/transports/base.py | 31 +- .../external_vpn_gateways/transports/rest.py | 63 +- .../services/firewall_policies/__init__.py | 18 + .../services/firewall_policies/client.py | 1880 ++++++ .../services/firewall_policies/pagers.py | 89 + .../firewall_policies/transports/__init__.py | 30 + .../firewall_policies/transports/base.py | 378 ++ .../firewall_policies/transports/rest.py | 1527 +++++ .../compute_v1/services/firewalls/client.py | 48 +- .../services/firewalls/transports/base.py | 31 +- .../services/firewalls/transports/rest.py | 63 +- .../services/forwarding_rules/client.py | 167 +- .../forwarding_rules/transports/base.py | 43 +- .../forwarding_rules/transports/rest.py | 164 +- .../services/global_addresses/client.py | 48 +- .../global_addresses/transports/base.py | 31 +- .../global_addresses/transports/rest.py | 43 +- .../global_forwarding_rules/client.py | 159 +- .../transports/base.py | 43 +- .../transports/rest.py | 149 +- .../global_network_endpoint_groups/client.py | 48 +- .../transports/base.py | 31 +- .../transports/rest.py | 73 +- .../services/global_operations/client.py | 48 +- .../global_operations/transports/base.py | 31 +- .../global_operations/transports/rest.py | 53 +- .../global_organization_operations/client.py | 48 +- .../transports/base.py | 31 +- .../transports/rest.py | 33 +- .../__init__.py | 18 + .../client.py | 806 +++ .../pagers.py | 89 + .../transports/__init__.py | 32 + .../transports/base.py | 215 + .../transports/rest.py | 491 ++ .../services/health_checks/client.py | 48 +- .../services/health_checks/transports/base.py | 31 +- .../services/health_checks/transports/rest.py | 73 +- .../compute_v1/services/images/client.py | 48 +- .../services/images/transports/base.py | 31 +- .../services/images/transports/rest.py | 113 +- .../instance_group_managers/client.py | 72 +- .../transports/base.py | 31 +- .../transports/rest.py | 203 +- .../services/instance_groups/client.py | 48 +- .../instance_groups/transports/base.py | 31 +- .../instance_groups/transports/rest.py | 93 +- .../services/instance_templates/client.py | 48 +- .../instance_templates/transports/base.py | 31 +- .../instance_templates/transports/rest.py | 73 +- .../compute_v1/services/instances/client.py | 258 +- .../services/instances/transports/base.py | 60 +- .../services/instances/transports/rest.py | 549 +- .../interconnect_attachments/client.py | 48 +- .../transports/base.py | 31 +- .../transports/rest.py | 63 +- .../services/interconnect_locations/client.py | 48 +- .../interconnect_locations/transports/base.py | 31 +- .../interconnect_locations/transports/rest.py | 23 +- .../services/interconnects/client.py | 48 +- .../services/interconnects/transports/base.py | 31 +- .../services/interconnects/transports/rest.py | 63 +- .../services/license_codes/client.py | 48 +- .../services/license_codes/transports/base.py | 31 +- .../services/license_codes/transports/rest.py | 23 +- .../compute_v1/services/licenses/client.py | 48 +- .../services/licenses/transports/base.py | 31 +- .../services/licenses/transports/rest.py | 73 +- .../services/machine_types/client.py | 48 +- .../services/machine_types/transports/base.py | 31 +- .../services/machine_types/transports/rest.py | 33 +- .../network_endpoint_groups/client.py | 48 +- .../transports/base.py | 31 +- .../transports/rest.py | 93 +- .../compute_v1/services/networks/client.py | 118 +- .../services/networks/transports/base.py | 48 +- .../services/networks/transports/rest.py | 156 +- .../compute_v1/services/node_groups/client.py | 48 +- .../services/node_groups/transports/base.py | 31 +- .../services/node_groups/transports/rest.py | 133 +- .../services/node_templates/client.py | 48 +- .../node_templates/transports/base.py | 31 +- .../node_templates/transports/rest.py | 83 +- .../compute_v1/services/node_types/client.py | 48 +- .../services/node_types/transports/base.py | 31 +- .../services/node_types/transports/rest.py | 33 +- .../services/packet_mirrorings/client.py | 48 +- .../packet_mirrorings/transports/base.py | 31 +- .../packet_mirrorings/transports/rest.py | 73 +- .../compute_v1/services/projects/client.py | 48 +- .../services/projects/transports/base.py | 31 +- .../services/projects/transports/rest.py | 133 +- .../public_advertised_prefixes/__init__.py | 18 + .../public_advertised_prefixes/client.py | 800 +++ .../public_advertised_prefixes/pagers.py | 89 + .../transports/__init__.py | 32 + .../transports/base.py | 217 + .../transports/rest.py | 486 ++ .../public_delegated_prefixes/__init__.py | 18 + .../public_delegated_prefixes/client.py | 921 +++ .../public_delegated_prefixes/pagers.py | 156 + .../transports/__init__.py | 32 + .../transports/base.py | 230 + .../transports/rest.py | 560 ++ .../services/region_autoscalers/client.py | 48 +- .../region_autoscalers/transports/base.py | 31 +- .../region_autoscalers/transports/rest.py | 63 +- .../region_backend_services/client.py | 48 +- .../transports/base.py | 31 +- .../transports/rest.py | 73 +- .../services/region_commitments/client.py | 48 +- .../region_commitments/transports/base.py | 31 +- .../region_commitments/transports/rest.py | 43 +- .../services/region_disk_types/client.py | 48 +- .../region_disk_types/transports/base.py | 31 +- .../region_disk_types/transports/rest.py | 23 +- .../services/region_disks/client.py | 48 +- .../services/region_disks/transports/base.py | 31 +- .../services/region_disks/transports/rest.py | 123 +- .../region_health_check_services/client.py | 48 +- .../transports/base.py | 31 +- .../transports/rest.py | 53 +- .../services/region_health_checks/client.py | 48 +- .../region_health_checks/transports/base.py | 31 +- .../region_health_checks/transports/rest.py | 63 +- .../region_instance_group_managers/client.py | 72 +- .../transports/base.py | 31 +- .../transports/rest.py | 193 +- .../services/region_instance_groups/client.py | 48 +- .../region_instance_groups/transports/base.py | 31 +- .../region_instance_groups/transports/rest.py | 43 +- .../services/region_instances/__init__.py | 18 + .../services/region_instances/client.py | 449 ++ .../region_instances/transports/__init__.py | 30 + .../region_instances/transports/base.py | 164 + .../region_instances/transports/rest.py | 186 + .../region_network_endpoint_groups/client.py | 48 +- .../transports/base.py | 31 +- .../transports/rest.py | 43 +- .../region_notification_endpoints/client.py | 48 +- .../transports/base.py | 31 +- .../transports/rest.py | 43 +- .../services/region_operations/client.py | 48 +- .../region_operations/transports/base.py | 31 +- .../region_operations/transports/rest.py | 43 +- .../region_ssl_certificates/client.py | 48 +- .../transports/base.py | 31 +- .../transports/rest.py | 43 +- .../region_target_http_proxies/client.py | 48 +- .../transports/base.py | 31 +- .../transports/rest.py | 53 +- .../region_target_https_proxies/client.py | 48 +- .../transports/base.py | 31 +- .../transports/rest.py | 63 +- .../services/region_url_maps/client.py | 48 +- .../region_url_maps/transports/base.py | 31 +- .../region_url_maps/transports/rest.py | 73 +- .../compute_v1/services/regions/client.py | 48 +- .../services/regions/transports/base.py | 31 +- .../services/regions/transports/rest.py | 23 +- .../services/reservations/client.py | 48 +- .../services/reservations/transports/base.py | 31 +- .../services/reservations/transports/rest.py | 93 +- .../services/resource_policies/client.py | 48 +- .../resource_policies/transports/base.py | 31 +- .../resource_policies/transports/rest.py | 83 +- .../compute_v1/services/routers/client.py | 48 +- .../services/routers/transports/base.py | 31 +- .../services/routers/transports/rest.py | 103 +- .../compute_v1/services/routes/client.py | 48 +- .../services/routes/transports/base.py | 31 +- .../services/routes/transports/rest.py | 43 +- .../services/security_policies/client.py | 48 +- .../security_policies/transports/base.py | 31 +- .../security_policies/transports/rest.py | 103 +- .../compute_v1/services/snapshots/client.py | 48 +- .../services/snapshots/transports/base.py | 31 +- .../services/snapshots/transports/rest.py | 73 +- .../services/ssl_certificates/client.py | 48 +- .../ssl_certificates/transports/base.py | 31 +- .../ssl_certificates/transports/rest.py | 53 +- .../services/ssl_policies/client.py | 48 +- .../services/ssl_policies/transports/base.py | 31 +- .../services/ssl_policies/transports/rest.py | 63 +- .../compute_v1/services/subnetworks/client.py | 48 +- .../services/subnetworks/transports/base.py | 31 +- .../services/subnetworks/transports/rest.py | 123 +- .../services/target_grpc_proxies/client.py | 57 +- .../target_grpc_proxies/transports/base.py | 31 +- .../target_grpc_proxies/transports/rest.py | 65 +- .../services/target_http_proxies/client.py | 48 +- .../target_http_proxies/transports/base.py | 31 +- .../target_http_proxies/transports/rest.py | 73 +- .../services/target_https_proxies/client.py | 158 +- .../target_https_proxies/transports/base.py | 43 +- .../target_https_proxies/transports/rest.py | 183 +- .../services/target_instances/client.py | 48 +- .../target_instances/transports/base.py | 31 +- .../target_instances/transports/rest.py | 53 +- .../services/target_pools/client.py | 48 +- .../services/target_pools/transports/base.py | 31 +- .../services/target_pools/transports/rest.py | 113 +- .../services/target_ssl_proxies/client.py | 48 +- .../target_ssl_proxies/transports/base.py | 31 +- .../target_ssl_proxies/transports/rest.py | 83 +- .../services/target_tcp_proxies/client.py | 48 +- .../target_tcp_proxies/transports/base.py | 31 +- .../target_tcp_proxies/transports/rest.py | 63 +- .../services/target_vpn_gateways/client.py | 48 +- .../target_vpn_gateways/transports/base.py | 31 +- .../target_vpn_gateways/transports/rest.py | 53 +- .../compute_v1/services/url_maps/client.py | 48 +- .../services/url_maps/transports/base.py | 31 +- .../services/url_maps/transports/rest.py | 93 +- .../services/vpn_gateways/client.py | 48 +- .../services/vpn_gateways/transports/base.py | 31 +- .../services/vpn_gateways/transports/rest.py | 83 +- .../compute_v1/services/vpn_tunnels/client.py | 48 +- .../services/vpn_tunnels/transports/base.py | 31 +- .../services/vpn_tunnels/transports/rest.py | 53 +- .../services/zone_operations/client.py | 48 +- .../zone_operations/transports/base.py | 31 +- .../zone_operations/transports/rest.py | 43 +- .../cloud/compute_v1/services/zones/client.py | 48 +- .../services/zones/transports/base.py | 31 +- .../services/zones/transports/rest.py | 23 +- .../google/cloud/compute_v1/types/__init__.py | 156 + .../google/cloud/compute_v1/types/compute.py | 5778 +++++++++++++---- packages/google-cloud-compute/noxfile.py | 8 +- packages/google-cloud-compute/setup.py | 3 +- packages/google-cloud-compute/synth.metadata | 43 +- packages/google-cloud-compute/synth.py | 2 +- .../testing/constraints-3.6.txt | 3 +- .../tests/system/test_smoke.py | 11 +- .../compute_v1/test_accelerator_types.py | 18 +- .../unit/gapic/compute_v1/test_addresses.py | 20 +- .../unit/gapic/compute_v1/test_autoscalers.py | 36 +- .../gapic/compute_v1/test_backend_buckets.py | 42 +- .../gapic/compute_v1/test_backend_services.py | 46 +- .../unit/gapic/compute_v1/test_disk_types.py | 18 +- .../tests/unit/gapic/compute_v1/test_disks.py | 38 +- .../compute_v1/test_external_vpn_gateways.py | 24 +- .../compute_v1/test_firewall_policies.py | 2844 ++++++++ .../unit/gapic/compute_v1/test_firewalls.py | 48 +- .../gapic/compute_v1/test_forwarding_rules.py | 217 +- .../gapic/compute_v1/test_global_addresses.py | 22 +- .../test_global_forwarding_rules.py | 212 +- .../test_global_network_endpoint_groups.py | 30 +- .../compute_v1/test_global_operations.py | 22 +- .../test_global_organization_operations.py | 20 +- .../test_global_public_delegated_prefixes.py | 1438 ++++ .../gapic/compute_v1/test_health_checks.py | 26 +- .../unit/gapic/compute_v1/test_images.py | 30 +- .../test_instance_group_managers.py | 50 +- .../gapic/compute_v1/test_instance_groups.py | 28 +- .../compute_v1/test_instance_templates.py | 34 +- .../unit/gapic/compute_v1/test_instances.py | 384 +- .../test_interconnect_attachments.py | 28 +- .../compute_v1/test_interconnect_locations.py | 18 +- .../gapic/compute_v1/test_interconnects.py | 24 +- .../gapic/compute_v1/test_license_codes.py | 18 +- .../unit/gapic/compute_v1/test_licenses.py | 20 +- .../gapic/compute_v1/test_machine_types.py | 18 +- .../test_network_endpoint_groups.py | 30 +- .../unit/gapic/compute_v1/test_networks.py | 145 +- .../unit/gapic/compute_v1/test_node_groups.py | 32 +- .../gapic/compute_v1/test_node_templates.py | 22 +- .../unit/gapic/compute_v1/test_node_types.py | 18 +- .../compute_v1/test_packet_mirrorings.py | 28 +- .../unit/gapic/compute_v1/test_projects.py | 34 +- .../test_public_advertised_prefixes.py | 1422 ++++ .../test_public_delegated_prefixes.py | 1619 +++++ .../compute_v1/test_region_autoscalers.py | 36 +- .../test_region_backend_services.py | 40 +- .../compute_v1/test_region_commitments.py | 20 +- .../compute_v1/test_region_disk_types.py | 18 +- .../gapic/compute_v1/test_region_disks.py | 40 +- .../test_region_health_check_services.py | 24 +- .../compute_v1/test_region_health_checks.py | 26 +- .../test_region_instance_group_managers.py | 50 +- .../compute_v1/test_region_instance_groups.py | 20 +- .../gapic/compute_v1/test_region_instances.py | 854 +++ .../test_region_network_endpoint_groups.py | 26 +- .../test_region_notification_endpoints.py | 22 +- .../compute_v1/test_region_operations.py | 22 +- .../test_region_ssl_certificates.py | 22 +- .../test_region_target_http_proxies.py | 24 +- .../test_region_target_https_proxies.py | 28 +- .../gapic/compute_v1/test_region_url_maps.py | 26 +- .../unit/gapic/compute_v1/test_regions.py | 18 +- .../gapic/compute_v1/test_reservations.py | 26 +- .../compute_v1/test_resource_policies.py | 41 +- .../unit/gapic/compute_v1/test_routers.py | 26 +- .../unit/gapic/compute_v1/test_routes.py | 20 +- .../compute_v1/test_security_policies.py | 30 +- .../unit/gapic/compute_v1/test_snapshots.py | 24 +- .../gapic/compute_v1/test_ssl_certificates.py | 22 +- .../gapic/compute_v1/test_ssl_policies.py | 24 +- .../unit/gapic/compute_v1/test_subnetworks.py | 28 +- .../compute_v1/test_target_grpc_proxies.py | 24 +- .../compute_v1/test_target_http_proxies.py | 26 +- .../compute_v1/test_target_https_proxies.py | 176 +- .../gapic/compute_v1/test_target_instances.py | 22 +- .../gapic/compute_v1/test_target_pools.py | 32 +- .../compute_v1/test_target_ssl_proxies.py | 30 +- .../compute_v1/test_target_tcp_proxies.py | 28 +- .../compute_v1/test_target_vpn_gateways.py | 22 +- .../unit/gapic/compute_v1/test_url_maps.py | 26 +- .../gapic/compute_v1/test_vpn_gateways.py | 24 +- .../unit/gapic/compute_v1/test_vpn_tunnels.py | 22 +- .../gapic/compute_v1/test_zone_operations.py | 22 +- .../tests/unit/gapic/compute_v1/test_zones.py | 18 +- 346 files changed, 32730 insertions(+), 7653 deletions(-) create mode 100644 packages/google-cloud-compute/docs/compute_v1/firewall_policies.rst create mode 100644 packages/google-cloud-compute/docs/compute_v1/global_public_delegated_prefixes.rst create mode 100644 packages/google-cloud-compute/docs/compute_v1/public_advertised_prefixes.rst create mode 100644 packages/google-cloud-compute/docs/compute_v1/public_delegated_prefixes.rst create mode 100644 packages/google-cloud-compute/docs/compute_v1/region_instances.rst create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/__init__.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/client.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/pagers.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/transports/__init__.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/transports/base.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/transports/rest.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/global_public_delegated_prefixes/__init__.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/global_public_delegated_prefixes/client.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/global_public_delegated_prefixes/pagers.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/global_public_delegated_prefixes/transports/__init__.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/global_public_delegated_prefixes/transports/base.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/global_public_delegated_prefixes/transports/rest.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/public_advertised_prefixes/__init__.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/public_advertised_prefixes/client.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/public_advertised_prefixes/pagers.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/public_advertised_prefixes/transports/__init__.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/public_advertised_prefixes/transports/base.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/public_advertised_prefixes/transports/rest.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/public_delegated_prefixes/__init__.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/public_delegated_prefixes/client.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/public_delegated_prefixes/pagers.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/public_delegated_prefixes/transports/__init__.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/public_delegated_prefixes/transports/base.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/public_delegated_prefixes/transports/rest.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/region_instances/__init__.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/region_instances/client.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/region_instances/transports/__init__.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/region_instances/transports/base.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/region_instances/transports/rest.py create mode 100644 packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_firewall_policies.py create mode 100644 packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_public_delegated_prefixes.py create mode 100644 packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_public_advertised_prefixes.py create mode 100644 packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_public_delegated_prefixes.py create mode 100644 packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instances.py diff --git a/packages/google-cloud-compute/.pre-commit-config.yaml b/packages/google-cloud-compute/.pre-commit-config.yaml index 1bbd787833ec..4f00c7cffcfd 100644 --- a/packages/google-cloud-compute/.pre-commit-config.yaml +++ b/packages/google-cloud-compute/.pre-commit-config.yaml @@ -26,6 +26,6 @@ repos: hooks: - id: black - repo: https://gitlab.com/pycqa/flake8 - rev: 3.9.1 + rev: 3.9.2 hooks: - id: flake8 diff --git a/packages/google-cloud-compute/docs/compute_v1/firewall_policies.rst b/packages/google-cloud-compute/docs/compute_v1/firewall_policies.rst new file mode 100644 index 000000000000..2d4fbd9ff22a --- /dev/null +++ b/packages/google-cloud-compute/docs/compute_v1/firewall_policies.rst @@ -0,0 +1,10 @@ +FirewallPolicies +---------------------------------- + +.. automodule:: google.cloud.compute_v1.services.firewall_policies + :members: + :inherited-members: + +.. automodule:: google.cloud.compute_v1.services.firewall_policies.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-compute/docs/compute_v1/global_public_delegated_prefixes.rst b/packages/google-cloud-compute/docs/compute_v1/global_public_delegated_prefixes.rst new file mode 100644 index 000000000000..c712f7473f95 --- /dev/null +++ b/packages/google-cloud-compute/docs/compute_v1/global_public_delegated_prefixes.rst @@ -0,0 +1,10 @@ +GlobalPublicDelegatedPrefixes +----------------------------------------------- + +.. automodule:: google.cloud.compute_v1.services.global_public_delegated_prefixes + :members: + :inherited-members: + +.. automodule:: google.cloud.compute_v1.services.global_public_delegated_prefixes.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-compute/docs/compute_v1/public_advertised_prefixes.rst b/packages/google-cloud-compute/docs/compute_v1/public_advertised_prefixes.rst new file mode 100644 index 000000000000..54c4336888b1 --- /dev/null +++ b/packages/google-cloud-compute/docs/compute_v1/public_advertised_prefixes.rst @@ -0,0 +1,10 @@ +PublicAdvertisedPrefixes +------------------------------------------ + +.. automodule:: google.cloud.compute_v1.services.public_advertised_prefixes + :members: + :inherited-members: + +.. automodule:: google.cloud.compute_v1.services.public_advertised_prefixes.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-compute/docs/compute_v1/public_delegated_prefixes.rst b/packages/google-cloud-compute/docs/compute_v1/public_delegated_prefixes.rst new file mode 100644 index 000000000000..79874476402e --- /dev/null +++ b/packages/google-cloud-compute/docs/compute_v1/public_delegated_prefixes.rst @@ -0,0 +1,10 @@ +PublicDelegatedPrefixes +----------------------------------------- + +.. automodule:: google.cloud.compute_v1.services.public_delegated_prefixes + :members: + :inherited-members: + +.. automodule:: google.cloud.compute_v1.services.public_delegated_prefixes.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-compute/docs/compute_v1/region_instances.rst b/packages/google-cloud-compute/docs/compute_v1/region_instances.rst new file mode 100644 index 000000000000..780a33cd91c1 --- /dev/null +++ b/packages/google-cloud-compute/docs/compute_v1/region_instances.rst @@ -0,0 +1,6 @@ +RegionInstances +--------------------------------- + +.. automodule:: google.cloud.compute_v1.services.region_instances + :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 244fcf09646e..b3e27397724b 100644 --- a/packages/google-cloud-compute/docs/compute_v1/services.rst +++ b/packages/google-cloud-compute/docs/compute_v1/services.rst @@ -11,6 +11,7 @@ Services for Google Cloud Compute v1 API disks disk_types external_vpn_gateways + firewall_policies firewalls forwarding_rules global_addresses @@ -18,6 +19,7 @@ Services for Google Cloud Compute v1 API global_network_endpoint_groups global_operations global_organization_operations + global_public_delegated_prefixes health_checks images instance_group_managers @@ -37,6 +39,8 @@ Services for Google Cloud Compute v1 API node_types packet_mirrorings projects + public_advertised_prefixes + public_delegated_prefixes region_autoscalers region_backend_services region_commitments @@ -46,6 +50,7 @@ Services for Google Cloud Compute v1 API region_health_check_services region_instance_group_managers region_instance_groups + region_instances region_network_endpoint_groups region_notification_endpoints region_operations diff --git a/packages/google-cloud-compute/docs/conf.py b/packages/google-cloud-compute/docs/conf.py index 3a93a336b9ef..5774aeb8b4bd 100644 --- a/packages/google-cloud-compute/docs/conf.py +++ b/packages/google-cloud-compute/docs/conf.py @@ -363,6 +363,7 @@ "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), } diff --git a/packages/google-cloud-compute/docs/multiprocessing.rst b/packages/google-cloud-compute/docs/multiprocessing.rst index 1cb29d4ca967..536d17b2ea65 100644 --- a/packages/google-cloud-compute/docs/multiprocessing.rst +++ b/packages/google-cloud-compute/docs/multiprocessing.rst @@ -1,7 +1,7 @@ .. note:: - Because this client uses :mod:`grpcio` library, it is safe to + 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` or + :func:`os.fork` by :class:`multiprocessing.pool.Pool` or :class:`multiprocessing.Process`. diff --git a/packages/google-cloud-compute/google/cloud/compute/__init__.py b/packages/google-cloud-compute/google/cloud/compute/__init__.py index 4be256c29f19..8ba011a2d781 100644 --- a/packages/google-cloud-compute/google/cloud/compute/__init__.py +++ b/packages/google-cloud-compute/google/cloud/compute/__init__.py @@ -28,6 +28,9 @@ from google.cloud.compute_v1.services.external_vpn_gateways.client import ( ExternalVpnGatewaysClient, ) +from google.cloud.compute_v1.services.firewall_policies.client import ( + FirewallPoliciesClient, +) from google.cloud.compute_v1.services.firewalls.client import FirewallsClient from google.cloud.compute_v1.services.forwarding_rules.client import ( ForwardingRulesClient, @@ -47,6 +50,9 @@ from google.cloud.compute_v1.services.global_organization_operations.client import ( GlobalOrganizationOperationsClient, ) +from google.cloud.compute_v1.services.global_public_delegated_prefixes.client import ( + GlobalPublicDelegatedPrefixesClient, +) from google.cloud.compute_v1.services.health_checks.client import HealthChecksClient from google.cloud.compute_v1.services.images.client import ImagesClient from google.cloud.compute_v1.services.instance_group_managers.client import ( @@ -78,6 +84,12 @@ PacketMirroringsClient, ) from google.cloud.compute_v1.services.projects.client import ProjectsClient +from google.cloud.compute_v1.services.public_advertised_prefixes.client import ( + PublicAdvertisedPrefixesClient, +) +from google.cloud.compute_v1.services.public_delegated_prefixes.client import ( + PublicDelegatedPrefixesClient, +) from google.cloud.compute_v1.services.region_autoscalers.client import ( RegionAutoscalersClient, ) @@ -103,6 +115,9 @@ from google.cloud.compute_v1.services.region_instance_groups.client import ( RegionInstanceGroupsClient, ) +from google.cloud.compute_v1.services.region_instances.client import ( + RegionInstancesClient, +) from google.cloud.compute_v1.services.region_network_endpoint_groups.client import ( RegionNetworkEndpointGroupsClient, ) @@ -180,6 +195,7 @@ from google.cloud.compute_v1.types.compute import AcceleratorTypesScopedList from google.cloud.compute_v1.types.compute import AccessConfig from google.cloud.compute_v1.types.compute import AddAccessConfigInstanceRequest +from google.cloud.compute_v1.types.compute import AddAssociationFirewallPolicyRequest from google.cloud.compute_v1.types.compute import AddHealthCheckTargetPoolRequest from google.cloud.compute_v1.types.compute import AddInstancesInstanceGroupRequest from google.cloud.compute_v1.types.compute import AddInstanceTargetPoolRequest @@ -192,9 +208,11 @@ from google.cloud.compute_v1.types.compute import AddressAggregatedList from google.cloud.compute_v1.types.compute import AddressesScopedList from google.cloud.compute_v1.types.compute import AddressList +from google.cloud.compute_v1.types.compute import AddRuleFirewallPolicyRequest from google.cloud.compute_v1.types.compute import AddRuleSecurityPolicyRequest from google.cloud.compute_v1.types.compute import AddSignedUrlKeyBackendBucketRequest from google.cloud.compute_v1.types.compute import AddSignedUrlKeyBackendServiceRequest +from google.cloud.compute_v1.types.compute import AdvancedMachineFeatures from google.cloud.compute_v1.types.compute import AggregatedListAcceleratorTypesRequest from google.cloud.compute_v1.types.compute import AggregatedListAddressesRequest from google.cloud.compute_v1.types.compute import AggregatedListAutoscalersRequest @@ -220,6 +238,9 @@ from google.cloud.compute_v1.types.compute import AggregatedListNodeTemplatesRequest from google.cloud.compute_v1.types.compute import AggregatedListNodeTypesRequest from google.cloud.compute_v1.types.compute import AggregatedListPacketMirroringsRequest +from google.cloud.compute_v1.types.compute import ( + AggregatedListPublicDelegatedPrefixesRequest, +) from google.cloud.compute_v1.types.compute import AggregatedListRegionCommitmentsRequest from google.cloud.compute_v1.types.compute import AggregatedListReservationsRequest from google.cloud.compute_v1.types.compute import AggregatedListResourcePoliciesRequest @@ -277,13 +298,26 @@ AutoscalingPolicyLoadBalancingUtilization, ) from google.cloud.compute_v1.types.compute import AutoscalingPolicyScaleInControl +from google.cloud.compute_v1.types.compute import AutoscalingPolicyScalingSchedule from google.cloud.compute_v1.types.compute import Backend from google.cloud.compute_v1.types.compute import BackendBucket from google.cloud.compute_v1.types.compute import BackendBucketCdnPolicy +from google.cloud.compute_v1.types.compute import ( + BackendBucketCdnPolicyBypassCacheOnRequestHeader, +) +from google.cloud.compute_v1.types.compute import ( + BackendBucketCdnPolicyNegativeCachingPolicy, +) from google.cloud.compute_v1.types.compute import BackendBucketList from google.cloud.compute_v1.types.compute import BackendService from google.cloud.compute_v1.types.compute import BackendServiceAggregatedList from google.cloud.compute_v1.types.compute import BackendServiceCdnPolicy +from google.cloud.compute_v1.types.compute import ( + BackendServiceCdnPolicyBypassCacheOnRequestHeader, +) +from google.cloud.compute_v1.types.compute import ( + BackendServiceCdnPolicyNegativeCachingPolicy, +) from google.cloud.compute_v1.types.compute import BackendServiceFailoverPolicy from google.cloud.compute_v1.types.compute import BackendServiceGroupHealth from google.cloud.compute_v1.types.compute import BackendServiceIAP @@ -292,9 +326,16 @@ from google.cloud.compute_v1.types.compute import BackendServiceReference from google.cloud.compute_v1.types.compute import BackendServicesScopedList from google.cloud.compute_v1.types.compute import Binding +from google.cloud.compute_v1.types.compute import BulkInsertInstanceRequest +from google.cloud.compute_v1.types.compute import BulkInsertInstanceResource +from google.cloud.compute_v1.types.compute import ( + BulkInsertInstanceResourcePerInstanceProperties, +) +from google.cloud.compute_v1.types.compute import BulkInsertRegionInstanceRequest from google.cloud.compute_v1.types.compute import CacheInvalidationRule from google.cloud.compute_v1.types.compute import CacheKeyPolicy from google.cloud.compute_v1.types.compute import CircuitBreakers +from google.cloud.compute_v1.types.compute import CloneRulesFirewallPolicyRequest from google.cloud.compute_v1.types.compute import Commitment from google.cloud.compute_v1.types.compute import CommitmentAggregatedList from google.cloud.compute_v1.types.compute import CommitmentList @@ -325,6 +366,7 @@ from google.cloud.compute_v1.types.compute import DeleteBackendServiceRequest from google.cloud.compute_v1.types.compute import DeleteDiskRequest from google.cloud.compute_v1.types.compute import DeleteExternalVpnGatewayRequest +from google.cloud.compute_v1.types.compute import DeleteFirewallPolicyRequest from google.cloud.compute_v1.types.compute import DeleteFirewallRequest from google.cloud.compute_v1.types.compute import DeleteForwardingRuleRequest from google.cloud.compute_v1.types.compute import DeleteGlobalAddressRequest @@ -340,6 +382,9 @@ from google.cloud.compute_v1.types.compute import ( DeleteGlobalOrganizationOperationResponse, ) +from google.cloud.compute_v1.types.compute import ( + DeleteGlobalPublicDelegatedPrefixeRequest, +) from google.cloud.compute_v1.types.compute import DeleteHealthCheckRequest from google.cloud.compute_v1.types.compute import DeleteImageRequest from google.cloud.compute_v1.types.compute import DeleteInstanceGroupManagerRequest @@ -367,6 +412,8 @@ from google.cloud.compute_v1.types.compute import ( DeletePerInstanceConfigsRegionInstanceGroupManagerRequest, ) +from google.cloud.compute_v1.types.compute import DeletePublicAdvertisedPrefixeRequest +from google.cloud.compute_v1.types.compute import DeletePublicDelegatedPrefixeRequest from google.cloud.compute_v1.types.compute import DeleteRegionAutoscalerRequest from google.cloud.compute_v1.types.compute import DeleteRegionBackendServiceRequest from google.cloud.compute_v1.types.compute import DeleteRegionDiskRequest @@ -457,21 +504,37 @@ from google.cloud.compute_v1.types.compute import Firewall from google.cloud.compute_v1.types.compute import FirewallList from google.cloud.compute_v1.types.compute import FirewallLogConfig +from google.cloud.compute_v1.types.compute import ( + FirewallPoliciesListAssociationsResponse, +) +from google.cloud.compute_v1.types.compute import FirewallPolicy +from google.cloud.compute_v1.types.compute import FirewallPolicyAssociation +from google.cloud.compute_v1.types.compute import FirewallPolicyList +from google.cloud.compute_v1.types.compute import FirewallPolicyRule +from google.cloud.compute_v1.types.compute import FirewallPolicyRuleMatcher +from google.cloud.compute_v1.types.compute import FirewallPolicyRuleMatcherLayer4Config from google.cloud.compute_v1.types.compute import FixedOrPercent from google.cloud.compute_v1.types.compute import ForwardingRule from google.cloud.compute_v1.types.compute import ForwardingRuleAggregatedList from google.cloud.compute_v1.types.compute import ForwardingRuleList from google.cloud.compute_v1.types.compute import ForwardingRuleReference +from google.cloud.compute_v1.types.compute import ( + ForwardingRuleServiceDirectoryRegistration, +) from google.cloud.compute_v1.types.compute import ForwardingRulesScopedList from google.cloud.compute_v1.types.compute import GetAcceleratorTypeRequest from google.cloud.compute_v1.types.compute import GetAddressRequest +from google.cloud.compute_v1.types.compute import GetAssociationFirewallPolicyRequest from google.cloud.compute_v1.types.compute import GetAutoscalerRequest from google.cloud.compute_v1.types.compute import GetBackendBucketRequest from google.cloud.compute_v1.types.compute import GetBackendServiceRequest from google.cloud.compute_v1.types.compute import GetDiagnosticsInterconnectRequest from google.cloud.compute_v1.types.compute import GetDiskRequest from google.cloud.compute_v1.types.compute import GetDiskTypeRequest +from google.cloud.compute_v1.types.compute import GetEffectiveFirewallsInstanceRequest +from google.cloud.compute_v1.types.compute import GetEffectiveFirewallsNetworkRequest from google.cloud.compute_v1.types.compute import GetExternalVpnGatewayRequest +from google.cloud.compute_v1.types.compute import GetFirewallPolicyRequest from google.cloud.compute_v1.types.compute import GetFirewallRequest from google.cloud.compute_v1.types.compute import GetForwardingRuleRequest from google.cloud.compute_v1.types.compute import GetFromFamilyImageRequest @@ -480,12 +543,14 @@ from google.cloud.compute_v1.types.compute import GetGlobalNetworkEndpointGroupRequest from google.cloud.compute_v1.types.compute import GetGlobalOperationRequest from google.cloud.compute_v1.types.compute import GetGlobalOrganizationOperationRequest +from google.cloud.compute_v1.types.compute import GetGlobalPublicDelegatedPrefixeRequest from google.cloud.compute_v1.types.compute import GetGuestAttributesInstanceRequest from google.cloud.compute_v1.types.compute import GetHealthBackendServiceRequest from google.cloud.compute_v1.types.compute import GetHealthCheckRequest from google.cloud.compute_v1.types.compute import GetHealthRegionBackendServiceRequest from google.cloud.compute_v1.types.compute import GetHealthTargetPoolRequest from google.cloud.compute_v1.types.compute import GetIamPolicyDiskRequest +from google.cloud.compute_v1.types.compute import GetIamPolicyFirewallPolicyRequest from google.cloud.compute_v1.types.compute import GetIamPolicyImageRequest from google.cloud.compute_v1.types.compute import GetIamPolicyInstanceRequest from google.cloud.compute_v1.types.compute import GetIamPolicyInstanceTemplateRequest @@ -516,6 +581,8 @@ from google.cloud.compute_v1.types.compute import GetNodeTypeRequest from google.cloud.compute_v1.types.compute import GetPacketMirroringRequest from google.cloud.compute_v1.types.compute import GetProjectRequest +from google.cloud.compute_v1.types.compute import GetPublicAdvertisedPrefixeRequest +from google.cloud.compute_v1.types.compute import GetPublicDelegatedPrefixeRequest from google.cloud.compute_v1.types.compute import GetRegionAutoscalerRequest from google.cloud.compute_v1.types.compute import GetRegionBackendServiceRequest from google.cloud.compute_v1.types.compute import GetRegionCommitmentRequest @@ -538,6 +605,7 @@ from google.cloud.compute_v1.types.compute import GetRouteRequest from google.cloud.compute_v1.types.compute import GetRouterRequest from google.cloud.compute_v1.types.compute import GetRouterStatusRouterRequest +from google.cloud.compute_v1.types.compute import GetRuleFirewallPolicyRequest from google.cloud.compute_v1.types.compute import GetRuleSecurityPolicyRequest from google.cloud.compute_v1.types.compute import GetScreenshotInstanceRequest from google.cloud.compute_v1.types.compute import GetSecurityPolicyRequest @@ -571,6 +639,7 @@ from google.cloud.compute_v1.types.compute import ( GlobalNetworkEndpointGroupsDetachEndpointsRequest, ) +from google.cloud.compute_v1.types.compute import GlobalOrganizationSetPolicyRequest from google.cloud.compute_v1.types.compute import GlobalSetLabelsRequest from google.cloud.compute_v1.types.compute import GlobalSetPolicyRequest from google.cloud.compute_v1.types.compute import GRPCHealthCheck @@ -614,6 +683,7 @@ from google.cloud.compute_v1.types.compute import InsertBackendServiceRequest from google.cloud.compute_v1.types.compute import InsertDiskRequest from google.cloud.compute_v1.types.compute import InsertExternalVpnGatewayRequest +from google.cloud.compute_v1.types.compute import InsertFirewallPolicyRequest from google.cloud.compute_v1.types.compute import InsertFirewallRequest from google.cloud.compute_v1.types.compute import InsertForwardingRuleRequest from google.cloud.compute_v1.types.compute import InsertGlobalAddressRequest @@ -621,6 +691,9 @@ from google.cloud.compute_v1.types.compute import ( InsertGlobalNetworkEndpointGroupRequest, ) +from google.cloud.compute_v1.types.compute import ( + InsertGlobalPublicDelegatedPrefixeRequest, +) from google.cloud.compute_v1.types.compute import InsertHealthCheckRequest from google.cloud.compute_v1.types.compute import InsertImageRequest from google.cloud.compute_v1.types.compute import InsertInstanceGroupManagerRequest @@ -635,6 +708,8 @@ from google.cloud.compute_v1.types.compute import InsertNodeGroupRequest from google.cloud.compute_v1.types.compute import InsertNodeTemplateRequest from google.cloud.compute_v1.types.compute import InsertPacketMirroringRequest +from google.cloud.compute_v1.types.compute import InsertPublicAdvertisedPrefixeRequest +from google.cloud.compute_v1.types.compute import InsertPublicDelegatedPrefixeRequest from google.cloud.compute_v1.types.compute import InsertRegionAutoscalerRequest from google.cloud.compute_v1.types.compute import InsertRegionBackendServiceRequest from google.cloud.compute_v1.types.compute import InsertRegionCommitmentRequest @@ -752,6 +827,10 @@ from google.cloud.compute_v1.types.compute import InstanceProperties from google.cloud.compute_v1.types.compute import InstanceReference from google.cloud.compute_v1.types.compute import InstancesAddResourcePoliciesRequest +from google.cloud.compute_v1.types.compute import InstancesGetEffectiveFirewallsResponse +from google.cloud.compute_v1.types.compute import ( + InstancesGetEffectiveFirewallsResponseEffectiveFirewallPolicy, +) from google.cloud.compute_v1.types.compute import InstancesRemoveResourcePoliciesRequest from google.cloud.compute_v1.types.compute import InstancesScopedList from google.cloud.compute_v1.types.compute import InstancesSetLabelsRequest @@ -795,6 +874,7 @@ from google.cloud.compute_v1.types.compute import LicensesListResponse from google.cloud.compute_v1.types.compute import ListAcceleratorTypesRequest from google.cloud.compute_v1.types.compute import ListAddressesRequest +from google.cloud.compute_v1.types.compute import ListAssociationsFirewallPolicyRequest from google.cloud.compute_v1.types.compute import ListAutoscalersRequest from google.cloud.compute_v1.types.compute import ( ListAvailableFeaturesSslPoliciesRequest, @@ -808,6 +888,7 @@ ListErrorsRegionInstanceGroupManagersRequest, ) from google.cloud.compute_v1.types.compute import ListExternalVpnGatewaysRequest +from google.cloud.compute_v1.types.compute import ListFirewallPoliciesRequest from google.cloud.compute_v1.types.compute import ListFirewallsRequest from google.cloud.compute_v1.types.compute import ListForwardingRulesRequest from google.cloud.compute_v1.types.compute import ListGlobalAddressesRequest @@ -817,6 +898,9 @@ from google.cloud.compute_v1.types.compute import ( ListGlobalOrganizationOperationsRequest, ) +from google.cloud.compute_v1.types.compute import ( + ListGlobalPublicDelegatedPrefixesRequest, +) from google.cloud.compute_v1.types.compute import ListHealthChecksRequest from google.cloud.compute_v1.types.compute import ListImagesRequest from google.cloud.compute_v1.types.compute import ListInstanceGroupManagersRequest @@ -861,6 +945,8 @@ from google.cloud.compute_v1.types.compute import ( ListPreconfiguredExpressionSetsSecurityPoliciesRequest, ) +from google.cloud.compute_v1.types.compute import ListPublicAdvertisedPrefixesRequest +from google.cloud.compute_v1.types.compute import ListPublicDelegatedPrefixesRequest from google.cloud.compute_v1.types.compute import ListReferrersInstancesRequest from google.cloud.compute_v1.types.compute import ListRegionAutoscalersRequest from google.cloud.compute_v1.types.compute import ListRegionBackendServicesRequest @@ -904,6 +990,8 @@ from google.cloud.compute_v1.types.compute import ListZoneOperationsRequest from google.cloud.compute_v1.types.compute import ListZonesRequest from google.cloud.compute_v1.types.compute import LocalDisk +from google.cloud.compute_v1.types.compute import LocationPolicy +from google.cloud.compute_v1.types.compute import LocationPolicyLocation from google.cloud.compute_v1.types.compute import LogConfig from google.cloud.compute_v1.types.compute import LogConfigCloudAuditOptions from google.cloud.compute_v1.types.compute import LogConfigCounterOptions @@ -921,6 +1009,7 @@ from google.cloud.compute_v1.types.compute import MetadataFilter from google.cloud.compute_v1.types.compute import MetadataFilterLabelMatch from google.cloud.compute_v1.types.compute import MoveDiskProjectRequest +from google.cloud.compute_v1.types.compute import MoveFirewallPolicyRequest from google.cloud.compute_v1.types.compute import MoveInstanceProjectRequest from google.cloud.compute_v1.types.compute import NamedPort from google.cloud.compute_v1.types.compute import Network @@ -950,6 +1039,10 @@ from google.cloud.compute_v1.types.compute import NetworkPeering from google.cloud.compute_v1.types.compute import NetworkRoutingConfig from google.cloud.compute_v1.types.compute import NetworksAddPeeringRequest +from google.cloud.compute_v1.types.compute import NetworksGetEffectiveFirewallsResponse +from google.cloud.compute_v1.types.compute import ( + NetworksGetEffectiveFirewallsResponseEffectiveFirewallPolicy, +) from google.cloud.compute_v1.types.compute import NetworksRemovePeeringRequest from google.cloud.compute_v1.types.compute import NetworksUpdatePeeringRequest from google.cloud.compute_v1.types.compute import NodeGroup @@ -997,9 +1090,13 @@ from google.cloud.compute_v1.types.compute import PatchAutoscalerRequest from google.cloud.compute_v1.types.compute import PatchBackendBucketRequest from google.cloud.compute_v1.types.compute import PatchBackendServiceRequest +from google.cloud.compute_v1.types.compute import PatchFirewallPolicyRequest from google.cloud.compute_v1.types.compute import PatchFirewallRequest from google.cloud.compute_v1.types.compute import PatchForwardingRuleRequest from google.cloud.compute_v1.types.compute import PatchGlobalForwardingRuleRequest +from google.cloud.compute_v1.types.compute import ( + PatchGlobalPublicDelegatedPrefixeRequest, +) from google.cloud.compute_v1.types.compute import PatchHealthCheckRequest from google.cloud.compute_v1.types.compute import PatchImageRequest from google.cloud.compute_v1.types.compute import PatchInstanceGroupManagerRequest @@ -1014,6 +1111,8 @@ from google.cloud.compute_v1.types.compute import ( PatchPerInstanceConfigsRegionInstanceGroupManagerRequest, ) +from google.cloud.compute_v1.types.compute import PatchPublicAdvertisedPrefixeRequest +from google.cloud.compute_v1.types.compute import PatchPublicDelegatedPrefixeRequest from google.cloud.compute_v1.types.compute import PatchRegionAutoscalerRequest from google.cloud.compute_v1.types.compute import PatchRegionBackendServiceRequest from google.cloud.compute_v1.types.compute import PatchRegionHealthCheckRequest @@ -1021,12 +1120,14 @@ from google.cloud.compute_v1.types.compute import PatchRegionInstanceGroupManagerRequest from google.cloud.compute_v1.types.compute import PatchRegionUrlMapRequest from google.cloud.compute_v1.types.compute import PatchRouterRequest +from google.cloud.compute_v1.types.compute import PatchRuleFirewallPolicyRequest from google.cloud.compute_v1.types.compute import PatchRuleSecurityPolicyRequest from google.cloud.compute_v1.types.compute import PatchSecurityPolicyRequest from google.cloud.compute_v1.types.compute import PatchSslPolicyRequest from google.cloud.compute_v1.types.compute import PatchSubnetworkRequest from google.cloud.compute_v1.types.compute import PatchTargetGrpcProxyRequest from google.cloud.compute_v1.types.compute import PatchTargetHttpProxyRequest +from google.cloud.compute_v1.types.compute import PatchTargetHttpsProxyRequest from google.cloud.compute_v1.types.compute import PatchUrlMapRequest from google.cloud.compute_v1.types.compute import PathMatcher from google.cloud.compute_v1.types.compute import PathRule @@ -1042,6 +1143,18 @@ from google.cloud.compute_v1.types.compute import ProjectsGetXpnResources from google.cloud.compute_v1.types.compute import ProjectsListXpnHostsRequest from google.cloud.compute_v1.types.compute import ProjectsSetDefaultNetworkTierRequest +from google.cloud.compute_v1.types.compute import PublicAdvertisedPrefix +from google.cloud.compute_v1.types.compute import PublicAdvertisedPrefixList +from google.cloud.compute_v1.types.compute import ( + PublicAdvertisedPrefixPublicDelegatedPrefix, +) +from google.cloud.compute_v1.types.compute import PublicDelegatedPrefix +from google.cloud.compute_v1.types.compute import PublicDelegatedPrefixAggregatedList +from google.cloud.compute_v1.types.compute import PublicDelegatedPrefixesScopedList +from google.cloud.compute_v1.types.compute import PublicDelegatedPrefixList +from google.cloud.compute_v1.types.compute import ( + PublicDelegatedPrefixPublicDelegatedSubPrefix, +) from google.cloud.compute_v1.types.compute import Quota from google.cloud.compute_v1.types.compute import RawDisk from google.cloud.compute_v1.types.compute import ( @@ -1114,6 +1227,7 @@ RegionTargetHttpsProxiesSetSslCertificatesRequest, ) from google.cloud.compute_v1.types.compute import RegionUrlMapsValidateRequest +from google.cloud.compute_v1.types.compute import RemoveAssociationFirewallPolicyRequest from google.cloud.compute_v1.types.compute import RemoveHealthCheckTargetPoolRequest from google.cloud.compute_v1.types.compute import RemoveInstancesInstanceGroupRequest from google.cloud.compute_v1.types.compute import RemoveInstanceTargetPoolRequest @@ -1123,6 +1237,7 @@ from google.cloud.compute_v1.types.compute import ( RemoveResourcePoliciesRegionDiskRequest, ) +from google.cloud.compute_v1.types.compute import RemoveRuleFirewallPolicyRequest from google.cloud.compute_v1.types.compute import RemoveRuleSecurityPolicyRequest from google.cloud.compute_v1.types.compute import RequestMirrorPolicy from google.cloud.compute_v1.types.compute import Reservation @@ -1147,7 +1262,15 @@ from google.cloud.compute_v1.types.compute import ResourcePolicyDailyCycle from google.cloud.compute_v1.types.compute import ResourcePolicyGroupPlacementPolicy from google.cloud.compute_v1.types.compute import ResourcePolicyHourlyCycle +from google.cloud.compute_v1.types.compute import ResourcePolicyInstanceSchedulePolicy +from google.cloud.compute_v1.types.compute import ( + ResourcePolicyInstanceSchedulePolicySchedule, +) from google.cloud.compute_v1.types.compute import ResourcePolicyList +from google.cloud.compute_v1.types.compute import ResourcePolicyResourceStatus +from google.cloud.compute_v1.types.compute import ( + ResourcePolicyResourceStatusInstanceSchedulePolicyStatus, +) from google.cloud.compute_v1.types.compute import ResourcePolicySnapshotSchedulePolicy from google.cloud.compute_v1.types.compute import ( ResourcePolicySnapshotSchedulePolicyRetentionPolicy, @@ -1179,6 +1302,7 @@ from google.cloud.compute_v1.types.compute import RouterStatusNatStatus from google.cloud.compute_v1.types.compute import RouterStatusResponse from google.cloud.compute_v1.types.compute import Rule +from google.cloud.compute_v1.types.compute import ScalingScheduleStatus from google.cloud.compute_v1.types.compute import Scheduling from google.cloud.compute_v1.types.compute import SchedulingNodeAffinity from google.cloud.compute_v1.types.compute import ScratchDisks @@ -1207,6 +1331,7 @@ from google.cloud.compute_v1.types.compute import SetDeletionProtectionInstanceRequest from google.cloud.compute_v1.types.compute import SetDiskAutoDeleteInstanceRequest from google.cloud.compute_v1.types.compute import SetIamPolicyDiskRequest +from google.cloud.compute_v1.types.compute import SetIamPolicyFirewallPolicyRequest from google.cloud.compute_v1.types.compute import SetIamPolicyImageRequest from google.cloud.compute_v1.types.compute import SetIamPolicyInstanceRequest from google.cloud.compute_v1.types.compute import SetIamPolicyInstanceTemplateRequest @@ -1226,6 +1351,8 @@ ) from google.cloud.compute_v1.types.compute import SetLabelsDiskRequest from google.cloud.compute_v1.types.compute import SetLabelsExternalVpnGatewayRequest +from google.cloud.compute_v1.types.compute import SetLabelsForwardingRuleRequest +from google.cloud.compute_v1.types.compute import SetLabelsGlobalForwardingRuleRequest from google.cloud.compute_v1.types.compute import SetLabelsImageRequest from google.cloud.compute_v1.types.compute import SetLabelsInstanceRequest from google.cloud.compute_v1.types.compute import SetLabelsRegionDiskRequest @@ -1376,6 +1503,9 @@ from google.cloud.compute_v1.types.compute import ( TestIamPermissionsExternalVpnGatewayRequest, ) +from google.cloud.compute_v1.types.compute import ( + TestIamPermissionsFirewallPolicyRequest, +) from google.cloud.compute_v1.types.compute import TestIamPermissionsImageRequest from google.cloud.compute_v1.types.compute import TestIamPermissionsInstanceRequest from google.cloud.compute_v1.types.compute import ( @@ -1434,6 +1564,7 @@ from google.cloud.compute_v1.types.compute import UrlMapsValidateRequest from google.cloud.compute_v1.types.compute import UrlMapsValidateResponse from google.cloud.compute_v1.types.compute import UrlMapTest +from google.cloud.compute_v1.types.compute import UrlMapTestHeader from google.cloud.compute_v1.types.compute import UrlMapValidationResult from google.cloud.compute_v1.types.compute import UrlRewrite from google.cloud.compute_v1.types.compute import UsableSubnetwork @@ -1487,6 +1618,7 @@ "DisksClient", "DiskTypesClient", "ExternalVpnGatewaysClient", + "FirewallPoliciesClient", "FirewallsClient", "ForwardingRulesClient", "GlobalAddressesClient", @@ -1494,6 +1626,7 @@ "GlobalNetworkEndpointGroupsClient", "GlobalOperationsClient", "GlobalOrganizationOperationsClient", + "GlobalPublicDelegatedPrefixesClient", "HealthChecksClient", "ImagesClient", "InstanceGroupManagersClient", @@ -1513,6 +1646,8 @@ "NodeTypesClient", "PacketMirroringsClient", "ProjectsClient", + "PublicAdvertisedPrefixesClient", + "PublicDelegatedPrefixesClient", "RegionAutoscalersClient", "RegionBackendServicesClient", "RegionCommitmentsClient", @@ -1522,6 +1657,7 @@ "RegionHealthCheckServicesClient", "RegionInstanceGroupManagersClient", "RegionInstanceGroupsClient", + "RegionInstancesClient", "RegionNetworkEndpointGroupsClient", "RegionNotificationEndpointsClient", "RegionOperationsClient", @@ -1562,6 +1698,7 @@ "AcceleratorTypesScopedList", "AccessConfig", "AddAccessConfigInstanceRequest", + "AddAssociationFirewallPolicyRequest", "AddHealthCheckTargetPoolRequest", "AddInstancesInstanceGroupRequest", "AddInstanceTargetPoolRequest", @@ -1574,9 +1711,11 @@ "AddressAggregatedList", "AddressesScopedList", "AddressList", + "AddRuleFirewallPolicyRequest", "AddRuleSecurityPolicyRequest", "AddSignedUrlKeyBackendBucketRequest", "AddSignedUrlKeyBackendServiceRequest", + "AdvancedMachineFeatures", "AggregatedListAcceleratorTypesRequest", "AggregatedListAddressesRequest", "AggregatedListAutoscalersRequest", @@ -1596,6 +1735,7 @@ "AggregatedListNodeTemplatesRequest", "AggregatedListNodeTypesRequest", "AggregatedListPacketMirroringsRequest", + "AggregatedListPublicDelegatedPrefixesRequest", "AggregatedListRegionCommitmentsRequest", "AggregatedListReservationsRequest", "AggregatedListResourcePoliciesRequest", @@ -1635,13 +1775,18 @@ "AutoscalingPolicyCustomMetricUtilization", "AutoscalingPolicyLoadBalancingUtilization", "AutoscalingPolicyScaleInControl", + "AutoscalingPolicyScalingSchedule", "Backend", "BackendBucket", "BackendBucketCdnPolicy", + "BackendBucketCdnPolicyBypassCacheOnRequestHeader", + "BackendBucketCdnPolicyNegativeCachingPolicy", "BackendBucketList", "BackendService", "BackendServiceAggregatedList", "BackendServiceCdnPolicy", + "BackendServiceCdnPolicyBypassCacheOnRequestHeader", + "BackendServiceCdnPolicyNegativeCachingPolicy", "BackendServiceFailoverPolicy", "BackendServiceGroupHealth", "BackendServiceIAP", @@ -1650,9 +1795,14 @@ "BackendServiceReference", "BackendServicesScopedList", "Binding", + "BulkInsertInstanceRequest", + "BulkInsertInstanceResource", + "BulkInsertInstanceResourcePerInstanceProperties", + "BulkInsertRegionInstanceRequest", "CacheInvalidationRule", "CacheKeyPolicy", "CircuitBreakers", + "CloneRulesFirewallPolicyRequest", "Commitment", "CommitmentAggregatedList", "CommitmentList", @@ -1677,6 +1827,7 @@ "DeleteBackendServiceRequest", "DeleteDiskRequest", "DeleteExternalVpnGatewayRequest", + "DeleteFirewallPolicyRequest", "DeleteFirewallRequest", "DeleteForwardingRuleRequest", "DeleteGlobalAddressRequest", @@ -1686,6 +1837,7 @@ "DeleteGlobalOperationResponse", "DeleteGlobalOrganizationOperationRequest", "DeleteGlobalOrganizationOperationResponse", + "DeleteGlobalPublicDelegatedPrefixeRequest", "DeleteHealthCheckRequest", "DeleteImageRequest", "DeleteInstanceGroupManagerRequest", @@ -1705,6 +1857,8 @@ "DeletePacketMirroringRequest", "DeletePerInstanceConfigsInstanceGroupManagerRequest", "DeletePerInstanceConfigsRegionInstanceGroupManagerRequest", + "DeletePublicAdvertisedPrefixeRequest", + "DeletePublicDelegatedPrefixeRequest", "DeleteRegionAutoscalerRequest", "DeleteRegionBackendServiceRequest", "DeleteRegionDiskRequest", @@ -1783,21 +1937,33 @@ "Firewall", "FirewallList", "FirewallLogConfig", + "FirewallPoliciesListAssociationsResponse", + "FirewallPolicy", + "FirewallPolicyAssociation", + "FirewallPolicyList", + "FirewallPolicyRule", + "FirewallPolicyRuleMatcher", + "FirewallPolicyRuleMatcherLayer4Config", "FixedOrPercent", "ForwardingRule", "ForwardingRuleAggregatedList", "ForwardingRuleList", "ForwardingRuleReference", + "ForwardingRuleServiceDirectoryRegistration", "ForwardingRulesScopedList", "GetAcceleratorTypeRequest", "GetAddressRequest", + "GetAssociationFirewallPolicyRequest", "GetAutoscalerRequest", "GetBackendBucketRequest", "GetBackendServiceRequest", "GetDiagnosticsInterconnectRequest", "GetDiskRequest", "GetDiskTypeRequest", + "GetEffectiveFirewallsInstanceRequest", + "GetEffectiveFirewallsNetworkRequest", "GetExternalVpnGatewayRequest", + "GetFirewallPolicyRequest", "GetFirewallRequest", "GetForwardingRuleRequest", "GetFromFamilyImageRequest", @@ -1806,12 +1972,14 @@ "GetGlobalNetworkEndpointGroupRequest", "GetGlobalOperationRequest", "GetGlobalOrganizationOperationRequest", + "GetGlobalPublicDelegatedPrefixeRequest", "GetGuestAttributesInstanceRequest", "GetHealthBackendServiceRequest", "GetHealthCheckRequest", "GetHealthRegionBackendServiceRequest", "GetHealthTargetPoolRequest", "GetIamPolicyDiskRequest", + "GetIamPolicyFirewallPolicyRequest", "GetIamPolicyImageRequest", "GetIamPolicyInstanceRequest", "GetIamPolicyInstanceTemplateRequest", @@ -1842,6 +2010,8 @@ "GetNodeTypeRequest", "GetPacketMirroringRequest", "GetProjectRequest", + "GetPublicAdvertisedPrefixeRequest", + "GetPublicDelegatedPrefixeRequest", "GetRegionAutoscalerRequest", "GetRegionBackendServiceRequest", "GetRegionCommitmentRequest", @@ -1864,6 +2034,7 @@ "GetRouteRequest", "GetRouterRequest", "GetRouterStatusRouterRequest", + "GetRuleFirewallPolicyRequest", "GetRuleSecurityPolicyRequest", "GetScreenshotInstanceRequest", "GetSecurityPolicyRequest", @@ -1891,6 +2062,7 @@ "GetZoneRequest", "GlobalNetworkEndpointGroupsAttachEndpointsRequest", "GlobalNetworkEndpointGroupsDetachEndpointsRequest", + "GlobalOrganizationSetPolicyRequest", "GlobalSetLabelsRequest", "GlobalSetPolicyRequest", "GRPCHealthCheck", @@ -1934,11 +2106,13 @@ "InsertBackendServiceRequest", "InsertDiskRequest", "InsertExternalVpnGatewayRequest", + "InsertFirewallPolicyRequest", "InsertFirewallRequest", "InsertForwardingRuleRequest", "InsertGlobalAddressRequest", "InsertGlobalForwardingRuleRequest", "InsertGlobalNetworkEndpointGroupRequest", + "InsertGlobalPublicDelegatedPrefixeRequest", "InsertHealthCheckRequest", "InsertImageRequest", "InsertInstanceGroupManagerRequest", @@ -1953,6 +2127,8 @@ "InsertNodeGroupRequest", "InsertNodeTemplateRequest", "InsertPacketMirroringRequest", + "InsertPublicAdvertisedPrefixeRequest", + "InsertPublicDelegatedPrefixeRequest", "InsertRegionAutoscalerRequest", "InsertRegionBackendServiceRequest", "InsertRegionCommitmentRequest", @@ -2030,6 +2206,8 @@ "InstanceProperties", "InstanceReference", "InstancesAddResourcePoliciesRequest", + "InstancesGetEffectiveFirewallsResponse", + "InstancesGetEffectiveFirewallsResponseEffectiveFirewallPolicy", "InstancesRemoveResourcePoliciesRequest", "InstancesScopedList", "InstancesSetLabelsRequest", @@ -2071,6 +2249,7 @@ "LicensesListResponse", "ListAcceleratorTypesRequest", "ListAddressesRequest", + "ListAssociationsFirewallPolicyRequest", "ListAutoscalersRequest", "ListAvailableFeaturesSslPoliciesRequest", "ListBackendBucketsRequest", @@ -2080,6 +2259,7 @@ "ListErrorsInstanceGroupManagersRequest", "ListErrorsRegionInstanceGroupManagersRequest", "ListExternalVpnGatewaysRequest", + "ListFirewallPoliciesRequest", "ListFirewallsRequest", "ListForwardingRulesRequest", "ListGlobalAddressesRequest", @@ -2087,6 +2267,7 @@ "ListGlobalNetworkEndpointGroupsRequest", "ListGlobalOperationsRequest", "ListGlobalOrganizationOperationsRequest", + "ListGlobalPublicDelegatedPrefixesRequest", "ListHealthChecksRequest", "ListImagesRequest", "ListInstanceGroupManagersRequest", @@ -2115,6 +2296,8 @@ "ListPerInstanceConfigsInstanceGroupManagersRequest", "ListPerInstanceConfigsRegionInstanceGroupManagersRequest", "ListPreconfiguredExpressionSetsSecurityPoliciesRequest", + "ListPublicAdvertisedPrefixesRequest", + "ListPublicDelegatedPrefixesRequest", "ListReferrersInstancesRequest", "ListRegionAutoscalersRequest", "ListRegionBackendServicesRequest", @@ -2158,6 +2341,8 @@ "ListZoneOperationsRequest", "ListZonesRequest", "LocalDisk", + "LocationPolicy", + "LocationPolicyLocation", "LogConfig", "LogConfigCloudAuditOptions", "LogConfigCounterOptions", @@ -2175,6 +2360,7 @@ "MetadataFilter", "MetadataFilterLabelMatch", "MoveDiskProjectRequest", + "MoveFirewallPolicyRequest", "MoveInstanceProjectRequest", "NamedPort", "Network", @@ -2196,6 +2382,8 @@ "NetworkPeering", "NetworkRoutingConfig", "NetworksAddPeeringRequest", + "NetworksGetEffectiveFirewallsResponse", + "NetworksGetEffectiveFirewallsResponseEffectiveFirewallPolicy", "NetworksRemovePeeringRequest", "NetworksUpdatePeeringRequest", "NodeGroup", @@ -2239,9 +2427,11 @@ "PatchAutoscalerRequest", "PatchBackendBucketRequest", "PatchBackendServiceRequest", + "PatchFirewallPolicyRequest", "PatchFirewallRequest", "PatchForwardingRuleRequest", "PatchGlobalForwardingRuleRequest", + "PatchGlobalPublicDelegatedPrefixeRequest", "PatchHealthCheckRequest", "PatchImageRequest", "PatchInstanceGroupManagerRequest", @@ -2252,6 +2442,8 @@ "PatchPacketMirroringRequest", "PatchPerInstanceConfigsInstanceGroupManagerRequest", "PatchPerInstanceConfigsRegionInstanceGroupManagerRequest", + "PatchPublicAdvertisedPrefixeRequest", + "PatchPublicDelegatedPrefixeRequest", "PatchRegionAutoscalerRequest", "PatchRegionBackendServiceRequest", "PatchRegionHealthCheckRequest", @@ -2259,12 +2451,14 @@ "PatchRegionInstanceGroupManagerRequest", "PatchRegionUrlMapRequest", "PatchRouterRequest", + "PatchRuleFirewallPolicyRequest", "PatchRuleSecurityPolicyRequest", "PatchSecurityPolicyRequest", "PatchSslPolicyRequest", "PatchSubnetworkRequest", "PatchTargetGrpcProxyRequest", "PatchTargetHttpProxyRequest", + "PatchTargetHttpsProxyRequest", "PatchUrlMapRequest", "PathMatcher", "PathRule", @@ -2280,6 +2474,14 @@ "ProjectsGetXpnResources", "ProjectsListXpnHostsRequest", "ProjectsSetDefaultNetworkTierRequest", + "PublicAdvertisedPrefix", + "PublicAdvertisedPrefixList", + "PublicAdvertisedPrefixPublicDelegatedPrefix", + "PublicDelegatedPrefix", + "PublicDelegatedPrefixAggregatedList", + "PublicDelegatedPrefixesScopedList", + "PublicDelegatedPrefixList", + "PublicDelegatedPrefixPublicDelegatedSubPrefix", "Quota", "RawDisk", "RecreateInstancesInstanceGroupManagerRequest", @@ -2314,6 +2516,7 @@ "RegionSetPolicyRequest", "RegionTargetHttpsProxiesSetSslCertificatesRequest", "RegionUrlMapsValidateRequest", + "RemoveAssociationFirewallPolicyRequest", "RemoveHealthCheckTargetPoolRequest", "RemoveInstancesInstanceGroupRequest", "RemoveInstanceTargetPoolRequest", @@ -2321,6 +2524,7 @@ "RemoveResourcePoliciesDiskRequest", "RemoveResourcePoliciesInstanceRequest", "RemoveResourcePoliciesRegionDiskRequest", + "RemoveRuleFirewallPolicyRequest", "RemoveRuleSecurityPolicyRequest", "RequestMirrorPolicy", "Reservation", @@ -2343,7 +2547,11 @@ "ResourcePolicyDailyCycle", "ResourcePolicyGroupPlacementPolicy", "ResourcePolicyHourlyCycle", + "ResourcePolicyInstanceSchedulePolicy", + "ResourcePolicyInstanceSchedulePolicySchedule", "ResourcePolicyList", + "ResourcePolicyResourceStatus", + "ResourcePolicyResourceStatusInstanceSchedulePolicyStatus", "ResourcePolicySnapshotSchedulePolicy", "ResourcePolicySnapshotSchedulePolicyRetentionPolicy", "ResourcePolicySnapshotSchedulePolicySchedule", @@ -2369,6 +2577,7 @@ "RouterStatusNatStatus", "RouterStatusResponse", "Rule", + "ScalingScheduleStatus", "Scheduling", "SchedulingNodeAffinity", "ScratchDisks", @@ -2393,6 +2602,7 @@ "SetDeletionProtectionInstanceRequest", "SetDiskAutoDeleteInstanceRequest", "SetIamPolicyDiskRequest", + "SetIamPolicyFirewallPolicyRequest", "SetIamPolicyImageRequest", "SetIamPolicyInstanceRequest", "SetIamPolicyInstanceTemplateRequest", @@ -2408,6 +2618,8 @@ "SetInstanceTemplateRegionInstanceGroupManagerRequest", "SetLabelsDiskRequest", "SetLabelsExternalVpnGatewayRequest", + "SetLabelsForwardingRuleRequest", + "SetLabelsGlobalForwardingRuleRequest", "SetLabelsImageRequest", "SetLabelsInstanceRequest", "SetLabelsRegionDiskRequest", @@ -2522,6 +2734,7 @@ "TestFailure", "TestIamPermissionsDiskRequest", "TestIamPermissionsExternalVpnGatewayRequest", + "TestIamPermissionsFirewallPolicyRequest", "TestIamPermissionsImageRequest", "TestIamPermissionsInstanceRequest", "TestIamPermissionsInstanceTemplateRequest", @@ -2566,6 +2779,7 @@ "UrlMapsValidateRequest", "UrlMapsValidateResponse", "UrlMapTest", + "UrlMapTestHeader", "UrlMapValidationResult", "UrlRewrite", "UsableSubnetwork", 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 57a5c4771a66..f1e24b94a0ce 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py @@ -22,6 +22,7 @@ from .services.disks import DisksClient from .services.disk_types import DiskTypesClient from .services.external_vpn_gateways import ExternalVpnGatewaysClient +from .services.firewall_policies import FirewallPoliciesClient from .services.firewalls import FirewallsClient from .services.forwarding_rules import ForwardingRulesClient from .services.global_addresses import GlobalAddressesClient @@ -29,6 +30,9 @@ from .services.global_network_endpoint_groups import GlobalNetworkEndpointGroupsClient from .services.global_operations import GlobalOperationsClient from .services.global_organization_operations import GlobalOrganizationOperationsClient +from .services.global_public_delegated_prefixes import ( + GlobalPublicDelegatedPrefixesClient, +) from .services.health_checks import HealthChecksClient from .services.images import ImagesClient from .services.instance_group_managers import InstanceGroupManagersClient @@ -48,6 +52,8 @@ from .services.node_types import NodeTypesClient from .services.packet_mirrorings import PacketMirroringsClient from .services.projects import ProjectsClient +from .services.public_advertised_prefixes import PublicAdvertisedPrefixesClient +from .services.public_delegated_prefixes import PublicDelegatedPrefixesClient from .services.region_autoscalers import RegionAutoscalersClient from .services.region_backend_services import RegionBackendServicesClient from .services.region_commitments import RegionCommitmentsClient @@ -57,6 +63,7 @@ from .services.region_health_check_services import RegionHealthCheckServicesClient from .services.region_instance_group_managers import RegionInstanceGroupManagersClient from .services.region_instance_groups import RegionInstanceGroupsClient +from .services.region_instances import RegionInstancesClient from .services.region_network_endpoint_groups import RegionNetworkEndpointGroupsClient from .services.region_notification_endpoints import RegionNotificationEndpointsClient from .services.region_operations import RegionOperationsClient @@ -98,6 +105,7 @@ from .types.compute import AcceleratorTypesScopedList from .types.compute import AccessConfig from .types.compute import AddAccessConfigInstanceRequest +from .types.compute import AddAssociationFirewallPolicyRequest from .types.compute import AddHealthCheckTargetPoolRequest from .types.compute import AddInstancesInstanceGroupRequest from .types.compute import AddInstanceTargetPoolRequest @@ -110,9 +118,11 @@ from .types.compute import AddressAggregatedList from .types.compute import AddressesScopedList from .types.compute import AddressList +from .types.compute import AddRuleFirewallPolicyRequest from .types.compute import AddRuleSecurityPolicyRequest from .types.compute import AddSignedUrlKeyBackendBucketRequest from .types.compute import AddSignedUrlKeyBackendServiceRequest +from .types.compute import AdvancedMachineFeatures from .types.compute import AggregatedListAcceleratorTypesRequest from .types.compute import AggregatedListAddressesRequest from .types.compute import AggregatedListAutoscalersRequest @@ -132,6 +142,7 @@ from .types.compute import AggregatedListNodeTemplatesRequest from .types.compute import AggregatedListNodeTypesRequest from .types.compute import AggregatedListPacketMirroringsRequest +from .types.compute import AggregatedListPublicDelegatedPrefixesRequest from .types.compute import AggregatedListRegionCommitmentsRequest from .types.compute import AggregatedListReservationsRequest from .types.compute import AggregatedListResourcePoliciesRequest @@ -173,13 +184,18 @@ from .types.compute import AutoscalingPolicyCustomMetricUtilization from .types.compute import AutoscalingPolicyLoadBalancingUtilization from .types.compute import AutoscalingPolicyScaleInControl +from .types.compute import AutoscalingPolicyScalingSchedule from .types.compute import Backend from .types.compute import BackendBucket from .types.compute import BackendBucketCdnPolicy +from .types.compute import BackendBucketCdnPolicyBypassCacheOnRequestHeader +from .types.compute import BackendBucketCdnPolicyNegativeCachingPolicy from .types.compute import BackendBucketList from .types.compute import BackendService from .types.compute import BackendServiceAggregatedList from .types.compute import BackendServiceCdnPolicy +from .types.compute import BackendServiceCdnPolicyBypassCacheOnRequestHeader +from .types.compute import BackendServiceCdnPolicyNegativeCachingPolicy from .types.compute import BackendServiceFailoverPolicy from .types.compute import BackendServiceGroupHealth from .types.compute import BackendServiceIAP @@ -188,9 +204,14 @@ from .types.compute import BackendServiceReference from .types.compute import BackendServicesScopedList from .types.compute import Binding +from .types.compute import BulkInsertInstanceRequest +from .types.compute import BulkInsertInstanceResource +from .types.compute import BulkInsertInstanceResourcePerInstanceProperties +from .types.compute import BulkInsertRegionInstanceRequest from .types.compute import CacheInvalidationRule from .types.compute import CacheKeyPolicy from .types.compute import CircuitBreakers +from .types.compute import CloneRulesFirewallPolicyRequest from .types.compute import Commitment from .types.compute import CommitmentAggregatedList from .types.compute import CommitmentList @@ -215,6 +236,7 @@ from .types.compute import DeleteBackendServiceRequest from .types.compute import DeleteDiskRequest from .types.compute import DeleteExternalVpnGatewayRequest +from .types.compute import DeleteFirewallPolicyRequest from .types.compute import DeleteFirewallRequest from .types.compute import DeleteForwardingRuleRequest from .types.compute import DeleteGlobalAddressRequest @@ -224,6 +246,7 @@ from .types.compute import DeleteGlobalOperationResponse from .types.compute import DeleteGlobalOrganizationOperationRequest from .types.compute import DeleteGlobalOrganizationOperationResponse +from .types.compute import DeleteGlobalPublicDelegatedPrefixeRequest from .types.compute import DeleteHealthCheckRequest from .types.compute import DeleteImageRequest from .types.compute import DeleteInstanceGroupManagerRequest @@ -243,6 +266,8 @@ from .types.compute import DeletePacketMirroringRequest from .types.compute import DeletePerInstanceConfigsInstanceGroupManagerRequest from .types.compute import DeletePerInstanceConfigsRegionInstanceGroupManagerRequest +from .types.compute import DeletePublicAdvertisedPrefixeRequest +from .types.compute import DeletePublicDelegatedPrefixeRequest from .types.compute import DeleteRegionAutoscalerRequest from .types.compute import DeleteRegionBackendServiceRequest from .types.compute import DeleteRegionDiskRequest @@ -321,21 +346,33 @@ from .types.compute import Firewall from .types.compute import FirewallList from .types.compute import FirewallLogConfig +from .types.compute import FirewallPoliciesListAssociationsResponse +from .types.compute import FirewallPolicy +from .types.compute import FirewallPolicyAssociation +from .types.compute import FirewallPolicyList +from .types.compute import FirewallPolicyRule +from .types.compute import FirewallPolicyRuleMatcher +from .types.compute import FirewallPolicyRuleMatcherLayer4Config from .types.compute import FixedOrPercent from .types.compute import ForwardingRule from .types.compute import ForwardingRuleAggregatedList from .types.compute import ForwardingRuleList from .types.compute import ForwardingRuleReference +from .types.compute import ForwardingRuleServiceDirectoryRegistration from .types.compute import ForwardingRulesScopedList from .types.compute import GetAcceleratorTypeRequest from .types.compute import GetAddressRequest +from .types.compute import GetAssociationFirewallPolicyRequest from .types.compute import GetAutoscalerRequest from .types.compute import GetBackendBucketRequest from .types.compute import GetBackendServiceRequest from .types.compute import GetDiagnosticsInterconnectRequest from .types.compute import GetDiskRequest from .types.compute import GetDiskTypeRequest +from .types.compute import GetEffectiveFirewallsInstanceRequest +from .types.compute import GetEffectiveFirewallsNetworkRequest from .types.compute import GetExternalVpnGatewayRequest +from .types.compute import GetFirewallPolicyRequest from .types.compute import GetFirewallRequest from .types.compute import GetForwardingRuleRequest from .types.compute import GetFromFamilyImageRequest @@ -344,12 +381,14 @@ from .types.compute import GetGlobalNetworkEndpointGroupRequest from .types.compute import GetGlobalOperationRequest from .types.compute import GetGlobalOrganizationOperationRequest +from .types.compute import GetGlobalPublicDelegatedPrefixeRequest from .types.compute import GetGuestAttributesInstanceRequest from .types.compute import GetHealthBackendServiceRequest from .types.compute import GetHealthCheckRequest from .types.compute import GetHealthRegionBackendServiceRequest from .types.compute import GetHealthTargetPoolRequest from .types.compute import GetIamPolicyDiskRequest +from .types.compute import GetIamPolicyFirewallPolicyRequest from .types.compute import GetIamPolicyImageRequest from .types.compute import GetIamPolicyInstanceRequest from .types.compute import GetIamPolicyInstanceTemplateRequest @@ -380,6 +419,8 @@ from .types.compute import GetNodeTypeRequest from .types.compute import GetPacketMirroringRequest from .types.compute import GetProjectRequest +from .types.compute import GetPublicAdvertisedPrefixeRequest +from .types.compute import GetPublicDelegatedPrefixeRequest from .types.compute import GetRegionAutoscalerRequest from .types.compute import GetRegionBackendServiceRequest from .types.compute import GetRegionCommitmentRequest @@ -402,6 +443,7 @@ from .types.compute import GetRouteRequest from .types.compute import GetRouterRequest from .types.compute import GetRouterStatusRouterRequest +from .types.compute import GetRuleFirewallPolicyRequest from .types.compute import GetRuleSecurityPolicyRequest from .types.compute import GetScreenshotInstanceRequest from .types.compute import GetSecurityPolicyRequest @@ -429,6 +471,7 @@ from .types.compute import GetZoneRequest from .types.compute import GlobalNetworkEndpointGroupsAttachEndpointsRequest from .types.compute import GlobalNetworkEndpointGroupsDetachEndpointsRequest +from .types.compute import GlobalOrganizationSetPolicyRequest from .types.compute import GlobalSetLabelsRequest from .types.compute import GlobalSetPolicyRequest from .types.compute import GRPCHealthCheck @@ -472,11 +515,13 @@ from .types.compute import InsertBackendServiceRequest from .types.compute import InsertDiskRequest from .types.compute import InsertExternalVpnGatewayRequest +from .types.compute import InsertFirewallPolicyRequest from .types.compute import InsertFirewallRequest from .types.compute import InsertForwardingRuleRequest from .types.compute import InsertGlobalAddressRequest from .types.compute import InsertGlobalForwardingRuleRequest from .types.compute import InsertGlobalNetworkEndpointGroupRequest +from .types.compute import InsertGlobalPublicDelegatedPrefixeRequest from .types.compute import InsertHealthCheckRequest from .types.compute import InsertImageRequest from .types.compute import InsertInstanceGroupManagerRequest @@ -491,6 +536,8 @@ from .types.compute import InsertNodeGroupRequest from .types.compute import InsertNodeTemplateRequest from .types.compute import InsertPacketMirroringRequest +from .types.compute import InsertPublicAdvertisedPrefixeRequest +from .types.compute import InsertPublicDelegatedPrefixeRequest from .types.compute import InsertRegionAutoscalerRequest from .types.compute import InsertRegionBackendServiceRequest from .types.compute import InsertRegionCommitmentRequest @@ -568,6 +615,8 @@ from .types.compute import InstanceProperties from .types.compute import InstanceReference from .types.compute import InstancesAddResourcePoliciesRequest +from .types.compute import InstancesGetEffectiveFirewallsResponse +from .types.compute import InstancesGetEffectiveFirewallsResponseEffectiveFirewallPolicy from .types.compute import InstancesRemoveResourcePoliciesRequest from .types.compute import InstancesScopedList from .types.compute import InstancesSetLabelsRequest @@ -609,6 +658,7 @@ from .types.compute import LicensesListResponse from .types.compute import ListAcceleratorTypesRequest from .types.compute import ListAddressesRequest +from .types.compute import ListAssociationsFirewallPolicyRequest from .types.compute import ListAutoscalersRequest from .types.compute import ListAvailableFeaturesSslPoliciesRequest from .types.compute import ListBackendBucketsRequest @@ -618,6 +668,7 @@ from .types.compute import ListErrorsInstanceGroupManagersRequest from .types.compute import ListErrorsRegionInstanceGroupManagersRequest from .types.compute import ListExternalVpnGatewaysRequest +from .types.compute import ListFirewallPoliciesRequest from .types.compute import ListFirewallsRequest from .types.compute import ListForwardingRulesRequest from .types.compute import ListGlobalAddressesRequest @@ -625,6 +676,7 @@ from .types.compute import ListGlobalNetworkEndpointGroupsRequest from .types.compute import ListGlobalOperationsRequest from .types.compute import ListGlobalOrganizationOperationsRequest +from .types.compute import ListGlobalPublicDelegatedPrefixesRequest from .types.compute import ListHealthChecksRequest from .types.compute import ListImagesRequest from .types.compute import ListInstanceGroupManagersRequest @@ -653,6 +705,8 @@ from .types.compute import ListPerInstanceConfigsInstanceGroupManagersRequest from .types.compute import ListPerInstanceConfigsRegionInstanceGroupManagersRequest from .types.compute import ListPreconfiguredExpressionSetsSecurityPoliciesRequest +from .types.compute import ListPublicAdvertisedPrefixesRequest +from .types.compute import ListPublicDelegatedPrefixesRequest from .types.compute import ListReferrersInstancesRequest from .types.compute import ListRegionAutoscalersRequest from .types.compute import ListRegionBackendServicesRequest @@ -696,6 +750,8 @@ from .types.compute import ListZoneOperationsRequest from .types.compute import ListZonesRequest from .types.compute import LocalDisk +from .types.compute import LocationPolicy +from .types.compute import LocationPolicyLocation from .types.compute import LogConfig from .types.compute import LogConfigCloudAuditOptions from .types.compute import LogConfigCounterOptions @@ -713,6 +769,7 @@ from .types.compute import MetadataFilter from .types.compute import MetadataFilterLabelMatch from .types.compute import MoveDiskProjectRequest +from .types.compute import MoveFirewallPolicyRequest from .types.compute import MoveInstanceProjectRequest from .types.compute import NamedPort from .types.compute import Network @@ -734,6 +791,8 @@ from .types.compute import NetworkPeering from .types.compute import NetworkRoutingConfig from .types.compute import NetworksAddPeeringRequest +from .types.compute import NetworksGetEffectiveFirewallsResponse +from .types.compute import NetworksGetEffectiveFirewallsResponseEffectiveFirewallPolicy from .types.compute import NetworksRemovePeeringRequest from .types.compute import NetworksUpdatePeeringRequest from .types.compute import NodeGroup @@ -777,9 +836,11 @@ from .types.compute import PatchAutoscalerRequest from .types.compute import PatchBackendBucketRequest from .types.compute import PatchBackendServiceRequest +from .types.compute import PatchFirewallPolicyRequest from .types.compute import PatchFirewallRequest from .types.compute import PatchForwardingRuleRequest from .types.compute import PatchGlobalForwardingRuleRequest +from .types.compute import PatchGlobalPublicDelegatedPrefixeRequest from .types.compute import PatchHealthCheckRequest from .types.compute import PatchImageRequest from .types.compute import PatchInstanceGroupManagerRequest @@ -790,6 +851,8 @@ from .types.compute import PatchPacketMirroringRequest from .types.compute import PatchPerInstanceConfigsInstanceGroupManagerRequest from .types.compute import PatchPerInstanceConfigsRegionInstanceGroupManagerRequest +from .types.compute import PatchPublicAdvertisedPrefixeRequest +from .types.compute import PatchPublicDelegatedPrefixeRequest from .types.compute import PatchRegionAutoscalerRequest from .types.compute import PatchRegionBackendServiceRequest from .types.compute import PatchRegionHealthCheckRequest @@ -797,12 +860,14 @@ from .types.compute import PatchRegionInstanceGroupManagerRequest from .types.compute import PatchRegionUrlMapRequest from .types.compute import PatchRouterRequest +from .types.compute import PatchRuleFirewallPolicyRequest from .types.compute import PatchRuleSecurityPolicyRequest from .types.compute import PatchSecurityPolicyRequest from .types.compute import PatchSslPolicyRequest from .types.compute import PatchSubnetworkRequest from .types.compute import PatchTargetGrpcProxyRequest from .types.compute import PatchTargetHttpProxyRequest +from .types.compute import PatchTargetHttpsProxyRequest from .types.compute import PatchUrlMapRequest from .types.compute import PathMatcher from .types.compute import PathRule @@ -818,6 +883,14 @@ from .types.compute import ProjectsGetXpnResources from .types.compute import ProjectsListXpnHostsRequest from .types.compute import ProjectsSetDefaultNetworkTierRequest +from .types.compute import PublicAdvertisedPrefix +from .types.compute import PublicAdvertisedPrefixList +from .types.compute import PublicAdvertisedPrefixPublicDelegatedPrefix +from .types.compute import PublicDelegatedPrefix +from .types.compute import PublicDelegatedPrefixAggregatedList +from .types.compute import PublicDelegatedPrefixesScopedList +from .types.compute import PublicDelegatedPrefixList +from .types.compute import PublicDelegatedPrefixPublicDelegatedSubPrefix from .types.compute import Quota from .types.compute import RawDisk from .types.compute import RecreateInstancesInstanceGroupManagerRequest @@ -852,6 +925,7 @@ from .types.compute import RegionSetPolicyRequest from .types.compute import RegionTargetHttpsProxiesSetSslCertificatesRequest from .types.compute import RegionUrlMapsValidateRequest +from .types.compute import RemoveAssociationFirewallPolicyRequest from .types.compute import RemoveHealthCheckTargetPoolRequest from .types.compute import RemoveInstancesInstanceGroupRequest from .types.compute import RemoveInstanceTargetPoolRequest @@ -859,6 +933,7 @@ from .types.compute import RemoveResourcePoliciesDiskRequest from .types.compute import RemoveResourcePoliciesInstanceRequest from .types.compute import RemoveResourcePoliciesRegionDiskRequest +from .types.compute import RemoveRuleFirewallPolicyRequest from .types.compute import RemoveRuleSecurityPolicyRequest from .types.compute import RequestMirrorPolicy from .types.compute import Reservation @@ -881,7 +956,11 @@ from .types.compute import ResourcePolicyDailyCycle from .types.compute import ResourcePolicyGroupPlacementPolicy from .types.compute import ResourcePolicyHourlyCycle +from .types.compute import ResourcePolicyInstanceSchedulePolicy +from .types.compute import ResourcePolicyInstanceSchedulePolicySchedule from .types.compute import ResourcePolicyList +from .types.compute import ResourcePolicyResourceStatus +from .types.compute import ResourcePolicyResourceStatusInstanceSchedulePolicyStatus from .types.compute import ResourcePolicySnapshotSchedulePolicy from .types.compute import ResourcePolicySnapshotSchedulePolicyRetentionPolicy from .types.compute import ResourcePolicySnapshotSchedulePolicySchedule @@ -907,6 +986,7 @@ from .types.compute import RouterStatusNatStatus from .types.compute import RouterStatusResponse from .types.compute import Rule +from .types.compute import ScalingScheduleStatus from .types.compute import Scheduling from .types.compute import SchedulingNodeAffinity from .types.compute import ScratchDisks @@ -931,6 +1011,7 @@ from .types.compute import SetDeletionProtectionInstanceRequest from .types.compute import SetDiskAutoDeleteInstanceRequest from .types.compute import SetIamPolicyDiskRequest +from .types.compute import SetIamPolicyFirewallPolicyRequest from .types.compute import SetIamPolicyImageRequest from .types.compute import SetIamPolicyInstanceRequest from .types.compute import SetIamPolicyInstanceTemplateRequest @@ -946,6 +1027,8 @@ from .types.compute import SetInstanceTemplateRegionInstanceGroupManagerRequest from .types.compute import SetLabelsDiskRequest from .types.compute import SetLabelsExternalVpnGatewayRequest +from .types.compute import SetLabelsForwardingRuleRequest +from .types.compute import SetLabelsGlobalForwardingRuleRequest from .types.compute import SetLabelsImageRequest from .types.compute import SetLabelsInstanceRequest from .types.compute import SetLabelsRegionDiskRequest @@ -1060,6 +1143,7 @@ from .types.compute import TestFailure from .types.compute import TestIamPermissionsDiskRequest from .types.compute import TestIamPermissionsExternalVpnGatewayRequest +from .types.compute import TestIamPermissionsFirewallPolicyRequest from .types.compute import TestIamPermissionsImageRequest from .types.compute import TestIamPermissionsInstanceRequest from .types.compute import TestIamPermissionsInstanceTemplateRequest @@ -1104,6 +1188,7 @@ from .types.compute import UrlMapsValidateRequest from .types.compute import UrlMapsValidateResponse from .types.compute import UrlMapTest +from .types.compute import UrlMapTestHeader from .types.compute import UrlMapValidationResult from .types.compute import UrlRewrite from .types.compute import UsableSubnetwork @@ -1156,6 +1241,7 @@ "Accelerators", "AccessConfig", "AddAccessConfigInstanceRequest", + "AddAssociationFirewallPolicyRequest", "AddHealthCheckTargetPoolRequest", "AddInstanceTargetPoolRequest", "AddInstancesInstanceGroupRequest", @@ -1164,6 +1250,7 @@ "AddResourcePoliciesDiskRequest", "AddResourcePoliciesInstanceRequest", "AddResourcePoliciesRegionDiskRequest", + "AddRuleFirewallPolicyRequest", "AddRuleSecurityPolicyRequest", "AddSignedUrlKeyBackendBucketRequest", "AddSignedUrlKeyBackendServiceRequest", @@ -1172,6 +1259,7 @@ "AddressList", "AddressesClient", "AddressesScopedList", + "AdvancedMachineFeatures", "AggregatedListAcceleratorTypesRequest", "AggregatedListAddressesRequest", "AggregatedListAutoscalersRequest", @@ -1191,6 +1279,7 @@ "AggregatedListNodeTemplatesRequest", "AggregatedListNodeTypesRequest", "AggregatedListPacketMirroringsRequest", + "AggregatedListPublicDelegatedPrefixesRequest", "AggregatedListRegionCommitmentsRequest", "AggregatedListReservationsRequest", "AggregatedListResourcePoliciesRequest", @@ -1231,14 +1320,19 @@ "AutoscalingPolicyCustomMetricUtilization", "AutoscalingPolicyLoadBalancingUtilization", "AutoscalingPolicyScaleInControl", + "AutoscalingPolicyScalingSchedule", "Backend", "BackendBucket", "BackendBucketCdnPolicy", + "BackendBucketCdnPolicyBypassCacheOnRequestHeader", + "BackendBucketCdnPolicyNegativeCachingPolicy", "BackendBucketList", "BackendBucketsClient", "BackendService", "BackendServiceAggregatedList", "BackendServiceCdnPolicy", + "BackendServiceCdnPolicyBypassCacheOnRequestHeader", + "BackendServiceCdnPolicyNegativeCachingPolicy", "BackendServiceFailoverPolicy", "BackendServiceGroupHealth", "BackendServiceIAP", @@ -1248,9 +1342,14 @@ "BackendServicesClient", "BackendServicesScopedList", "Binding", + "BulkInsertInstanceRequest", + "BulkInsertInstanceResource", + "BulkInsertInstanceResourcePerInstanceProperties", + "BulkInsertRegionInstanceRequest", "CacheInvalidationRule", "CacheKeyPolicy", "CircuitBreakers", + "CloneRulesFirewallPolicyRequest", "Commitment", "CommitmentAggregatedList", "CommitmentList", @@ -1275,6 +1374,7 @@ "DeleteBackendServiceRequest", "DeleteDiskRequest", "DeleteExternalVpnGatewayRequest", + "DeleteFirewallPolicyRequest", "DeleteFirewallRequest", "DeleteForwardingRuleRequest", "DeleteGlobalAddressRequest", @@ -1284,6 +1384,7 @@ "DeleteGlobalOperationResponse", "DeleteGlobalOrganizationOperationRequest", "DeleteGlobalOrganizationOperationResponse", + "DeleteGlobalPublicDelegatedPrefixeRequest", "DeleteHealthCheckRequest", "DeleteImageRequest", "DeleteInstanceGroupManagerRequest", @@ -1303,6 +1404,8 @@ "DeletePacketMirroringRequest", "DeletePerInstanceConfigsInstanceGroupManagerRequest", "DeletePerInstanceConfigsRegionInstanceGroupManagerRequest", + "DeletePublicAdvertisedPrefixeRequest", + "DeletePublicDelegatedPrefixeRequest", "DeleteRegionAutoscalerRequest", "DeleteRegionBackendServiceRequest", "DeleteRegionDiskRequest", @@ -1384,24 +1487,37 @@ "Firewall", "FirewallList", "FirewallLogConfig", + "FirewallPoliciesClient", + "FirewallPoliciesListAssociationsResponse", + "FirewallPolicy", + "FirewallPolicyAssociation", + "FirewallPolicyList", + "FirewallPolicyRule", + "FirewallPolicyRuleMatcher", + "FirewallPolicyRuleMatcherLayer4Config", "FirewallsClient", "FixedOrPercent", "ForwardingRule", "ForwardingRuleAggregatedList", "ForwardingRuleList", "ForwardingRuleReference", + "ForwardingRuleServiceDirectoryRegistration", "ForwardingRulesClient", "ForwardingRulesScopedList", "GRPCHealthCheck", "GetAcceleratorTypeRequest", "GetAddressRequest", + "GetAssociationFirewallPolicyRequest", "GetAutoscalerRequest", "GetBackendBucketRequest", "GetBackendServiceRequest", "GetDiagnosticsInterconnectRequest", "GetDiskRequest", "GetDiskTypeRequest", + "GetEffectiveFirewallsInstanceRequest", + "GetEffectiveFirewallsNetworkRequest", "GetExternalVpnGatewayRequest", + "GetFirewallPolicyRequest", "GetFirewallRequest", "GetForwardingRuleRequest", "GetFromFamilyImageRequest", @@ -1410,12 +1526,14 @@ "GetGlobalNetworkEndpointGroupRequest", "GetGlobalOperationRequest", "GetGlobalOrganizationOperationRequest", + "GetGlobalPublicDelegatedPrefixeRequest", "GetGuestAttributesInstanceRequest", "GetHealthBackendServiceRequest", "GetHealthCheckRequest", "GetHealthRegionBackendServiceRequest", "GetHealthTargetPoolRequest", "GetIamPolicyDiskRequest", + "GetIamPolicyFirewallPolicyRequest", "GetIamPolicyImageRequest", "GetIamPolicyInstanceRequest", "GetIamPolicyInstanceTemplateRequest", @@ -1446,6 +1564,8 @@ "GetNodeTypeRequest", "GetPacketMirroringRequest", "GetProjectRequest", + "GetPublicAdvertisedPrefixeRequest", + "GetPublicDelegatedPrefixeRequest", "GetRegionAutoscalerRequest", "GetRegionBackendServiceRequest", "GetRegionCommitmentRequest", @@ -1468,6 +1588,7 @@ "GetRouteRequest", "GetRouterRequest", "GetRouterStatusRouterRequest", + "GetRuleFirewallPolicyRequest", "GetRuleSecurityPolicyRequest", "GetScreenshotInstanceRequest", "GetSecurityPolicyRequest", @@ -1500,6 +1621,8 @@ "GlobalNetworkEndpointGroupsDetachEndpointsRequest", "GlobalOperationsClient", "GlobalOrganizationOperationsClient", + "GlobalOrganizationSetPolicyRequest", + "GlobalPublicDelegatedPrefixesClient", "GlobalSetLabelsRequest", "GlobalSetPolicyRequest", "GuestAttributes", @@ -1544,11 +1667,13 @@ "InsertBackendServiceRequest", "InsertDiskRequest", "InsertExternalVpnGatewayRequest", + "InsertFirewallPolicyRequest", "InsertFirewallRequest", "InsertForwardingRuleRequest", "InsertGlobalAddressRequest", "InsertGlobalForwardingRuleRequest", "InsertGlobalNetworkEndpointGroupRequest", + "InsertGlobalPublicDelegatedPrefixeRequest", "InsertHealthCheckRequest", "InsertImageRequest", "InsertInstanceGroupManagerRequest", @@ -1563,6 +1688,8 @@ "InsertNodeGroupRequest", "InsertNodeTemplateRequest", "InsertPacketMirroringRequest", + "InsertPublicAdvertisedPrefixeRequest", + "InsertPublicDelegatedPrefixeRequest", "InsertRegionAutoscalerRequest", "InsertRegionBackendServiceRequest", "InsertRegionCommitmentRequest", @@ -1647,6 +1774,8 @@ "InstanceWithNamedPorts", "InstancesAddResourcePoliciesRequest", "InstancesClient", + "InstancesGetEffectiveFirewallsResponse", + "InstancesGetEffectiveFirewallsResponseEffectiveFirewallPolicy", "InstancesRemoveResourcePoliciesRequest", "InstancesScopedList", "InstancesSetLabelsRequest", @@ -1690,6 +1819,7 @@ "LicensesListResponse", "ListAcceleratorTypesRequest", "ListAddressesRequest", + "ListAssociationsFirewallPolicyRequest", "ListAutoscalersRequest", "ListAvailableFeaturesSslPoliciesRequest", "ListBackendBucketsRequest", @@ -1699,6 +1829,7 @@ "ListErrorsInstanceGroupManagersRequest", "ListErrorsRegionInstanceGroupManagersRequest", "ListExternalVpnGatewaysRequest", + "ListFirewallPoliciesRequest", "ListFirewallsRequest", "ListForwardingRulesRequest", "ListGlobalAddressesRequest", @@ -1706,6 +1837,7 @@ "ListGlobalNetworkEndpointGroupsRequest", "ListGlobalOperationsRequest", "ListGlobalOrganizationOperationsRequest", + "ListGlobalPublicDelegatedPrefixesRequest", "ListHealthChecksRequest", "ListImagesRequest", "ListInstanceGroupManagersRequest", @@ -1734,6 +1866,8 @@ "ListPerInstanceConfigsInstanceGroupManagersRequest", "ListPerInstanceConfigsRegionInstanceGroupManagersRequest", "ListPreconfiguredExpressionSetsSecurityPoliciesRequest", + "ListPublicAdvertisedPrefixesRequest", + "ListPublicDelegatedPrefixesRequest", "ListReferrersInstancesRequest", "ListRegionAutoscalersRequest", "ListRegionBackendServicesRequest", @@ -1777,6 +1911,8 @@ "ListZoneOperationsRequest", "ListZonesRequest", "LocalDisk", + "LocationPolicy", + "LocationPolicyLocation", "LogConfig", "LogConfigCloudAuditOptions", "LogConfigCounterOptions", @@ -1795,6 +1931,7 @@ "MetadataFilter", "MetadataFilterLabelMatch", "MoveDiskProjectRequest", + "MoveFirewallPolicyRequest", "MoveInstanceProjectRequest", "NamedPort", "Network", @@ -1818,6 +1955,8 @@ "NetworkRoutingConfig", "NetworksAddPeeringRequest", "NetworksClient", + "NetworksGetEffectiveFirewallsResponse", + "NetworksGetEffectiveFirewallsResponseEffectiveFirewallPolicy", "NetworksRemovePeeringRequest", "NetworksUpdatePeeringRequest", "NodeGroup", @@ -1865,9 +2004,11 @@ "PatchAutoscalerRequest", "PatchBackendBucketRequest", "PatchBackendServiceRequest", + "PatchFirewallPolicyRequest", "PatchFirewallRequest", "PatchForwardingRuleRequest", "PatchGlobalForwardingRuleRequest", + "PatchGlobalPublicDelegatedPrefixeRequest", "PatchHealthCheckRequest", "PatchImageRequest", "PatchInstanceGroupManagerRequest", @@ -1878,6 +2019,8 @@ "PatchPacketMirroringRequest", "PatchPerInstanceConfigsInstanceGroupManagerRequest", "PatchPerInstanceConfigsRegionInstanceGroupManagerRequest", + "PatchPublicAdvertisedPrefixeRequest", + "PatchPublicDelegatedPrefixeRequest", "PatchRegionAutoscalerRequest", "PatchRegionBackendServiceRequest", "PatchRegionHealthCheckRequest", @@ -1885,12 +2028,14 @@ "PatchRegionInstanceGroupManagerRequest", "PatchRegionUrlMapRequest", "PatchRouterRequest", + "PatchRuleFirewallPolicyRequest", "PatchRuleSecurityPolicyRequest", "PatchSecurityPolicyRequest", "PatchSslPolicyRequest", "PatchSubnetworkRequest", "PatchTargetGrpcProxyRequest", "PatchTargetHttpProxyRequest", + "PatchTargetHttpsProxyRequest", "PatchUrlMapRequest", "PathMatcher", "PathRule", @@ -1907,6 +2052,16 @@ "ProjectsGetXpnResources", "ProjectsListXpnHostsRequest", "ProjectsSetDefaultNetworkTierRequest", + "PublicAdvertisedPrefix", + "PublicAdvertisedPrefixList", + "PublicAdvertisedPrefixPublicDelegatedPrefix", + "PublicAdvertisedPrefixesClient", + "PublicDelegatedPrefix", + "PublicDelegatedPrefixAggregatedList", + "PublicDelegatedPrefixList", + "PublicDelegatedPrefixPublicDelegatedSubPrefix", + "PublicDelegatedPrefixesClient", + "PublicDelegatedPrefixesScopedList", "Quota", "RawDisk", "RecreateInstancesInstanceGroupManagerRequest", @@ -1945,6 +2100,7 @@ "RegionInstanceGroupsListInstances", "RegionInstanceGroupsListInstancesRequest", "RegionInstanceGroupsSetNamedPortsRequest", + "RegionInstancesClient", "RegionList", "RegionNetworkEndpointGroupsClient", "RegionNotificationEndpointsClient", @@ -1958,6 +2114,7 @@ "RegionUrlMapsClient", "RegionUrlMapsValidateRequest", "RegionsClient", + "RemoveAssociationFirewallPolicyRequest", "RemoveHealthCheckTargetPoolRequest", "RemoveInstanceTargetPoolRequest", "RemoveInstancesInstanceGroupRequest", @@ -1965,6 +2122,7 @@ "RemoveResourcePoliciesDiskRequest", "RemoveResourcePoliciesInstanceRequest", "RemoveResourcePoliciesRegionDiskRequest", + "RemoveRuleFirewallPolicyRequest", "RemoveRuleSecurityPolicyRequest", "RequestMirrorPolicy", "Reservation", @@ -1989,7 +2147,11 @@ "ResourcePolicyDailyCycle", "ResourcePolicyGroupPlacementPolicy", "ResourcePolicyHourlyCycle", + "ResourcePolicyInstanceSchedulePolicy", + "ResourcePolicyInstanceSchedulePolicySchedule", "ResourcePolicyList", + "ResourcePolicyResourceStatus", + "ResourcePolicyResourceStatusInstanceSchedulePolicyStatus", "ResourcePolicySnapshotSchedulePolicy", "ResourcePolicySnapshotSchedulePolicyRetentionPolicy", "ResourcePolicySnapshotSchedulePolicySchedule", @@ -2018,6 +2180,7 @@ "RoutesClient", "Rule", "SSLHealthCheck", + "ScalingScheduleStatus", "Scheduling", "SchedulingNodeAffinity", "ScratchDisks", @@ -2043,6 +2206,7 @@ "SetDeletionProtectionInstanceRequest", "SetDiskAutoDeleteInstanceRequest", "SetIamPolicyDiskRequest", + "SetIamPolicyFirewallPolicyRequest", "SetIamPolicyImageRequest", "SetIamPolicyInstanceRequest", "SetIamPolicyInstanceTemplateRequest", @@ -2058,6 +2222,8 @@ "SetInstanceTemplateRegionInstanceGroupManagerRequest", "SetLabelsDiskRequest", "SetLabelsExternalVpnGatewayRequest", + "SetLabelsForwardingRuleRequest", + "SetLabelsGlobalForwardingRuleRequest", "SetLabelsImageRequest", "SetLabelsInstanceRequest", "SetLabelsRegionDiskRequest", @@ -2183,6 +2349,7 @@ "TestFailure", "TestIamPermissionsDiskRequest", "TestIamPermissionsExternalVpnGatewayRequest", + "TestIamPermissionsFirewallPolicyRequest", "TestIamPermissionsImageRequest", "TestIamPermissionsInstanceRequest", "TestIamPermissionsInstanceTemplateRequest", @@ -2223,6 +2390,7 @@ "UrlMapList", "UrlMapReference", "UrlMapTest", + "UrlMapTestHeader", "UrlMapValidationResult", "UrlMapsAggregatedList", "UrlMapsClient", 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 debcc74b08c0..21f94ce1469c 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 @@ -357,6 +357,105 @@ } } }, + "FirewallPolicies": { + "clients": { + "rest": { + "libraryClient": "FirewallPoliciesClient", + "rpcs": { + "AddAssociation": { + "methods": [ + "add_association" + ] + }, + "AddRule": { + "methods": [ + "add_rule" + ] + }, + "CloneRules": { + "methods": [ + "clone_rules" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetAssociation": { + "methods": [ + "get_association" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetRule": { + "methods": [ + "get_rule" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "ListAssociations": { + "methods": [ + "list_associations" + ] + }, + "Move": { + "methods": [ + "move" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + }, + "PatchRule": { + "methods": [ + "patch_rule" + ] + }, + "RemoveAssociation": { + "methods": [ + "remove_association" + ] + }, + "RemoveRule": { + "methods": [ + "remove_rule" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + } + } + } + } + }, "Firewalls": { "clients": { "rest": { @@ -431,6 +530,11 @@ "patch" ] }, + "SetLabels": { + "methods": [ + "set_labels" + ] + }, "SetTarget": { "methods": [ "set_target" @@ -499,6 +603,11 @@ "patch" ] }, + "SetLabels": { + "methods": [ + "set_labels" + ] + }, "SetTarget": { "methods": [ "set_target" @@ -610,6 +719,40 @@ } } }, + "GlobalPublicDelegatedPrefixes": { + "clients": { + "rest": { + "libraryClient": "GlobalPublicDelegatedPrefixesClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + } + } + } + } + }, "HealthChecks": { "clients": { "rest": { @@ -950,6 +1093,11 @@ "attach_disk" ] }, + "BulkInsert": { + "methods": [ + "bulk_insert" + ] + }, "Delete": { "methods": [ "delete" @@ -970,6 +1118,11 @@ "get" ] }, + "GetEffectiveFirewalls": { + "methods": [ + "get_effective_firewalls" + ] + }, "GetGuestAttributes": { "methods": [ "get_guest_attributes" @@ -1392,6 +1545,11 @@ "get" ] }, + "GetEffectiveFirewalls": { + "methods": [ + "get_effective_firewalls" + ] + }, "Insert": { "methods": [ "insert" @@ -1696,6 +1854,79 @@ } } }, + "PublicAdvertisedPrefixes": { + "clients": { + "rest": { + "libraryClient": "PublicAdvertisedPrefixesClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + } + } + } + } + }, + "PublicDelegatedPrefixes": { + "clients": { + "rest": { + "libraryClient": "PublicDelegatedPrefixesClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + } + } + } + } + }, "RegionAutoscalers": { "clients": { "rest": { @@ -2102,6 +2333,20 @@ } } }, + "RegionInstances": { + "clients": { + "rest": { + "libraryClient": "RegionInstancesClient", + "rpcs": { + "BulkInsert": { + "methods": [ + "bulk_insert" + ] + } + } + } + } + }, "RegionNetworkEndpointGroups": { "clients": { "rest": { @@ -2898,6 +3143,11 @@ "list" ] }, + "Patch": { + "methods": [ + "patch" + ] + }, "SetQuicOverride": { "methods": [ "set_quic_override" 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 a60b4e92671e..0ea76250bc93 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 @@ -50,7 +50,7 @@ class AcceleratorTypesClientMeta(type): _transport_registry["rest"] = AcceleratorTypesRestTransport def get_transport_class(cls, label: str = None,) -> Type[AcceleratorTypesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -75,7 +75,8 @@ class AcceleratorTypesClient(metaclass=AcceleratorTypesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -109,7 +110,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -126,7 +128,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -145,16 +147,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AcceleratorTypesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - AcceleratorTypesTransport: The transport used by the client instance. + AcceleratorTypesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -167,7 +170,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -178,7 +181,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -189,7 +192,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -200,7 +203,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -219,7 +222,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the accelerator types client. + """Instantiates the accelerator types client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -274,9 +277,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -288,12 +292,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -308,8 +314,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/accelerator_types/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/accelerator_types/transports/base.py index baad37c5fcf0..f5d37dd1a24f 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/accelerator_types/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/accelerator_types/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class AcceleratorTypesTransport(abc.ABC): """Abstract transport class for AcceleratorTypes.""" @@ -120,10 +121,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -144,27 +144,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/accelerator_types/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/accelerator_types/transports/rest.py index 7588fe91e47c..62778085991d 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/accelerator_types/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/accelerator_types/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -148,10 +149,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.AcceleratorTypeAggregatedList.from_json( @@ -208,10 +213,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.AcceleratorType.from_json( @@ -267,10 +276,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 return compute.AcceleratorTypeList.from_json( 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 edb0323726a5..efdedd095c17 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 @@ -48,7 +48,7 @@ class AddressesClientMeta(type): _transport_registry["rest"] = AddressesRestTransport def get_transport_class(cls, label: str = None,) -> Type[AddressesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class AddressesClient(metaclass=AddressesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AddressesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - AddressesTransport: The transport used by the client instance. + AddressesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the addresses client. + """Instantiates the addresses client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/addresses/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/addresses/transports/base.py index 4cdde8968c03..c14ad63c86fd 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/addresses/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/addresses/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class AddressesTransport(abc.ABC): """Abstract transport class for Addresses.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/addresses/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/addresses/transports/rest.py index deba72fde382..53b9509082b1 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/addresses/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/addresses/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -144,10 +145,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.AddressAggregatedList.from_json( @@ -226,10 +231,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -303,10 +312,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Address.from_json(response.content, ignore_unknown_fields=True) @@ -387,10 +400,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -443,10 +460,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 return compute.AddressList.from_json( 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 3400b462e819..6345f503b226 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 @@ -48,7 +48,7 @@ class AutoscalersClientMeta(type): _transport_registry["rest"] = AutoscalersRestTransport def get_transport_class(cls, label: str = None,) -> Type[AutoscalersTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class AutoscalersClient(metaclass=AutoscalersClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AutoscalersTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - AutoscalersTransport: The transport used by the client instance. + AutoscalersTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the autoscalers client. + """Instantiates the autoscalers client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/autoscalers/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/autoscalers/transports/base.py index 74a74442447d..109e91eb5044 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/autoscalers/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/autoscalers/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class AutoscalersTransport(abc.ABC): """Abstract transport class for Autoscalers.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/autoscalers/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/autoscalers/transports/rest.py index 84658489857d..f1541cb791c7 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/autoscalers/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/autoscalers/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -144,10 +145,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.AutoscalerAggregatedList.from_json( @@ -226,10 +231,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -296,10 +305,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Autoscaler.from_json( @@ -382,10 +395,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -441,10 +458,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.AutoscalerList.from_json( @@ -529,10 +550,14 @@ def patch( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -615,10 +640,14 @@ def update( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.put(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.put(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_buckets/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_buckets/client.py index 0e5af912fe0f..0128d553f0c9 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_buckets/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_buckets/client.py @@ -50,7 +50,7 @@ class BackendBucketsClientMeta(type): _transport_registry["rest"] = BackendBucketsRestTransport def get_transport_class(cls, label: str = None,) -> Type[BackendBucketsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -73,7 +73,8 @@ class BackendBucketsClient(metaclass=BackendBucketsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -107,7 +108,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -124,7 +126,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -143,16 +145,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> BackendBucketsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - BackendBucketsTransport: The transport used by the client instance. + BackendBucketsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -165,7 +168,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -176,7 +179,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -187,7 +190,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -198,7 +201,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -217,7 +220,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the backend buckets client. + """Instantiates the backend buckets client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -272,9 +275,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -286,12 +290,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -306,8 +312,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_buckets/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_buckets/transports/base.py index ce72e11b5b5a..4526d6929ddd 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_buckets/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_buckets/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class BackendBucketsTransport(abc.ABC): """Abstract transport class for BackendBuckets.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_buckets/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_buckets/transports/rest.py index 213c19657e87..ee9bc6b8e611 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_buckets/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_buckets/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -171,10 +172,14 @@ def add_signed_url_key( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -250,10 +255,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -331,10 +340,14 @@ def delete_signed_url_key( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -386,10 +399,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.BackendBucket.from_json( @@ -472,10 +489,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -531,10 +552,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.BackendBucketList.from_json( @@ -619,10 +644,14 @@ def patch( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -705,10 +734,14 @@ def update( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.put(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.put(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) 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 103a137f6fe0..9728a93e7923 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 @@ -50,7 +50,7 @@ class BackendServicesClientMeta(type): _transport_registry["rest"] = BackendServicesRestTransport def get_transport_class(cls, label: str = None,) -> Type[BackendServicesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -73,7 +73,8 @@ class BackendServicesClient(metaclass=BackendServicesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -107,7 +108,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -124,7 +126,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -143,16 +145,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> BackendServicesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - BackendServicesTransport: The transport used by the client instance. + BackendServicesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -165,7 +168,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -176,7 +179,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -187,7 +190,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -198,7 +201,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -217,7 +220,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the backend services client. + """Instantiates the backend services client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -272,9 +275,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -286,12 +290,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -306,8 +312,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -1188,8 +1194,9 @@ def set_security_policy( timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Operation: - r"""Sets the security policy for the specified backend - service. + r"""Sets the Google Cloud Armor security policy for the + specified backend service. For more information, see + Google Cloud Armor Overview Args: request (google.cloud.compute_v1.types.SetSecurityPolicyBackendServiceRequest): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/transports/base.py index 7e58fefa4bd3..47392e6d4436 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class BackendServicesTransport(abc.ABC): """Abstract transport class for BackendServices.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/transports/rest.py index 09afa47fc8aa..86fc6473f231 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -171,10 +172,14 @@ def add_signed_url_key( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -235,10 +240,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.BackendServiceAggregatedList.from_json( @@ -316,10 +325,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -397,10 +410,14 @@ def delete_signed_url_key( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -468,10 +485,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.BackendService.from_json( @@ -526,10 +547,14 @@ def get_health( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.BackendServiceGroupHealth.from_json( @@ -612,10 +637,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -671,10 +700,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.BackendServiceList.from_json( @@ -759,10 +792,14 @@ def patch( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -845,10 +882,14 @@ def set_security_policy( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -931,10 +972,14 @@ def update( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.put(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.put(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) 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 246eedd0111a..8939f4ccbf0f 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 @@ -48,7 +48,7 @@ class DiskTypesClientMeta(type): _transport_registry["rest"] = DiskTypesRestTransport def get_transport_class(cls, label: str = None,) -> Type[DiskTypesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class DiskTypesClient(metaclass=DiskTypesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> DiskTypesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - DiskTypesTransport: The transport used by the client instance. + DiskTypesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the disk types client. + """Instantiates the disk types client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/disk_types/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/disk_types/transports/base.py index b330b6cfd132..c44914d3ca9f 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/disk_types/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/disk_types/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class DiskTypesTransport(abc.ABC): """Abstract transport class for DiskTypes.""" @@ -120,10 +121,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -144,27 +144,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/disk_types/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/disk_types/transports/rest.py index 579796807361..18e4260d0140 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/disk_types/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/disk_types/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -144,10 +145,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.DiskTypeAggregatedList.from_json( @@ -215,10 +220,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.DiskType.from_json(response.content, ignore_unknown_fields=True) @@ -271,10 +280,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 return compute.DiskTypeList.from_json( 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 f33d75a235d8..89cc7550e111 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 @@ -48,7 +48,7 @@ class DisksClientMeta(type): _transport_registry["rest"] = DisksRestTransport def get_transport_class(cls, label: str = None,) -> Type[DisksTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class DisksClient(metaclass=DisksClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> DisksTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - DisksTransport: The transport used by the client instance. + DisksTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the disks client. + """Instantiates the disks client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/disks/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/disks/transports/base.py index d336f3c62ea0..1d6b21eebf38 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/disks/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/disks/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class DisksTransport(abc.ABC): """Abstract transport class for Disks.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/disks/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/disks/transports/rest.py index 1a778cda711b..77dfec062064 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/disks/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/disks/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -172,10 +173,14 @@ def add_resource_policies( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -231,10 +236,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.DiskAggregatedList.from_json( @@ -322,10 +331,14 @@ def create_snapshot( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -401,10 +414,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -470,10 +487,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Disk.from_json(response.content, ignore_unknown_fields=True) @@ -574,10 +595,14 @@ def get_iam_policy( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Policy.from_json(response.content, ignore_unknown_fields=True) @@ -659,10 +684,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -715,10 +744,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.DiskList.from_json(response.content, ignore_unknown_fields=True) @@ -802,10 +835,14 @@ def remove_resource_policies( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -888,10 +925,14 @@ def resize( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -995,10 +1036,14 @@ def set_iam_policy( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Policy.from_json(response.content, ignore_unknown_fields=True) @@ -1082,10 +1127,14 @@ def set_labels( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -1139,10 +1188,14 @@ def test_iam_permissions( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.TestPermissionsResponse.from_json( diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/external_vpn_gateways/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/external_vpn_gateways/client.py index a3860ad70186..5c84b80c8051 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/external_vpn_gateways/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/external_vpn_gateways/client.py @@ -52,7 +52,7 @@ class ExternalVpnGatewaysClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[ExternalVpnGatewaysTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -75,7 +75,8 @@ class ExternalVpnGatewaysClient(metaclass=ExternalVpnGatewaysClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -109,7 +110,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -126,7 +128,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -145,16 +147,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ExternalVpnGatewaysTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - ExternalVpnGatewaysTransport: The transport used by the client instance. + ExternalVpnGatewaysTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -167,7 +170,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -178,7 +181,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -189,7 +192,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -200,7 +203,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -219,7 +222,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the external vpn gateways client. + """Instantiates the external vpn gateways client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -274,9 +277,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -288,12 +292,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -308,8 +314,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/external_vpn_gateways/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/external_vpn_gateways/transports/base.py index f22510198f38..f0a2d8d64b5f 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/external_vpn_gateways/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/external_vpn_gateways/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class ExternalVpnGatewaysTransport(abc.ABC): """Abstract transport class for ExternalVpnGateways.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/external_vpn_gateways/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/external_vpn_gateways/transports/rest.py index 920eea86a1bf..989d8fb0c489 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/external_vpn_gateways/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/external_vpn_gateways/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -164,10 +165,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -228,10 +233,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.ExternalVpnGateway.from_json( @@ -314,10 +323,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -373,10 +386,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.ExternalVpnGatewayList.from_json( @@ -457,10 +474,14 @@ def set_labels( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -511,10 +532,14 @@ def test_iam_permissions( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.TestPermissionsResponse.from_json( diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/__init__.py new file mode 100644 index 000000000000..d451ee988f17 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 FirewallPoliciesClient + +__all__ = ("FirewallPoliciesClient",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/client.py new file mode 100644 index 000000000000..edaf4279a2c3 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/client.py @@ -0,0 +1,1880 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.compute_v1.services.firewall_policies import pagers +from google.cloud.compute_v1.types import compute +from .transports.base import FirewallPoliciesTransport, DEFAULT_CLIENT_INFO +from .transports.rest import FirewallPoliciesRestTransport + + +class FirewallPoliciesClientMeta(type): + """Metaclass for the FirewallPolicies 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[FirewallPoliciesTransport]] + _transport_registry["rest"] = FirewallPoliciesRestTransport + + def get_transport_class(cls, label: str = None,) -> Type[FirewallPoliciesTransport]: + """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 FirewallPoliciesClient(metaclass=FirewallPoliciesClientMeta): + """The FirewallPolicies 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") + + DEFAULT_ENDPOINT = "compute.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @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: + FirewallPoliciesClient: 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: + FirewallPoliciesClient: 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) -> FirewallPoliciesTransport: + """Returns the transport used by the client instance. + + Returns: + FirewallPoliciesTransport: 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 {} + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, FirewallPoliciesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the firewall policies client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, FirewallPoliciesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "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). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS 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. + 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. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, FirewallPoliciesTransport): + # transport is a FirewallPoliciesTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def add_association( + self, + request: compute.AddAssociationFirewallPolicyRequest = None, + *, + firewall_policy: str = None, + firewall_policy_association_resource: compute.FirewallPolicyAssociation = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Inserts an association for the specified firewall + policy. + + Args: + request (google.cloud.compute_v1.types.AddAssociationFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.AddAssociation. See the method + description for details. + firewall_policy (str): + Name of the firewall policy to + update. + + This corresponds to the ``firewall_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + firewall_policy_association_resource (google.cloud.compute_v1.types.FirewallPolicyAssociation): + The body resource for this request + This corresponds to the ``firewall_policy_association_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.compute_v1.types.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - [Global](/compute/docs/reference/rest/{$api_version}/globalOperations) + \* + [Regional](/compute/docs/reference/rest/{$api_version}/regionOperations) + \* + [Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations) + + 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 + zonalOperations resource. + + For more information, read Global, Regional, and + Zonal Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any( + [firewall_policy, firewall_policy_association_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.AddAssociationFirewallPolicyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.AddAssociationFirewallPolicyRequest): + request = compute.AddAssociationFirewallPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if firewall_policy is not None: + request.firewall_policy = firewall_policy + if firewall_policy_association_resource is not None: + request.firewall_policy_association_resource = ( + firewall_policy_association_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_association] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def add_rule( + self, + request: compute.AddRuleFirewallPolicyRequest = None, + *, + firewall_policy: str = None, + firewall_policy_rule_resource: compute.FirewallPolicyRule = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Inserts a rule into a firewall policy. + + Args: + request (google.cloud.compute_v1.types.AddRuleFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.AddRule. See the method description for + details. + firewall_policy (str): + Name of the firewall policy to + update. + + This corresponds to the ``firewall_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + firewall_policy_rule_resource (google.cloud.compute_v1.types.FirewallPolicyRule): + The body resource for this request + This corresponds to the ``firewall_policy_rule_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.compute_v1.types.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - [Global](/compute/docs/reference/rest/{$api_version}/globalOperations) + \* + [Regional](/compute/docs/reference/rest/{$api_version}/regionOperations) + \* + [Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations) + + 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 + zonalOperations resource. + + For more information, read Global, Regional, and + Zonal Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([firewall_policy, firewall_policy_rule_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.AddRuleFirewallPolicyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.AddRuleFirewallPolicyRequest): + request = compute.AddRuleFirewallPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if firewall_policy is not None: + request.firewall_policy = firewall_policy + if firewall_policy_rule_resource is not None: + request.firewall_policy_rule_resource = firewall_policy_rule_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_rule] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def clone_rules( + self, + request: compute.CloneRulesFirewallPolicyRequest = None, + *, + firewall_policy: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Copies rules to the specified firewall policy. + + Args: + request (google.cloud.compute_v1.types.CloneRulesFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.CloneRules. See the method description + for details. + firewall_policy (str): + Name of the firewall policy to + update. + + This corresponds to the ``firewall_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.compute_v1.types.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - [Global](/compute/docs/reference/rest/{$api_version}/globalOperations) + \* + [Regional](/compute/docs/reference/rest/{$api_version}/regionOperations) + \* + [Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations) + + 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 + zonalOperations resource. + + For more information, read Global, Regional, and + Zonal Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([firewall_policy]) + if request is 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.CloneRulesFirewallPolicyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.CloneRulesFirewallPolicyRequest): + request = compute.CloneRulesFirewallPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if firewall_policy is not None: + request.firewall_policy = firewall_policy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.clone_rules] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete( + self, + request: compute.DeleteFirewallPolicyRequest = None, + *, + firewall_policy: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Deletes the specified policy. + + Args: + request (google.cloud.compute_v1.types.DeleteFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.Delete. See the method description for + details. + firewall_policy (str): + Name of the firewall policy to + delete. + + This corresponds to the ``firewall_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.compute_v1.types.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - [Global](/compute/docs/reference/rest/{$api_version}/globalOperations) + \* + [Regional](/compute/docs/reference/rest/{$api_version}/regionOperations) + \* + [Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations) + + 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 + zonalOperations resource. + + For more information, read Global, Regional, and + Zonal Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([firewall_policy]) + if request is 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.DeleteFirewallPolicyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.DeleteFirewallPolicyRequest): + request = compute.DeleteFirewallPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if firewall_policy is not None: + request.firewall_policy = firewall_policy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get( + self, + request: compute.GetFirewallPolicyRequest = None, + *, + firewall_policy: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.FirewallPolicy: + r"""Returns the specified firewall policy. + + Args: + request (google.cloud.compute_v1.types.GetFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.Get. See the method description for + details. + firewall_policy (str): + Name of the firewall policy to get. + This corresponds to the ``firewall_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.compute_v1.types.FirewallPolicy: + Represents a Firewall Policy resource. (== resource_for + {$api_version}.firewallPolicies ==) + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([firewall_policy]) + if request is 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.GetFirewallPolicyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.GetFirewallPolicyRequest): + request = compute.GetFirewallPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if firewall_policy is not None: + request.firewall_policy = firewall_policy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_association( + self, + request: compute.GetAssociationFirewallPolicyRequest = None, + *, + firewall_policy: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.FirewallPolicyAssociation: + r"""Gets an association with the specified name. + + Args: + request (google.cloud.compute_v1.types.GetAssociationFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.GetAssociation. See the method + description for details. + firewall_policy (str): + Name of the firewall policy to which + the queried rule belongs. + + This corresponds to the ``firewall_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.compute_v1.types.FirewallPolicyAssociation: + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([firewall_policy]) + if request is 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.GetAssociationFirewallPolicyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.GetAssociationFirewallPolicyRequest): + request = compute.GetAssociationFirewallPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if firewall_policy is not None: + request.firewall_policy = firewall_policy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_association] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: compute.GetIamPolicyFirewallPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (google.cloud.compute_v1.types.GetIamPolicyFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.GetIamPolicy. See the method + description for details. + 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 to a single role. Members 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:** + + { "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](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Sanity 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.GetIamPolicyFirewallPolicyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.GetIamPolicyFirewallPolicyRequest): + request = compute.GetIamPolicyFirewallPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_rule( + self, + request: compute.GetRuleFirewallPolicyRequest = None, + *, + firewall_policy: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.FirewallPolicyRule: + r"""Gets a rule of the specified priority. + + Args: + request (google.cloud.compute_v1.types.GetRuleFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.GetRule. See the method description for + details. + firewall_policy (str): + Name of the firewall policy to which + the queried rule belongs. + + This corresponds to the ``firewall_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.compute_v1.types.FirewallPolicyRule: + Represents a rule that describes one + or more match conditions along with the + action to be taken when traffic matches + this condition (allow or deny). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([firewall_policy]) + if request is 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.GetRuleFirewallPolicyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.GetRuleFirewallPolicyRequest): + request = compute.GetRuleFirewallPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if firewall_policy is not None: + request.firewall_policy = firewall_policy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_rule] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def insert( + self, + request: compute.InsertFirewallPolicyRequest = None, + *, + firewall_policy_resource: compute.FirewallPolicy = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Creates a new policy in the specified project using + the data included in the request. + + Args: + request (google.cloud.compute_v1.types.InsertFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.Insert. See the method description for + details. + firewall_policy_resource (google.cloud.compute_v1.types.FirewallPolicy): + The body resource for this request + This corresponds to the ``firewall_policy_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.compute_v1.types.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - [Global](/compute/docs/reference/rest/{$api_version}/globalOperations) + \* + [Regional](/compute/docs/reference/rest/{$api_version}/regionOperations) + \* + [Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations) + + 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 + zonalOperations resource. + + For more information, read Global, Regional, and + Zonal Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([firewall_policy_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.InsertFirewallPolicyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.InsertFirewallPolicyRequest): + request = compute.InsertFirewallPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if firewall_policy_resource is not None: + request.firewall_policy_resource = firewall_policy_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list( + self, + request: compute.ListFirewallPoliciesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPager: + r"""Lists all the policies that have been configured for + the specified project. + + Args: + request (google.cloud.compute_v1.types.ListFirewallPoliciesRequest): + The request object. A request message for + FirewallPolicies.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: + google.cloud.compute_v1.services.firewall_policies.pagers.ListPager: + 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 compute.ListFirewallPoliciesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.ListFirewallPoliciesRequest): + request = compute.ListFirewallPoliciesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list] + + # 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 list_associations( + self, + request: compute.ListAssociationsFirewallPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.FirewallPoliciesListAssociationsResponse: + r"""Lists associations of a specified target, i.e., + organization or folder. + + Args: + request (google.cloud.compute_v1.types.ListAssociationsFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.ListAssociations. See the method + description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.compute_v1.types.FirewallPoliciesListAssociationsResponse: + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a compute.ListAssociationsFirewallPolicyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.ListAssociationsFirewallPolicyRequest): + request = compute.ListAssociationsFirewallPolicyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_associations] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def move( + self, + request: compute.MoveFirewallPolicyRequest = None, + *, + firewall_policy: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Moves the specified firewall policy. + + Args: + request (google.cloud.compute_v1.types.MoveFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.Move. See the method description for + details. + firewall_policy (str): + Name of the firewall policy to + update. + + This corresponds to the ``firewall_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.compute_v1.types.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - [Global](/compute/docs/reference/rest/{$api_version}/globalOperations) + \* + [Regional](/compute/docs/reference/rest/{$api_version}/regionOperations) + \* + [Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations) + + 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 + zonalOperations resource. + + For more information, read Global, Regional, and + Zonal Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([firewall_policy]) + if request is 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.MoveFirewallPolicyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.MoveFirewallPolicyRequest): + request = compute.MoveFirewallPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if firewall_policy is not None: + request.firewall_policy = firewall_policy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.move] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def patch( + self, + request: compute.PatchFirewallPolicyRequest = None, + *, + firewall_policy: str = None, + firewall_policy_resource: compute.FirewallPolicy = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Patches the specified policy with the data included + in the request. + + Args: + request (google.cloud.compute_v1.types.PatchFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.Patch. See the method description for + details. + firewall_policy (str): + Name of the firewall policy to + update. + + This corresponds to the ``firewall_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + firewall_policy_resource (google.cloud.compute_v1.types.FirewallPolicy): + The body resource for this request + This corresponds to the ``firewall_policy_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.compute_v1.types.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - [Global](/compute/docs/reference/rest/{$api_version}/globalOperations) + \* + [Regional](/compute/docs/reference/rest/{$api_version}/regionOperations) + \* + [Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations) + + 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 + zonalOperations resource. + + For more information, read Global, Regional, and + Zonal Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([firewall_policy, firewall_policy_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.PatchFirewallPolicyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.PatchFirewallPolicyRequest): + request = compute.PatchFirewallPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if firewall_policy is not None: + request.firewall_policy = firewall_policy + if firewall_policy_resource is not None: + request.firewall_policy_resource = firewall_policy_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.patch] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def patch_rule( + self, + request: compute.PatchRuleFirewallPolicyRequest = None, + *, + firewall_policy: str = None, + firewall_policy_rule_resource: compute.FirewallPolicyRule = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Patches a rule of the specified priority. + + Args: + request (google.cloud.compute_v1.types.PatchRuleFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.PatchRule. See the method description + for details. + firewall_policy (str): + Name of the firewall policy to + update. + + This corresponds to the ``firewall_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + firewall_policy_rule_resource (google.cloud.compute_v1.types.FirewallPolicyRule): + The body resource for this request + This corresponds to the ``firewall_policy_rule_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.compute_v1.types.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - [Global](/compute/docs/reference/rest/{$api_version}/globalOperations) + \* + [Regional](/compute/docs/reference/rest/{$api_version}/regionOperations) + \* + [Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations) + + 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 + zonalOperations resource. + + For more information, read Global, Regional, and + Zonal Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([firewall_policy, firewall_policy_rule_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.PatchRuleFirewallPolicyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.PatchRuleFirewallPolicyRequest): + request = compute.PatchRuleFirewallPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if firewall_policy is not None: + request.firewall_policy = firewall_policy + if firewall_policy_rule_resource is not None: + request.firewall_policy_rule_resource = firewall_policy_rule_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.patch_rule] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def remove_association( + self, + request: compute.RemoveAssociationFirewallPolicyRequest = None, + *, + firewall_policy: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Removes an association for the specified firewall + policy. + + Args: + request (google.cloud.compute_v1.types.RemoveAssociationFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.RemoveAssociation. See the method + description for details. + firewall_policy (str): + Name of the firewall policy to + update. + + This corresponds to the ``firewall_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.compute_v1.types.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - [Global](/compute/docs/reference/rest/{$api_version}/globalOperations) + \* + [Regional](/compute/docs/reference/rest/{$api_version}/regionOperations) + \* + [Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations) + + 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 + zonalOperations resource. + + For more information, read Global, Regional, and + Zonal Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([firewall_policy]) + if request is 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.RemoveAssociationFirewallPolicyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.RemoveAssociationFirewallPolicyRequest): + request = compute.RemoveAssociationFirewallPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if firewall_policy is not None: + request.firewall_policy = firewall_policy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_association] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def remove_rule( + self, + request: compute.RemoveRuleFirewallPolicyRequest = None, + *, + firewall_policy: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Deletes a rule of the specified priority. + + Args: + request (google.cloud.compute_v1.types.RemoveRuleFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.RemoveRule. See the method description + for details. + firewall_policy (str): + Name of the firewall policy to + update. + + This corresponds to the ``firewall_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.compute_v1.types.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - [Global](/compute/docs/reference/rest/{$api_version}/globalOperations) + \* + [Regional](/compute/docs/reference/rest/{$api_version}/regionOperations) + \* + [Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations) + + 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 + zonalOperations resource. + + For more information, read Global, Regional, and + Zonal Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([firewall_policy]) + if request is 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.RemoveRuleFirewallPolicyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.RemoveRuleFirewallPolicyRequest): + request = compute.RemoveRuleFirewallPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if firewall_policy is not None: + request.firewall_policy = firewall_policy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_rule] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def set_iam_policy( + self, + request: compute.SetIamPolicyFirewallPolicyRequest = None, + *, + resource: str = None, + global_organization_set_policy_request_resource: compute.GlobalOrganizationSetPolicyRequest = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Policy: + r"""Sets the access control policy on the specified + resource. Replaces any existing policy. + + Args: + request (google.cloud.compute_v1.types.SetIamPolicyFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.SetIamPolicy. See the method + description for details. + resource (str): + Name or id of the resource for this + request. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + global_organization_set_policy_request_resource (google.cloud.compute_v1.types.GlobalOrganizationSetPolicyRequest): + The body resource for this request + This corresponds to the ``global_organization_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 to a single role. Members 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:** + + { "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](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Sanity 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, global_organization_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.SetIamPolicyFirewallPolicyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.SetIamPolicyFirewallPolicyRequest): + request = compute.SetIamPolicyFirewallPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if resource is not None: + request.resource = resource + if global_organization_set_policy_request_resource is not None: + request.global_organization_set_policy_request_resource = ( + global_organization_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] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: compute.TestIamPermissionsFirewallPolicyRequest = None, + *, + resource: str = None, + test_permissions_request_resource: compute.TestPermissionsRequest = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.TestPermissionsResponse: + r"""Returns permissions that a caller has on the + specified resource. + + Args: + request (google.cloud.compute_v1.types.TestIamPermissionsFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.TestIamPermissions. See the method + description for details. + 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. + # Sanity 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, 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.TestIamPermissionsFirewallPolicyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.TestIamPermissionsFirewallPolicyRequest): + request = compute.TestIamPermissionsFirewallPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("FirewallPoliciesClient",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/pagers.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/pagers.py new file mode 100644 index 000000000000..df2a6b66caae --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/pagers.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, + AsyncIterable, + Awaitable, + Callable, + Iterable, + Sequence, + Tuple, + Optional, +) + +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.FirewallPolicyList` 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.FirewallPolicyList` + 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.FirewallPolicyList], + request: compute.ListFirewallPoliciesRequest, + response: compute.FirewallPolicyList, + *, + 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.ListFirewallPoliciesRequest): + The initial request object. + response (google.cloud.compute_v1.types.FirewallPolicyList): + 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.ListFirewallPoliciesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[compute.FirewallPolicyList]: + 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) -> Iterable[compute.FirewallPolicy]: + 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/firewall_policies/transports/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/transports/__init__.py new file mode 100644 index 000000000000..ad3ce5757f13 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/transports/__init__.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 FirewallPoliciesTransport +from .rest import FirewallPoliciesRestTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[FirewallPoliciesTransport]] +_transport_registry["rest"] = FirewallPoliciesRestTransport + +__all__ = ( + "FirewallPoliciesTransport", + "FirewallPoliciesRestTransport", +) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/transports/base.py new file mode 100644 index 000000000000..6893c06e7491 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/transports/base.py @@ -0,0 +1,378 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 packaging.version +import pkg_resources +from requests import __version__ as requests_version + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.compute_v1.types import compute + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class FirewallPoliciesTransport(abc.ABC): + """Abstract transport class for FirewallPolicies.""" + + 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: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + 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. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_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 + ) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.add_association: gapic_v1.method.wrap_method( + self.add_association, default_timeout=None, client_info=client_info, + ), + self.add_rule: gapic_v1.method.wrap_method( + self.add_rule, default_timeout=None, client_info=client_info, + ), + self.clone_rules: gapic_v1.method.wrap_method( + self.clone_rules, default_timeout=None, client_info=client_info, + ), + self.delete: gapic_v1.method.wrap_method( + self.delete, default_timeout=None, client_info=client_info, + ), + self.get: gapic_v1.method.wrap_method( + self.get, default_timeout=None, client_info=client_info, + ), + self.get_association: gapic_v1.method.wrap_method( + self.get_association, default_timeout=None, client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, default_timeout=None, client_info=client_info, + ), + self.get_rule: gapic_v1.method.wrap_method( + self.get_rule, default_timeout=None, client_info=client_info, + ), + self.insert: gapic_v1.method.wrap_method( + self.insert, default_timeout=None, client_info=client_info, + ), + self.list: gapic_v1.method.wrap_method( + self.list, default_timeout=None, client_info=client_info, + ), + self.list_associations: gapic_v1.method.wrap_method( + self.list_associations, default_timeout=None, client_info=client_info, + ), + self.move: gapic_v1.method.wrap_method( + self.move, default_timeout=None, client_info=client_info, + ), + self.patch: gapic_v1.method.wrap_method( + self.patch, default_timeout=None, client_info=client_info, + ), + self.patch_rule: gapic_v1.method.wrap_method( + self.patch_rule, default_timeout=None, client_info=client_info, + ), + self.remove_association: gapic_v1.method.wrap_method( + self.remove_association, default_timeout=None, client_info=client_info, + ), + self.remove_rule: gapic_v1.method.wrap_method( + self.remove_rule, default_timeout=None, client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, 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, + ), + } + + @property + def add_association( + self, + ) -> Callable[ + [compute.AddAssociationFirewallPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def add_rule( + self, + ) -> Callable[ + [compute.AddRuleFirewallPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def clone_rules( + self, + ) -> Callable[ + [compute.CloneRulesFirewallPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def delete( + self, + ) -> Callable[ + [compute.DeleteFirewallPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def get( + self, + ) -> Callable[ + [compute.GetFirewallPolicyRequest], + Union[compute.FirewallPolicy, Awaitable[compute.FirewallPolicy]], + ]: + raise NotImplementedError() + + @property + def get_association( + self, + ) -> Callable[ + [compute.GetAssociationFirewallPolicyRequest], + Union[ + compute.FirewallPolicyAssociation, + Awaitable[compute.FirewallPolicyAssociation], + ], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [compute.GetIamPolicyFirewallPolicyRequest], + Union[compute.Policy, Awaitable[compute.Policy]], + ]: + raise NotImplementedError() + + @property + def get_rule( + self, + ) -> Callable[ + [compute.GetRuleFirewallPolicyRequest], + Union[compute.FirewallPolicyRule, Awaitable[compute.FirewallPolicyRule]], + ]: + raise NotImplementedError() + + @property + def insert( + self, + ) -> Callable[ + [compute.InsertFirewallPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def list( + self, + ) -> Callable[ + [compute.ListFirewallPoliciesRequest], + Union[compute.FirewallPolicyList, Awaitable[compute.FirewallPolicyList]], + ]: + raise NotImplementedError() + + @property + def list_associations( + self, + ) -> Callable[ + [compute.ListAssociationsFirewallPolicyRequest], + Union[ + compute.FirewallPoliciesListAssociationsResponse, + Awaitable[compute.FirewallPoliciesListAssociationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def move( + self, + ) -> Callable[ + [compute.MoveFirewallPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def patch( + self, + ) -> Callable[ + [compute.PatchFirewallPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def patch_rule( + self, + ) -> Callable[ + [compute.PatchRuleFirewallPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def remove_association( + self, + ) -> Callable[ + [compute.RemoveAssociationFirewallPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def remove_rule( + self, + ) -> Callable[ + [compute.RemoveRuleFirewallPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [compute.SetIamPolicyFirewallPolicyRequest], + Union[compute.Policy, Awaitable[compute.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [compute.TestIamPermissionsFirewallPolicyRequest], + Union[ + compute.TestPermissionsResponse, Awaitable[compute.TestPermissionsResponse] + ], + ]: + raise NotImplementedError() + + +__all__ = ("FirewallPoliciesTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/transports/rest.py new file mode 100644 index 000000000000..b543ca504947 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/transports/rest.py @@ -0,0 +1,1527 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # 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.auth.transport.requests import AuthorizedSession + +from google.cloud.compute_v1.types import compute + +from .base import FirewallPoliciesTransport, DEFAULT_CLIENT_INFO + + +class FirewallPoliciesRestTransport(FirewallPoliciesTransport): + """REST backend transport for FirewallPolicies. + + The FirewallPolicies API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "compute.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + 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're developing + your own client library. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, credentials=credentials, client_info=client_info, + ) + 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._prep_wrapped_messages(client_info) + + def add_association( + self, + request: compute.AddAssociationFirewallPolicyRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the add association method over HTTP. + + Args: + request (~.compute.AddAssociationFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.AddAssociation. See the + method description for details. + + 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 ``zonalOperations`` + resource. + + For more information, read Global, Regional, and Zonal + Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + + # Jsonify the request body + body = compute.FirewallPolicyAssociation.to_json( + request.firewall_policy_association_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/locations/global/firewallPolicies/{firewall_policy}/addAssociation".format( + host=self._host, firewall_policy=request.firewall_policy, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if ( + compute.AddAssociationFirewallPolicyRequest.replace_existing_association + in request + ): + query_params[ + "replaceExistingAssociation" + ] = request.replace_existing_association + if compute.AddAssociationFirewallPolicyRequest.request_id in request: + query_params["requestId"] = request.request_id + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 + return compute.Operation.from_json(response.content, ignore_unknown_fields=True) + + def add_rule( + self, + request: compute.AddRuleFirewallPolicyRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the add rule method over HTTP. + + Args: + request (~.compute.AddRuleFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.AddRule. See the method + description for details. + + 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 ``zonalOperations`` + resource. + + For more information, read Global, Regional, and Zonal + Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + + # Jsonify the request body + body = compute.FirewallPolicyRule.to_json( + request.firewall_policy_rule_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/locations/global/firewallPolicies/{firewall_policy}/addRule".format( + host=self._host, firewall_policy=request.firewall_policy, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.AddRuleFirewallPolicyRequest.request_id in request: + query_params["requestId"] = request.request_id + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 + return compute.Operation.from_json(response.content, ignore_unknown_fields=True) + + def clone_rules( + self, + request: compute.CloneRulesFirewallPolicyRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the clone rules method over HTTP. + + Args: + request (~.compute.CloneRulesFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.CloneRules. See the + method description for details. + + 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 ``zonalOperations`` + resource. + + For more information, read Global, Regional, and Zonal + Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/locations/global/firewallPolicies/{firewall_policy}/cloneRules".format( + host=self._host, firewall_policy=request.firewall_policy, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.CloneRulesFirewallPolicyRequest.request_id in request: + query_params["requestId"] = request.request_id + if compute.CloneRulesFirewallPolicyRequest.source_firewall_policy in request: + query_params["sourceFirewallPolicy"] = request.source_firewall_policy + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers,) + + # 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 + return compute.Operation.from_json(response.content, ignore_unknown_fields=True) + + def delete( + self, + request: compute.DeleteFirewallPolicyRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the delete method over HTTP. + + Args: + request (~.compute.DeleteFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.Delete. See the method + description for details. + + 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 ``zonalOperations`` + resource. + + For more information, read Global, Regional, and Zonal + Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/locations/global/firewallPolicies/{firewall_policy}".format( + host=self._host, firewall_policy=request.firewall_policy, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.DeleteFirewallPolicyRequest.request_id in request: + query_params["requestId"] = request.request_id + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) + + # 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 + return compute.Operation.from_json(response.content, ignore_unknown_fields=True) + + def get( + self, + request: compute.GetFirewallPolicyRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.FirewallPolicy: + r"""Call the get method over HTTP. + + Args: + request (~.compute.GetFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.Get. See the method + description for details. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.FirewallPolicy: + Represents a Firewall Policy resource. (== resource_for + {$api_version}.firewallPolicies ==) + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/locations/global/firewallPolicies/{firewall_policy}".format( + host=self._host, firewall_policy=request.firewall_policy, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 + return compute.FirewallPolicy.from_json( + response.content, ignore_unknown_fields=True + ) + + def get_association( + self, + request: compute.GetAssociationFirewallPolicyRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.FirewallPolicyAssociation: + r"""Call the get association method over HTTP. + + Args: + request (~.compute.GetAssociationFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.GetAssociation. See the + method description for details. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.FirewallPolicyAssociation: + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/locations/global/firewallPolicies/{firewall_policy}/getAssociation".format( + host=self._host, firewall_policy=request.firewall_policy, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.GetAssociationFirewallPolicyRequest.name in request: + query_params["name"] = request.name + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 + return compute.FirewallPolicyAssociation.from_json( + response.content, ignore_unknown_fields=True + ) + + def get_iam_policy( + self, + request: compute.GetIamPolicyFirewallPolicyRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Policy: + r"""Call the get iam policy method over HTTP. + + Args: + request (~.compute.GetIamPolicyFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.GetIamPolicy. See the + method description for details. + + 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`` to a single + ``role``. Members 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 `__. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/locations/global/firewallPolicies/{resource}/getIamPolicy".format( + host=self._host, resource=request.resource, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if ( + compute.GetIamPolicyFirewallPolicyRequest.options_requested_policy_version + in request + ): + query_params[ + "optionsRequestedPolicyVersion" + ] = request.options_requested_policy_version + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 + return compute.Policy.from_json(response.content, ignore_unknown_fields=True) + + def get_rule( + self, + request: compute.GetRuleFirewallPolicyRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.FirewallPolicyRule: + r"""Call the get rule method over HTTP. + + Args: + request (~.compute.GetRuleFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.GetRule. See the method + description for details. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.FirewallPolicyRule: + Represents a rule that describes one + or more match conditions along with the + action to be taken when traffic matches + this condition (allow or deny). + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/locations/global/firewallPolicies/{firewall_policy}/getRule".format( + host=self._host, firewall_policy=request.firewall_policy, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.GetRuleFirewallPolicyRequest.priority in request: + query_params["priority"] = request.priority + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 + return compute.FirewallPolicyRule.from_json( + response.content, ignore_unknown_fields=True + ) + + def insert( + self, + request: compute.InsertFirewallPolicyRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the insert method over HTTP. + + Args: + request (~.compute.InsertFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.Insert. See the method + description for details. + + 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 ``zonalOperations`` + resource. + + For more information, read Global, Regional, and Zonal + Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + + # Jsonify the request body + body = compute.FirewallPolicy.to_json( + request.firewall_policy_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/locations/global/firewallPolicies".format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.InsertFirewallPolicyRequest.parent_id in request: + query_params["parentId"] = request.parent_id + if compute.InsertFirewallPolicyRequest.request_id in request: + query_params["requestId"] = request.request_id + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 + return compute.Operation.from_json(response.content, ignore_unknown_fields=True) + + def list( + self, + request: compute.ListFirewallPoliciesRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.FirewallPolicyList: + r"""Call the list method over HTTP. + + Args: + request (~.compute.ListFirewallPoliciesRequest): + The request object. A request message for + FirewallPolicies.List. See the method + description for details. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.FirewallPolicyList: + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/locations/global/firewallPolicies".format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.ListFirewallPoliciesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListFirewallPoliciesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListFirewallPoliciesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListFirewallPoliciesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListFirewallPoliciesRequest.parent_id in request: + query_params["parentId"] = request.parent_id + if compute.ListFirewallPoliciesRequest.return_partial_success in request: + query_params["returnPartialSuccess"] = request.return_partial_success + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 + return compute.FirewallPolicyList.from_json( + response.content, ignore_unknown_fields=True + ) + + def list_associations( + self, + request: compute.ListAssociationsFirewallPolicyRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.FirewallPoliciesListAssociationsResponse: + r"""Call the list associations method over HTTP. + + Args: + request (~.compute.ListAssociationsFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.ListAssociations. See + the method description for details. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.FirewallPoliciesListAssociationsResponse: + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/locations/global/firewallPolicies/listAssociations".format( + host=self._host, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.ListAssociationsFirewallPolicyRequest.target_resource in request: + query_params["targetResource"] = request.target_resource + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 + return compute.FirewallPoliciesListAssociationsResponse.from_json( + response.content, ignore_unknown_fields=True + ) + + def move( + self, + request: compute.MoveFirewallPolicyRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the move method over HTTP. + + Args: + request (~.compute.MoveFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.Move. See the method + description for details. + + 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 ``zonalOperations`` + resource. + + For more information, read Global, Regional, and Zonal + Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/locations/global/firewallPolicies/{firewall_policy}/move".format( + host=self._host, firewall_policy=request.firewall_policy, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.MoveFirewallPolicyRequest.parent_id in request: + query_params["parentId"] = request.parent_id + if compute.MoveFirewallPolicyRequest.request_id in request: + query_params["requestId"] = request.request_id + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers,) + + # 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 + return compute.Operation.from_json(response.content, ignore_unknown_fields=True) + + def patch( + self, + request: compute.PatchFirewallPolicyRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the patch method over HTTP. + + Args: + request (~.compute.PatchFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.Patch. See the method + description for details. + + 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 ``zonalOperations`` + resource. + + For more information, read Global, Regional, and Zonal + Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + + # Jsonify the request body + body = compute.FirewallPolicy.to_json( + request.firewall_policy_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/locations/global/firewallPolicies/{firewall_policy}".format( + host=self._host, firewall_policy=request.firewall_policy, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.PatchFirewallPolicyRequest.request_id in request: + query_params["requestId"] = request.request_id + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, 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 + return compute.Operation.from_json(response.content, ignore_unknown_fields=True) + + def patch_rule( + self, + request: compute.PatchRuleFirewallPolicyRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the patch rule method over HTTP. + + Args: + request (~.compute.PatchRuleFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.PatchRule. See the + method description for details. + + 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 ``zonalOperations`` + resource. + + For more information, read Global, Regional, and Zonal + Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + + # Jsonify the request body + body = compute.FirewallPolicyRule.to_json( + request.firewall_policy_rule_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/locations/global/firewallPolicies/{firewall_policy}/patchRule".format( + host=self._host, firewall_policy=request.firewall_policy, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.PatchRuleFirewallPolicyRequest.priority in request: + query_params["priority"] = request.priority + if compute.PatchRuleFirewallPolicyRequest.request_id in request: + query_params["requestId"] = request.request_id + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 + return compute.Operation.from_json(response.content, ignore_unknown_fields=True) + + def remove_association( + self, + request: compute.RemoveAssociationFirewallPolicyRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the remove association method over HTTP. + + Args: + request (~.compute.RemoveAssociationFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.RemoveAssociation. See + the method description for details. + + 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 ``zonalOperations`` + resource. + + For more information, read Global, Regional, and Zonal + Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/locations/global/firewallPolicies/{firewall_policy}/removeAssociation".format( + host=self._host, firewall_policy=request.firewall_policy, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.RemoveAssociationFirewallPolicyRequest.name in request: + query_params["name"] = request.name + if compute.RemoveAssociationFirewallPolicyRequest.request_id in request: + query_params["requestId"] = request.request_id + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers,) + + # 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 + return compute.Operation.from_json(response.content, ignore_unknown_fields=True) + + def remove_rule( + self, + request: compute.RemoveRuleFirewallPolicyRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the remove rule method over HTTP. + + Args: + request (~.compute.RemoveRuleFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.RemoveRule. See the + method description for details. + + 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 ``zonalOperations`` + resource. + + For more information, read Global, Regional, and Zonal + Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/locations/global/firewallPolicies/{firewall_policy}/removeRule".format( + host=self._host, firewall_policy=request.firewall_policy, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.RemoveRuleFirewallPolicyRequest.priority in request: + query_params["priority"] = request.priority + if compute.RemoveRuleFirewallPolicyRequest.request_id in request: + query_params["requestId"] = request.request_id + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers,) + + # 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 + return compute.Operation.from_json(response.content, ignore_unknown_fields=True) + + def set_iam_policy( + self, + request: compute.SetIamPolicyFirewallPolicyRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Policy: + r"""Call the set iam policy method over HTTP. + + Args: + request (~.compute.SetIamPolicyFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.SetIamPolicy. See the + method description for details. + + 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`` to a single + ``role``. Members 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 `__. + + """ + + # Jsonify the request body + body = compute.GlobalOrganizationSetPolicyRequest.to_json( + request.global_organization_set_policy_request_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/locations/global/firewallPolicies/{resource}/setIamPolicy".format( + host=self._host, resource=request.resource, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 + return compute.Policy.from_json(response.content, ignore_unknown_fields=True) + + def test_iam_permissions( + self, + request: compute.TestIamPermissionsFirewallPolicyRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.TestPermissionsResponse: + r"""Call the test iam permissions method over HTTP. + + Args: + request (~.compute.TestIamPermissionsFirewallPolicyRequest): + The request object. A request message for + FirewallPolicies.TestIamPermissions. See + the method description for details. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.TestPermissionsResponse: + + """ + + # Jsonify the request body + body = compute.TestPermissionsRequest.to_json( + request.test_permissions_request_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/locations/global/firewallPolicies/{resource}/testIamPermissions".format( + host=self._host, resource=request.resource, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 + return compute.TestPermissionsResponse.from_json( + response.content, ignore_unknown_fields=True + ) + + +__all__ = ("FirewallPoliciesRestTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/firewalls/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/firewalls/client.py index 5195d229c791..0d0193609dca 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/firewalls/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/firewalls/client.py @@ -48,7 +48,7 @@ class FirewallsClientMeta(type): _transport_registry["rest"] = FirewallsRestTransport def get_transport_class(cls, label: str = None,) -> Type[FirewallsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class FirewallsClient(metaclass=FirewallsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> FirewallsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - FirewallsTransport: The transport used by the client instance. + FirewallsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the firewalls client. + """Instantiates the firewalls client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/firewalls/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/firewalls/transports/base.py index 9ccefbb439f9..49f7a4f8415b 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/firewalls/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/firewalls/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class FirewallsTransport(abc.ABC): """Abstract transport class for Firewalls.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/firewalls/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/firewalls/transports/rest.py index ba9e66cfd98e..fed614c14992 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/firewalls/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/firewalls/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -162,10 +163,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -213,10 +218,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Firewall.from_json(response.content, ignore_unknown_fields=True) @@ -297,10 +306,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -353,10 +366,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.FirewallList.from_json( @@ -439,10 +456,14 @@ def patch( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -523,10 +544,14 @@ def update( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.put(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.put(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) 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 20206460ae9c..13f863fa406d 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 @@ -50,7 +50,7 @@ class ForwardingRulesClientMeta(type): _transport_registry["rest"] = ForwardingRulesRestTransport def get_transport_class(cls, label: str = None,) -> Type[ForwardingRulesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -73,7 +73,8 @@ class ForwardingRulesClient(metaclass=ForwardingRulesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -107,7 +108,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -124,7 +126,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -143,16 +145,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ForwardingRulesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - ForwardingRulesTransport: The transport used by the client instance. + ForwardingRulesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -165,7 +168,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -176,7 +179,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -187,7 +190,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -198,7 +201,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -217,7 +220,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the forwarding rules client. + """Instantiates the forwarding rules client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -272,9 +275,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -286,12 +290,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -306,8 +312,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -915,6 +921,125 @@ def patch( # Done; return the response. return response + def set_labels( + self, + request: compute.SetLabelsForwardingRuleRequest = None, + *, + project: str = None, + region: str = None, + resource: str = None, + region_set_labels_request_resource: compute.RegionSetLabelsRequest = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Sets the labels on the specified resource. To learn + more about labels, read the Labeling Resources + documentation. + + Args: + request (google.cloud.compute_v1.types.SetLabelsForwardingRuleRequest): + The request object. A request message for + ForwardingRules.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.cloud.compute_v1.types.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - [Global](/compute/docs/reference/rest/{$api_version}/globalOperations) + \* + [Regional](/compute/docs/reference/rest/{$api_version}/regionOperations) + \* + [Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations) + + 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 + zonalOperations resource. + + For more information, read Global, Regional, and + Zonal Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + # Create or coerce a protobuf request object. + # Sanity 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.SetLabelsForwardingRuleRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.SetLabelsForwardingRuleRequest): + request = compute.SetLabelsForwardingRuleRequest(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] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + def set_target( self, request: compute.SetTargetForwardingRuleRequest = None, diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/forwarding_rules/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/forwarding_rules/transports/base.py index bee99777ba4c..54a77e73160d 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/forwarding_rules/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/forwarding_rules/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class ForwardingRulesTransport(abc.ABC): """Abstract transport class for ForwardingRules.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -185,6 +164,9 @@ def _prep_wrapped_messages(self, client_info): self.patch: gapic_v1.method.wrap_method( self.patch, 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.set_target: gapic_v1.method.wrap_method( self.set_target, default_timeout=None, client_info=client_info, ), @@ -247,6 +229,15 @@ def patch( ]: raise NotImplementedError() + @property + def set_labels( + self, + ) -> Callable[ + [compute.SetLabelsForwardingRuleRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + @property def set_target( self, diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/forwarding_rules/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/forwarding_rules/transports/rest.py index 0a89f355e08d..73881b20dbdd 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/forwarding_rules/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/forwarding_rules/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -147,10 +148,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.ForwardingRuleAggregatedList.from_json( @@ -229,10 +234,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -301,10 +310,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.ForwardingRule.from_json( @@ -387,10 +400,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -446,10 +463,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.ForwardingRuleList.from_json( @@ -535,10 +556,105 @@ def patch( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 + return compute.Operation.from_json(response.content, ignore_unknown_fields=True) + + def set_labels( + self, + request: compute.SetLabelsForwardingRuleRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the set labels method over HTTP. + + Args: + request (~.compute.SetLabelsForwardingRuleRequest): + The request object. A request message for + ForwardingRules.SetLabels. See the + method description for details. + + 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 ``zonalOperations`` + resource. + + For more information, read Global, Regional, and Zonal + Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + + # Jsonify the request body + body = compute.RegionSetLabelsRequest.to_json( + request.region_set_labels_request_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/projects/{project}/regions/{region}/forwardingRules/{resource}/setLabels".format( + host=self._host, + project=request.project, + region=request.region, + resource=request.resource, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.SetLabelsForwardingRuleRequest.request_id in request: + query_params["requestId"] = request.request_id + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -622,10 +738,14 @@ def set_target( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_addresses/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_addresses/client.py index 70e8ecc7be5f..1d38702625ea 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_addresses/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_addresses/client.py @@ -50,7 +50,7 @@ class GlobalAddressesClientMeta(type): _transport_registry["rest"] = GlobalAddressesRestTransport def get_transport_class(cls, label: str = None,) -> Type[GlobalAddressesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -73,7 +73,8 @@ class GlobalAddressesClient(metaclass=GlobalAddressesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -107,7 +108,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -124,7 +126,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -143,16 +145,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> GlobalAddressesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - GlobalAddressesTransport: The transport used by the client instance. + GlobalAddressesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -165,7 +168,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -176,7 +179,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -187,7 +190,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -198,7 +201,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -217,7 +220,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the global addresses client. + """Instantiates the global addresses client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -272,9 +275,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -286,12 +290,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -306,8 +312,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_addresses/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_addresses/transports/base.py index 7933a80267e6..59d3eedaf560 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_addresses/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_addresses/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class GlobalAddressesTransport(abc.ABC): """Abstract transport class for GlobalAddresses.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_addresses/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_addresses/transports/rest.py index 443d4516f8a9..faa556af43a6 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_addresses/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_addresses/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -162,10 +163,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -237,10 +242,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Address.from_json(response.content, ignore_unknown_fields=True) @@ -321,10 +330,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -378,10 +391,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 return compute.AddressList.from_json( diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_forwarding_rules/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_forwarding_rules/client.py index 8b435bc85adf..93d9a28b54a1 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_forwarding_rules/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_forwarding_rules/client.py @@ -52,7 +52,7 @@ class GlobalForwardingRulesClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[GlobalForwardingRulesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -75,7 +75,8 @@ class GlobalForwardingRulesClient(metaclass=GlobalForwardingRulesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -109,7 +110,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -126,7 +128,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -145,16 +147,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> GlobalForwardingRulesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - GlobalForwardingRulesTransport: The transport used by the client instance. + GlobalForwardingRulesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -167,7 +170,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -178,7 +181,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -189,7 +192,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -200,7 +203,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -219,7 +222,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the global forwarding rules client. + """Instantiates the global forwarding rules client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -274,9 +277,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -288,12 +292,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -308,8 +314,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -796,6 +802,117 @@ def patch( # Done; return the response. return response + def set_labels( + self, + request: compute.SetLabelsGlobalForwardingRuleRequest = None, + *, + project: str = None, + resource: str = None, + global_set_labels_request_resource: compute.GlobalSetLabelsRequest = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Sets the labels on the specified resource. To learn + more about labels, read the Labeling Resources + documentation. + + Args: + request (google.cloud.compute_v1.types.SetLabelsGlobalForwardingRuleRequest): + The request object. A request message for + GlobalForwardingRules.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. + resource (str): + Name or id of the resource for this + request. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + global_set_labels_request_resource (google.cloud.compute_v1.types.GlobalSetLabelsRequest): + The body resource for this request + This corresponds to the ``global_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.cloud.compute_v1.types.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - [Global](/compute/docs/reference/rest/{$api_version}/globalOperations) + \* + [Regional](/compute/docs/reference/rest/{$api_version}/regionOperations) + \* + [Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations) + + 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 + zonalOperations resource. + + For more information, read Global, Regional, and + Zonal Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + # Create or coerce a protobuf request object. + # Sanity 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, resource, global_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.SetLabelsGlobalForwardingRuleRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.SetLabelsGlobalForwardingRuleRequest): + request = compute.SetLabelsGlobalForwardingRuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if resource is not None: + request.resource = resource + if global_set_labels_request_resource is not None: + request.global_set_labels_request_resource = ( + global_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] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + def set_target( self, request: compute.SetTargetGlobalForwardingRuleRequest = None, diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_forwarding_rules/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_forwarding_rules/transports/base.py index 23a32b6b6938..5bb7546144cb 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_forwarding_rules/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_forwarding_rules/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class GlobalForwardingRulesTransport(abc.ABC): """Abstract transport class for GlobalForwardingRules.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -182,6 +161,9 @@ def _prep_wrapped_messages(self, client_info): self.patch: gapic_v1.method.wrap_method( self.patch, 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.set_target: gapic_v1.method.wrap_method( self.set_target, default_timeout=None, client_info=client_info, ), @@ -232,6 +214,15 @@ def patch( ]: raise NotImplementedError() + @property + def set_labels( + self, + ) -> Callable[ + [compute.SetLabelsGlobalForwardingRuleRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + @property def set_target( self, diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_forwarding_rules/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_forwarding_rules/transports/rest.py index d07e82db73d6..ffe0c27b1514 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_forwarding_rules/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_forwarding_rules/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -164,10 +165,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -235,10 +240,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.ForwardingRule.from_json( @@ -321,10 +330,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -380,10 +393,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.ForwardingRuleList.from_json( @@ -468,10 +485,100 @@ def patch( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 + return compute.Operation.from_json(response.content, ignore_unknown_fields=True) + + def set_labels( + self, + request: compute.SetLabelsGlobalForwardingRuleRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the set labels method over HTTP. + + Args: + request (~.compute.SetLabelsGlobalForwardingRuleRequest): + The request object. A request message for + GlobalForwardingRules.SetLabels. See the + method description for details. + + 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 ``zonalOperations`` + resource. + + For more information, read Global, Regional, and Zonal + Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + + # Jsonify the request body + body = compute.GlobalSetLabelsRequest.to_json( + request.global_set_labels_request_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/projects/{project}/global/forwardingRules/{resource}/setLabels".format( + host=self._host, project=request.project, resource=request.resource, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -554,10 +661,14 @@ def set_target( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_network_endpoint_groups/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_network_endpoint_groups/client.py index 89dfd12cff88..ecec4662eccd 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_network_endpoint_groups/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_network_endpoint_groups/client.py @@ -52,7 +52,7 @@ class GlobalNetworkEndpointGroupsClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[GlobalNetworkEndpointGroupsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -77,7 +77,8 @@ class GlobalNetworkEndpointGroupsClient( @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -111,7 +112,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -128,7 +130,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -147,16 +149,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> GlobalNetworkEndpointGroupsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - GlobalNetworkEndpointGroupsTransport: The transport used by the client instance. + GlobalNetworkEndpointGroupsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -169,7 +172,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -180,7 +183,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -191,7 +194,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -202,7 +205,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -221,7 +224,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the global network endpoint groups client. + """Instantiates the global network endpoint groups client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -276,9 +279,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -290,12 +294,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -310,8 +316,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_network_endpoint_groups/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_network_endpoint_groups/transports/base.py index abc9c48202d0..64c3f6d8fff9 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_network_endpoint_groups/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_network_endpoint_groups/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class GlobalNetworkEndpointGroupsTransport(abc.ABC): """Abstract transport class for GlobalNetworkEndpointGroups.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_network_endpoint_groups/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_network_endpoint_groups/transports/rest.py index 7a599103f882..9a311b2b6d95 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_network_endpoint_groups/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_network_endpoint_groups/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -174,10 +175,14 @@ def attach_network_endpoints( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -253,10 +258,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -342,10 +351,14 @@ def detach_network_endpoints( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -404,10 +417,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.NetworkEndpointGroup.from_json( @@ -490,10 +507,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -550,10 +571,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.NetworkEndpointGroupList.from_json( @@ -626,10 +651,14 @@ def list_network_endpoints( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers,) + + # 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 return compute.NetworkEndpointGroupsListNetworkEndpoints.from_json( 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 52239171cf95..6587dca2146c 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 @@ -50,7 +50,7 @@ class GlobalOperationsClientMeta(type): _transport_registry["rest"] = GlobalOperationsRestTransport def get_transport_class(cls, label: str = None,) -> Type[GlobalOperationsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -73,7 +73,8 @@ class GlobalOperationsClient(metaclass=GlobalOperationsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -107,7 +108,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -124,7 +126,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -143,16 +145,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> GlobalOperationsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - GlobalOperationsTransport: The transport used by the client instance. + GlobalOperationsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -165,7 +168,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -176,7 +179,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -187,7 +190,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -198,7 +201,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -217,7 +220,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the global operations client. + """Instantiates the global operations client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -272,9 +275,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -286,12 +290,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -306,8 +312,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_operations/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_operations/transports/base.py index 6a7e5f3521d2..739ea72281d2 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_operations/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_operations/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class GlobalOperationsTransport(abc.ABC): """Abstract transport class for GlobalOperations.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_operations/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_operations/transports/rest.py index f47f32e9ebde..07c85796aee5 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_operations/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_operations/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -147,10 +148,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.OperationAggregatedList.from_json( @@ -199,10 +204,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.DeleteGlobalOperationResponse.from_json( @@ -276,10 +285,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -335,10 +348,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.OperationList.from_json( @@ -412,10 +429,14 @@ def wait( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers,) + + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_organization_operations/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_organization_operations/client.py index 3a3a87cea44a..e3b3bc6ea48a 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_organization_operations/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_organization_operations/client.py @@ -52,7 +52,7 @@ class GlobalOrganizationOperationsClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[GlobalOrganizationOperationsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -77,7 +77,8 @@ class GlobalOrganizationOperationsClient( @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -111,7 +112,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -128,7 +130,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -147,16 +149,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> GlobalOrganizationOperationsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - GlobalOrganizationOperationsTransport: The transport used by the client instance. + GlobalOrganizationOperationsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -169,7 +172,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -180,7 +183,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -191,7 +194,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -202,7 +205,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -221,7 +224,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the global organization operations client. + """Instantiates the global organization operations client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -276,9 +279,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -290,12 +294,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -310,8 +316,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_organization_operations/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_organization_operations/transports/base.py index ef78ef50a096..bc05e03b7f67 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_organization_operations/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_organization_operations/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class GlobalOrganizationOperationsTransport(abc.ABC): """Abstract transport class for GlobalOrganizationOperations.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_organization_operations/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_organization_operations/transports/rest.py index f92e7e235577..6c8b90dcbe40 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_organization_operations/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_organization_operations/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -137,10 +138,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.DeleteGlobalOrganizationOperationResponse.from_json( @@ -216,10 +221,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -280,10 +289,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 return compute.OperationList.from_json( diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_public_delegated_prefixes/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_public_delegated_prefixes/__init__.py new file mode 100644 index 000000000000..3bf944f01aa3 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_public_delegated_prefixes/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 GlobalPublicDelegatedPrefixesClient + +__all__ = ("GlobalPublicDelegatedPrefixesClient",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_public_delegated_prefixes/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_public_delegated_prefixes/client.py new file mode 100644 index 000000000000..bf7f0e8141fc --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_public_delegated_prefixes/client.py @@ -0,0 +1,806 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.compute_v1.services.global_public_delegated_prefixes import pagers +from google.cloud.compute_v1.types import compute +from .transports.base import GlobalPublicDelegatedPrefixesTransport, DEFAULT_CLIENT_INFO +from .transports.rest import GlobalPublicDelegatedPrefixesRestTransport + + +class GlobalPublicDelegatedPrefixesClientMeta(type): + """Metaclass for the GlobalPublicDelegatedPrefixes 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[GlobalPublicDelegatedPrefixesTransport]] + _transport_registry["rest"] = GlobalPublicDelegatedPrefixesRestTransport + + def get_transport_class( + cls, label: str = None, + ) -> Type[GlobalPublicDelegatedPrefixesTransport]: + """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 GlobalPublicDelegatedPrefixesClient( + metaclass=GlobalPublicDelegatedPrefixesClientMeta +): + """The GlobalPublicDelegatedPrefixes 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") + + DEFAULT_ENDPOINT = "compute.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @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: + GlobalPublicDelegatedPrefixesClient: 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: + GlobalPublicDelegatedPrefixesClient: 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) -> GlobalPublicDelegatedPrefixesTransport: + """Returns the transport used by the client instance. + + Returns: + GlobalPublicDelegatedPrefixesTransport: 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 {} + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, GlobalPublicDelegatedPrefixesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the global public delegated prefixes 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, GlobalPublicDelegatedPrefixesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "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). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS 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. + 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. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, GlobalPublicDelegatedPrefixesTransport): + # transport is a GlobalPublicDelegatedPrefixesTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def delete( + self, + request: compute.DeleteGlobalPublicDelegatedPrefixeRequest = None, + *, + project: str = None, + public_delegated_prefix: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Deletes the specified global PublicDelegatedPrefix. + + Args: + request (google.cloud.compute_v1.types.DeleteGlobalPublicDelegatedPrefixeRequest): + The request object. A request message for + GlobalPublicDelegatedPrefixes.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. + public_delegated_prefix (str): + Name of the PublicDelegatedPrefix + resource to delete. + + This corresponds to the ``public_delegated_prefix`` 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.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - [Global](/compute/docs/reference/rest/{$api_version}/globalOperations) + \* + [Regional](/compute/docs/reference/rest/{$api_version}/regionOperations) + \* + [Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations) + + 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 + zonalOperations resource. + + For more information, read Global, Regional, and + Zonal Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + # Create or coerce a protobuf request object. + # Sanity 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, public_delegated_prefix]) + if request is 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.DeleteGlobalPublicDelegatedPrefixeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.DeleteGlobalPublicDelegatedPrefixeRequest): + request = compute.DeleteGlobalPublicDelegatedPrefixeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if public_delegated_prefix is not None: + request.public_delegated_prefix = public_delegated_prefix + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get( + self, + request: compute.GetGlobalPublicDelegatedPrefixeRequest = None, + *, + project: str = None, + public_delegated_prefix: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.PublicDelegatedPrefix: + r"""Returns the specified global PublicDelegatedPrefix + resource. + + Args: + request (google.cloud.compute_v1.types.GetGlobalPublicDelegatedPrefixeRequest): + The request object. A request message for + GlobalPublicDelegatedPrefixes.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. + public_delegated_prefix (str): + Name of the PublicDelegatedPrefix + resource to return. + + This corresponds to the ``public_delegated_prefix`` 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.PublicDelegatedPrefix: + A PublicDelegatedPrefix resource + represents an IP block within a + PublicAdvertisedPrefix that is + configured within a single cloud scope + (global or region). IPs in the block can + be allocated to resources within that + scope. Public delegated prefixes may be + further broken up into smaller IP blocks + in the same scope as the parent block. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, public_delegated_prefix]) + if request is 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.GetGlobalPublicDelegatedPrefixeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.GetGlobalPublicDelegatedPrefixeRequest): + request = compute.GetGlobalPublicDelegatedPrefixeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if public_delegated_prefix is not None: + request.public_delegated_prefix = public_delegated_prefix + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def insert( + self, + request: compute.InsertGlobalPublicDelegatedPrefixeRequest = None, + *, + project: str = None, + public_delegated_prefix_resource: compute.PublicDelegatedPrefix = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Creates a global PublicDelegatedPrefix in the + specified project using the parameters that are included + in the request. + + Args: + request (google.cloud.compute_v1.types.InsertGlobalPublicDelegatedPrefixeRequest): + The request object. A request message for + GlobalPublicDelegatedPrefixes.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. + public_delegated_prefix_resource (google.cloud.compute_v1.types.PublicDelegatedPrefix): + The body resource for this request + This corresponds to the ``public_delegated_prefix_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.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - [Global](/compute/docs/reference/rest/{$api_version}/globalOperations) + \* + [Regional](/compute/docs/reference/rest/{$api_version}/regionOperations) + \* + [Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations) + + 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 + zonalOperations resource. + + For more information, read Global, Regional, and + Zonal Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + # Create or coerce a protobuf request object. + # Sanity 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, public_delegated_prefix_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.InsertGlobalPublicDelegatedPrefixeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.InsertGlobalPublicDelegatedPrefixeRequest): + request = compute.InsertGlobalPublicDelegatedPrefixeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if public_delegated_prefix_resource is not None: + request.public_delegated_prefix_resource = ( + public_delegated_prefix_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list( + self, + request: compute.ListGlobalPublicDelegatedPrefixesRequest = None, + *, + project: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPager: + r"""Lists the global PublicDelegatedPrefixes for a + project. + + Args: + request (google.cloud.compute_v1.types.ListGlobalPublicDelegatedPrefixesRequest): + The request object. A request message for + GlobalPublicDelegatedPrefixes.List. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.compute_v1.services.global_public_delegated_prefixes.pagers.ListPager: + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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.ListGlobalPublicDelegatedPrefixesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.ListGlobalPublicDelegatedPrefixesRequest): + request = compute.ListGlobalPublicDelegatedPrefixesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list] + + # 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 patch( + self, + request: compute.PatchGlobalPublicDelegatedPrefixeRequest = None, + *, + project: str = None, + public_delegated_prefix: str = None, + public_delegated_prefix_resource: compute.PublicDelegatedPrefix = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Patches the specified global PublicDelegatedPrefix + resource with the data included in the request. This + method supports PATCH semantics and uses JSON merge + patch format and processing rules. + + Args: + request (google.cloud.compute_v1.types.PatchGlobalPublicDelegatedPrefixeRequest): + The request object. A request message for + GlobalPublicDelegatedPrefixes.Patch. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + public_delegated_prefix (str): + Name of the PublicDelegatedPrefix + resource to patch. + + This corresponds to the ``public_delegated_prefix`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + public_delegated_prefix_resource (google.cloud.compute_v1.types.PublicDelegatedPrefix): + The body resource for this request + This corresponds to the ``public_delegated_prefix_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.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - [Global](/compute/docs/reference/rest/{$api_version}/globalOperations) + \* + [Regional](/compute/docs/reference/rest/{$api_version}/regionOperations) + \* + [Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations) + + 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 + zonalOperations resource. + + For more information, read Global, Regional, and + Zonal Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + # Create or coerce a protobuf request object. + # Sanity 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, public_delegated_prefix, public_delegated_prefix_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.PatchGlobalPublicDelegatedPrefixeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.PatchGlobalPublicDelegatedPrefixeRequest): + request = compute.PatchGlobalPublicDelegatedPrefixeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if public_delegated_prefix is not None: + request.public_delegated_prefix = public_delegated_prefix + if public_delegated_prefix_resource is not None: + request.public_delegated_prefix_resource = ( + public_delegated_prefix_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.patch] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("GlobalPublicDelegatedPrefixesClient",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_public_delegated_prefixes/pagers.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_public_delegated_prefixes/pagers.py new file mode 100644 index 000000000000..37ed65a541fd --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_public_delegated_prefixes/pagers.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, + AsyncIterable, + Awaitable, + Callable, + Iterable, + Sequence, + Tuple, + Optional, +) + +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.PublicDelegatedPrefixList` 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.PublicDelegatedPrefixList` + 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.PublicDelegatedPrefixList], + request: compute.ListGlobalPublicDelegatedPrefixesRequest, + response: compute.PublicDelegatedPrefixList, + *, + 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.ListGlobalPublicDelegatedPrefixesRequest): + The initial request object. + response (google.cloud.compute_v1.types.PublicDelegatedPrefixList): + 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.ListGlobalPublicDelegatedPrefixesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[compute.PublicDelegatedPrefixList]: + 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) -> Iterable[compute.PublicDelegatedPrefix]: + for page in self.pages: + yield from page.items + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_public_delegated_prefixes/transports/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_public_delegated_prefixes/transports/__init__.py new file mode 100644 index 000000000000..f2a839cba36d --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_public_delegated_prefixes/transports/__init__.py @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 GlobalPublicDelegatedPrefixesTransport +from .rest import GlobalPublicDelegatedPrefixesRestTransport + + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[GlobalPublicDelegatedPrefixesTransport]] +_transport_registry["rest"] = GlobalPublicDelegatedPrefixesRestTransport + +__all__ = ( + "GlobalPublicDelegatedPrefixesTransport", + "GlobalPublicDelegatedPrefixesRestTransport", +) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_public_delegated_prefixes/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_public_delegated_prefixes/transports/base.py new file mode 100644 index 000000000000..38fd07454948 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_public_delegated_prefixes/transports/base.py @@ -0,0 +1,215 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 packaging.version +import pkg_resources +from requests import __version__ as requests_version + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.compute_v1.types import compute + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class GlobalPublicDelegatedPrefixesTransport(abc.ABC): + """Abstract transport class for GlobalPublicDelegatedPrefixes.""" + + 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: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + 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. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_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 + ) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + 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.insert: gapic_v1.method.wrap_method( + self.insert, default_timeout=None, client_info=client_info, + ), + self.list: gapic_v1.method.wrap_method( + self.list, default_timeout=None, client_info=client_info, + ), + self.patch: gapic_v1.method.wrap_method( + self.patch, default_timeout=None, client_info=client_info, + ), + } + + @property + def delete( + self, + ) -> Callable[ + [compute.DeleteGlobalPublicDelegatedPrefixeRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def get( + self, + ) -> Callable[ + [compute.GetGlobalPublicDelegatedPrefixeRequest], + Union[compute.PublicDelegatedPrefix, Awaitable[compute.PublicDelegatedPrefix]], + ]: + raise NotImplementedError() + + @property + def insert( + self, + ) -> Callable[ + [compute.InsertGlobalPublicDelegatedPrefixeRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def list( + self, + ) -> Callable[ + [compute.ListGlobalPublicDelegatedPrefixesRequest], + Union[ + compute.PublicDelegatedPrefixList, + Awaitable[compute.PublicDelegatedPrefixList], + ], + ]: + raise NotImplementedError() + + @property + def patch( + self, + ) -> Callable[ + [compute.PatchGlobalPublicDelegatedPrefixeRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + +__all__ = ("GlobalPublicDelegatedPrefixesTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_public_delegated_prefixes/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_public_delegated_prefixes/transports/rest.py new file mode 100644 index 000000000000..577054bca2f7 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_public_delegated_prefixes/transports/rest.py @@ -0,0 +1,491 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # 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.auth.transport.requests import AuthorizedSession + +from google.cloud.compute_v1.types import compute + +from .base import GlobalPublicDelegatedPrefixesTransport, DEFAULT_CLIENT_INFO + + +class GlobalPublicDelegatedPrefixesRestTransport( + GlobalPublicDelegatedPrefixesTransport +): + """REST backend transport for GlobalPublicDelegatedPrefixes. + + The GlobalPublicDelegatedPrefixes API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "compute.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + 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're developing + your own client library. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, credentials=credentials, client_info=client_info, + ) + 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._prep_wrapped_messages(client_info) + + def delete( + self, + request: compute.DeleteGlobalPublicDelegatedPrefixeRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the delete method over HTTP. + + Args: + request (~.compute.DeleteGlobalPublicDelegatedPrefixeRequest): + The request object. A request message for + GlobalPublicDelegatedPrefixes.Delete. + See the method description for details. + + 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 ``zonalOperations`` + resource. + + For more information, read Global, Regional, and Zonal + Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/projects/{project}/global/publicDelegatedPrefixes/{public_delegated_prefix}".format( + host=self._host, + project=request.project, + public_delegated_prefix=request.public_delegated_prefix, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.DeleteGlobalPublicDelegatedPrefixeRequest.request_id in request: + query_params["requestId"] = request.request_id + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) + + # 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 + return compute.Operation.from_json(response.content, ignore_unknown_fields=True) + + def get( + self, + request: compute.GetGlobalPublicDelegatedPrefixeRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.PublicDelegatedPrefix: + r"""Call the get method over HTTP. + + Args: + request (~.compute.GetGlobalPublicDelegatedPrefixeRequest): + The request object. A request message for + GlobalPublicDelegatedPrefixes.Get. See + the method description for details. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.PublicDelegatedPrefix: + A PublicDelegatedPrefix resource + represents an IP block within a + PublicAdvertisedPrefix that is + configured within a single cloud scope + (global or region). IPs in the block can + be allocated to resources within that + scope. Public delegated prefixes may be + further broken up into smaller IP blocks + in the same scope as the parent block. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/projects/{project}/global/publicDelegatedPrefixes/{public_delegated_prefix}".format( + host=self._host, + project=request.project, + public_delegated_prefix=request.public_delegated_prefix, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 + return compute.PublicDelegatedPrefix.from_json( + response.content, ignore_unknown_fields=True + ) + + def insert( + self, + request: compute.InsertGlobalPublicDelegatedPrefixeRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the insert method over HTTP. + + Args: + request (~.compute.InsertGlobalPublicDelegatedPrefixeRequest): + The request object. A request message for + GlobalPublicDelegatedPrefixes.Insert. + See the method description for details. + + 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 ``zonalOperations`` + resource. + + For more information, read Global, Regional, and Zonal + Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + + # Jsonify the request body + body = compute.PublicDelegatedPrefix.to_json( + request.public_delegated_prefix_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/projects/{project}/global/publicDelegatedPrefixes".format( + host=self._host, project=request.project, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.InsertGlobalPublicDelegatedPrefixeRequest.request_id in request: + query_params["requestId"] = request.request_id + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 + return compute.Operation.from_json(response.content, ignore_unknown_fields=True) + + def list( + self, + request: compute.ListGlobalPublicDelegatedPrefixesRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.PublicDelegatedPrefixList: + r"""Call the list method over HTTP. + + Args: + request (~.compute.ListGlobalPublicDelegatedPrefixesRequest): + The request object. A request message for + GlobalPublicDelegatedPrefixes.List. See + the method description for details. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.PublicDelegatedPrefixList: + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/projects/{project}/global/publicDelegatedPrefixes".format( + host=self._host, project=request.project, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.ListGlobalPublicDelegatedPrefixesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListGlobalPublicDelegatedPrefixesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListGlobalPublicDelegatedPrefixesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListGlobalPublicDelegatedPrefixesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if ( + compute.ListGlobalPublicDelegatedPrefixesRequest.return_partial_success + in request + ): + query_params["returnPartialSuccess"] = request.return_partial_success + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 + return compute.PublicDelegatedPrefixList.from_json( + response.content, ignore_unknown_fields=True + ) + + def patch( + self, + request: compute.PatchGlobalPublicDelegatedPrefixeRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the patch method over HTTP. + + Args: + request (~.compute.PatchGlobalPublicDelegatedPrefixeRequest): + The request object. A request message for + GlobalPublicDelegatedPrefixes.Patch. See + the method description for details. + + 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 ``zonalOperations`` + resource. + + For more information, read Global, Regional, and Zonal + Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + + # Jsonify the request body + body = compute.PublicDelegatedPrefix.to_json( + request.public_delegated_prefix_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/projects/{project}/global/publicDelegatedPrefixes/{public_delegated_prefix}".format( + host=self._host, + project=request.project, + public_delegated_prefix=request.public_delegated_prefix, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.PatchGlobalPublicDelegatedPrefixeRequest.request_id in request: + query_params["requestId"] = request.request_id + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, 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 + return compute.Operation.from_json(response.content, ignore_unknown_fields=True) + + +__all__ = ("GlobalPublicDelegatedPrefixesRestTransport",) 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 9747cb7102cd..fc583508271a 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 @@ -48,7 +48,7 @@ class HealthChecksClientMeta(type): _transport_registry["rest"] = HealthChecksRestTransport def get_transport_class(cls, label: str = None,) -> Type[HealthChecksTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class HealthChecksClient(metaclass=HealthChecksClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> HealthChecksTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - HealthChecksTransport: The transport used by the client instance. + HealthChecksTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the health checks client. + """Instantiates the health checks client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/health_checks/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/health_checks/transports/base.py index c5240e6d6f17..c4088ac14721 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/health_checks/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/health_checks/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class HealthChecksTransport(abc.ABC): """Abstract transport class for HealthChecks.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/health_checks/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/health_checks/transports/rest.py index 7712fc0722be..e1271e5cf4c5 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/health_checks/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/health_checks/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -144,10 +145,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.HealthChecksAggregatedList.from_json( @@ -223,10 +228,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -298,10 +307,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.HealthCheck.from_json( @@ -384,10 +397,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -443,10 +460,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.HealthCheckList.from_json( @@ -529,10 +550,14 @@ def patch( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -613,10 +638,14 @@ def update( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.put(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.put(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/images/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/images/client.py index 6d3a5edc1846..916282573b34 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/images/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/images/client.py @@ -48,7 +48,7 @@ class ImagesClientMeta(type): _transport_registry["rest"] = ImagesRestTransport def get_transport_class(cls, label: str = None,) -> Type[ImagesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class ImagesClient(metaclass=ImagesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ImagesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - ImagesTransport: The transport used by the client instance. + ImagesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the images client. + """Instantiates the images client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/images/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/images/transports/base.py index 22c6d7ef1ea7..96cd7abcf3d7 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/images/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/images/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class ImagesTransport(abc.ABC): """Abstract transport class for Images.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/images/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/images/transports/rest.py index 3b6d735cffb9..9ee104adb650 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/images/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/images/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -161,10 +162,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -245,10 +250,14 @@ def deprecate( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -296,10 +305,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Image.from_json(response.content, ignore_unknown_fields=True) @@ -348,10 +361,14 @@ def get_from_family( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Image.from_json(response.content, ignore_unknown_fields=True) @@ -449,10 +466,14 @@ def get_iam_policy( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Policy.from_json(response.content, ignore_unknown_fields=True) @@ -534,10 +555,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -590,10 +615,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.ImageList.from_json(response.content, ignore_unknown_fields=True) @@ -673,10 +702,14 @@ def patch( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -777,10 +810,14 @@ def set_iam_policy( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Policy.from_json(response.content, ignore_unknown_fields=True) @@ -859,10 +896,14 @@ def set_labels( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -913,10 +954,14 @@ def test_iam_permissions( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.TestPermissionsResponse.from_json( 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 5484b954415b..0a66d5014b34 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 @@ -52,7 +52,7 @@ class InstanceGroupManagersClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[InstanceGroupManagersTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -75,7 +75,8 @@ class InstanceGroupManagersClient(metaclass=InstanceGroupManagersClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -109,7 +110,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -126,7 +128,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -145,16 +147,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> InstanceGroupManagersTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - InstanceGroupManagersTransport: The transport used by the client instance. + InstanceGroupManagersTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -167,7 +170,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -178,7 +181,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -189,7 +192,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -200,7 +203,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -219,7 +222,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the instance group managers client. + """Instantiates the instance group managers client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -274,9 +277,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -288,12 +292,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -308,8 +314,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -2054,18 +2060,18 @@ def recreate_instances( timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Operation: - r"""Flags the specified instances in the managed instance - group to be immediately recreated. The instances are - deleted and recreated using the current instance - template for the managed instance group. This operation - is marked as DONE when the flag is set even if the - instances have not yet been recreated. You must - separately verify the status of the recreating action - with the listmanagedinstances method. If the group is - part of a backend service that has enabled connection - draining, it can take up to 60 seconds after the - connection draining duration has elapsed before the VM - instance is removed or deleted. + r"""Flags the specified VM instances in the managed + instance group to be immediately recreated. Each + instance is recreated using the group's current + configuration. This operation is marked as DONE when the + flag is set even if the instances have not yet been + recreated. You must separately verify the status of each + instance by checking its currentAction field; for more + information, see Checking the status of managed + instances. If the group is part of a backend service + that has enabled connection draining, it can take up to + 60 seconds after the connection draining duration has + elapsed before the VM instance is removed or deleted. You can specify a maximum of 1000 instances with this method per request. diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_group_managers/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_group_managers/transports/base.py index 65462ca241b9..624aabce5aa5 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_group_managers/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_group_managers/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class InstanceGroupManagersTransport(abc.ABC): """Abstract transport class for InstanceGroupManagers.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_group_managers/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_group_managers/transports/rest.py index daa4607abda4..e23838ca81ec 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_group_managers/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_group_managers/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -172,10 +173,14 @@ def abandon_instances( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -237,10 +242,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.InstanceGroupManagerAggregatedList.from_json( @@ -325,10 +334,14 @@ def apply_updates_to_instances( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -412,10 +425,14 @@ def create_instances( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -492,10 +509,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -579,10 +600,14 @@ def delete_instances( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -665,10 +690,14 @@ def delete_per_instance_configs( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -729,10 +758,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.InstanceGroupManager.from_json( @@ -815,10 +848,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -872,10 +909,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.InstanceGroupManagerList.from_json( @@ -937,10 +978,14 @@ def list_errors( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.InstanceGroupManagersListErrorsResponse.from_json( @@ -1008,10 +1053,14 @@ def list_managed_instances( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.InstanceGroupManagersListManagedInstancesResponse.from_json( @@ -1082,10 +1131,14 @@ def list_per_instance_configs( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.InstanceGroupManagersListPerInstanceConfigsResp.from_json( @@ -1171,10 +1224,14 @@ def patch( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -1262,10 +1319,14 @@ def patch_per_instance_configs( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -1349,10 +1410,14 @@ def recreate_instances( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -1431,10 +1496,14 @@ def resize( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -1518,10 +1587,14 @@ def set_instance_template( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -1605,10 +1678,14 @@ def set_target_pools( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -1696,10 +1773,14 @@ def update_per_instance_configs( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) 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 8c2a02340d3d..c861b2dc9a33 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 @@ -50,7 +50,7 @@ class InstanceGroupsClientMeta(type): _transport_registry["rest"] = InstanceGroupsRestTransport def get_transport_class(cls, label: str = None,) -> Type[InstanceGroupsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -73,7 +73,8 @@ class InstanceGroupsClient(metaclass=InstanceGroupsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -107,7 +108,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -124,7 +126,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -143,16 +145,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> InstanceGroupsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - InstanceGroupsTransport: The transport used by the client instance. + InstanceGroupsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -165,7 +168,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -176,7 +179,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -187,7 +190,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -198,7 +201,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -217,7 +220,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the instance groups client. + """Instantiates the instance groups client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -272,9 +275,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -286,12 +290,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -306,8 +312,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_groups/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_groups/transports/base.py index a43607dadfcc..4fa60b1d2409 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_groups/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_groups/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class InstanceGroupsTransport(abc.ABC): """Abstract transport class for InstanceGroups.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_groups/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_groups/transports/rest.py index 63d2c7c0c7b0..3cace55f6ed4 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_groups/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_groups/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -172,10 +173,14 @@ def add_instances( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -234,10 +239,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.InstanceGroupAggregatedList.from_json( @@ -316,10 +325,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -386,10 +399,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.InstanceGroup.from_json( @@ -472,10 +489,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -529,10 +550,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.InstanceGroupList.from_json( @@ -598,10 +623,14 @@ def list_instances( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.InstanceGroupsListInstances.from_json( @@ -687,10 +716,14 @@ def remove_instances( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -774,10 +807,14 @@ def set_named_ports( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) 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 94603ad5df66..f2e1ba7215aa 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 @@ -52,7 +52,7 @@ class InstanceTemplatesClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[InstanceTemplatesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -75,7 +75,8 @@ class InstanceTemplatesClient(metaclass=InstanceTemplatesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -109,7 +110,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -126,7 +128,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -145,16 +147,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> InstanceTemplatesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - InstanceTemplatesTransport: The transport used by the client instance. + InstanceTemplatesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -167,7 +170,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -178,7 +181,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -189,7 +192,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -200,7 +203,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -219,7 +222,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the instance templates client. + """Instantiates the instance templates client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -274,9 +277,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -288,12 +292,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -308,8 +314,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_templates/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_templates/transports/base.py index f0f9ee394624..2fae32fffdde 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_templates/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_templates/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class InstanceTemplatesTransport(abc.ABC): """Abstract transport class for InstanceTemplates.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_templates/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_templates/transports/rest.py index 529c9c7b669a..b76edeb0f529 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_templates/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_templates/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -164,10 +165,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -219,10 +224,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.InstanceTemplate.from_json( @@ -325,10 +334,14 @@ def get_iam_policy( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Policy.from_json(response.content, ignore_unknown_fields=True) @@ -409,10 +422,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -466,10 +483,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.InstanceTemplateList.from_json( @@ -572,10 +593,14 @@ def set_iam_policy( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Policy.from_json(response.content, ignore_unknown_fields=True) @@ -626,10 +651,14 @@ def test_iam_permissions( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.TestPermissionsResponse.from_json( 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 120e78a47348..3f58a290d41b 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 @@ -48,7 +48,7 @@ class InstancesClientMeta(type): _transport_registry["rest"] = InstancesRestTransport def get_transport_class(cls, label: str = None,) -> Type[InstancesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class InstancesClient(metaclass=InstancesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> InstancesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - InstancesTransport: The transport used by the client instance. + InstancesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the instances client. + """Instantiates the instances client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -754,6 +760,116 @@ def attach_disk( # Done; return the response. return response + def bulk_insert( + self, + request: compute.BulkInsertInstanceRequest = None, + *, + project: str = None, + zone: str = None, + bulk_insert_instance_resource_resource: compute.BulkInsertInstanceResource = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Creates multiple instances. Count specifies the + number of instances to create. + + Args: + request (google.cloud.compute_v1.types.BulkInsertInstanceRequest): + The request object. A request message for + Instances.BulkInsert. 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. + bulk_insert_instance_resource_resource (google.cloud.compute_v1.types.BulkInsertInstanceResource): + The body resource for this request + This corresponds to the ``bulk_insert_instance_resource_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.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - [Global](/compute/docs/reference/rest/{$api_version}/globalOperations) + \* + [Regional](/compute/docs/reference/rest/{$api_version}/regionOperations) + \* + [Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations) + + 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 + zonalOperations resource. + + For more information, read Global, Regional, and + Zonal Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + # Create or coerce a protobuf request object. + # Sanity 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, bulk_insert_instance_resource_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.BulkInsertInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.BulkInsertInstanceRequest): + request = compute.BulkInsertInstanceRequest(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 bulk_insert_instance_resource_resource is not None: + request.bulk_insert_instance_resource_resource = ( + bulk_insert_instance_resource_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.bulk_insert] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + def delete( self, request: compute.DeleteInstanceRequest = None, @@ -766,7 +882,7 @@ def delete( metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Operation: r"""Deletes the specified Instance resource. For more - information, see Stopping or Deleting an Instance. + information, see Deleting an instance. Args: request (google.cloud.compute_v1.types.DeleteInstanceRequest): @@ -1193,6 +1309,99 @@ def get( # Done; return the response. return response + def get_effective_firewalls( + self, + request: compute.GetEffectiveFirewallsInstanceRequest = None, + *, + project: str = None, + zone: str = None, + instance: str = None, + network_interface: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.InstancesGetEffectiveFirewallsResponse: + r"""Returns effective firewalls applied to an interface + of the instance. + + Args: + request (google.cloud.compute_v1.types.GetEffectiveFirewallsInstanceRequest): + The request object. A request message for + Instances.GetEffectiveFirewalls. 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. + instance (str): + Name of the instance scoping this + request. + + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network_interface (str): + The name of the network interface to + get the effective firewalls. + + This corresponds to the ``network_interface`` 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.InstancesGetEffectiveFirewallsResponse: + + """ + # Create or coerce a protobuf request object. + # Sanity 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, instance, network_interface]) + if request is 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.GetEffectiveFirewallsInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.GetEffectiveFirewallsInstanceRequest): + request = compute.GetEffectiveFirewallsInstanceRequest(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 instance is not None: + request.instance = instance + if network_interface is not None: + request.network_interface = network_interface + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_effective_firewalls] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + def get_guest_attributes( self, request: compute.GetGuestAttributesInstanceRequest = None, @@ -4564,6 +4773,11 @@ def update_network_interface( metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Operation: r"""Updates an instance's network interface. This method + can only update an interface's alias IP range and + attached network. See Modifying alias IP ranges for an + existing instance for instructions on changing alias IP + ranges. See Migrating a VM between networks for + instructions on migrating an interface. This method follows PATCH semantics. Args: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/transports/base.py index 5adbe7c79bcd..729435037a46 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class InstancesTransport(abc.ABC): """Abstract transport class for Instances.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -181,6 +160,9 @@ def _prep_wrapped_messages(self, client_info): self.attach_disk: gapic_v1.method.wrap_method( self.attach_disk, default_timeout=None, client_info=client_info, ), + self.bulk_insert: gapic_v1.method.wrap_method( + self.bulk_insert, default_timeout=None, client_info=client_info, + ), self.delete: gapic_v1.method.wrap_method( self.delete, default_timeout=None, client_info=client_info, ), @@ -195,6 +177,11 @@ def _prep_wrapped_messages(self, client_info): self.get: gapic_v1.method.wrap_method( self.get, default_timeout=None, client_info=client_info, ), + self.get_effective_firewalls: gapic_v1.method.wrap_method( + self.get_effective_firewalls, + default_timeout=None, + client_info=client_info, + ), self.get_guest_attributes: gapic_v1.method.wrap_method( self.get_guest_attributes, default_timeout=None, @@ -363,6 +350,15 @@ def attach_disk( ]: raise NotImplementedError() + @property + def bulk_insert( + self, + ) -> Callable[ + [compute.BulkInsertInstanceRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + @property def delete( self, @@ -399,6 +395,18 @@ def get( ]: raise NotImplementedError() + @property + def get_effective_firewalls( + self, + ) -> Callable[ + [compute.GetEffectiveFirewallsInstanceRequest], + Union[ + compute.InstancesGetEffectiveFirewallsResponse, + Awaitable[compute.InstancesGetEffectiveFirewallsResponse], + ], + ]: + raise NotImplementedError() + @property def get_guest_attributes( self, diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/transports/rest.py index aea6942857a2..e4adb2932eaa 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -174,10 +175,14 @@ def add_access_config( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -261,10 +266,14 @@ def add_resource_policies( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -320,10 +329,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.InstanceAggregatedList.from_json( @@ -411,10 +424,102 @@ def attach_disk( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 + return compute.Operation.from_json(response.content, ignore_unknown_fields=True) + + def bulk_insert( + self, + request: compute.BulkInsertInstanceRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the bulk insert method over HTTP. + + Args: + request (~.compute.BulkInsertInstanceRequest): + The request object. A request message for + Instances.BulkInsert. See the method + description for details. + + 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 ``zonalOperations`` + resource. + + For more information, read Global, Regional, and Zonal + Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + + # Jsonify the request body + body = compute.BulkInsertInstanceResource.to_json( + request.bulk_insert_instance_resource_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/projects/{project}/zones/{zone}/instances/bulkInsert".format( + host=self._host, project=request.project, zone=request.zone, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.BulkInsertInstanceRequest.request_id in request: + query_params["requestId"] = request.request_id + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -491,10 +596,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -575,10 +684,14 @@ def delete_access_config( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -657,10 +770,14 @@ def detach_disk( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -712,14 +829,76 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Instance.from_json(response.content, ignore_unknown_fields=True) + def get_effective_firewalls( + self, + request: compute.GetEffectiveFirewallsInstanceRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.InstancesGetEffectiveFirewallsResponse: + r"""Call the get effective firewalls method over HTTP. + + Args: + request (~.compute.GetEffectiveFirewallsInstanceRequest): + The request object. A request message for + Instances.GetEffectiveFirewalls. See the + method description for details. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.InstancesGetEffectiveFirewallsResponse: + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/projects/{project}/zones/{zone}/instances/{instance}/getEffectiveFirewalls".format( + host=self._host, + project=request.project, + zone=request.zone, + instance=request.instance, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if request.network_interface: + query_params["networkInterface"] = request.network_interface + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 + return compute.InstancesGetEffectiveFirewallsResponse.from_json( + response.content, ignore_unknown_fields=True + ) + def get_guest_attributes( self, request: compute.GetGuestAttributesInstanceRequest, @@ -766,10 +945,14 @@ def get_guest_attributes( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.GuestAttributes.from_json( @@ -875,10 +1058,14 @@ def get_iam_policy( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Policy.from_json(response.content, ignore_unknown_fields=True) @@ -925,10 +1112,14 @@ def get_screenshot( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Screenshot.from_json( @@ -981,10 +1172,14 @@ def get_serial_port_output( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.SerialPortOutput.from_json( @@ -1034,10 +1229,14 @@ def get_shielded_instance_identity( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.ShieldedInstanceIdentity.from_json( @@ -1122,10 +1321,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -1178,10 +1381,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.InstanceList.from_json( @@ -1242,10 +1449,14 @@ def list_referrers( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.InstanceListReferrers.from_json( @@ -1331,10 +1542,14 @@ def remove_resource_policies( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -1411,10 +1626,14 @@ def reset( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -1493,10 +1712,14 @@ def set_deletion_protection( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -1577,10 +1800,14 @@ def set_disk_auto_delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -1684,10 +1911,14 @@ def set_iam_policy( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Policy.from_json(response.content, ignore_unknown_fields=True) @@ -1771,10 +2002,14 @@ def set_labels( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -1858,10 +2093,14 @@ def set_machine_resources( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -1945,10 +2184,14 @@ def set_machine_type( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -2032,10 +2275,14 @@ def set_metadata( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -2119,10 +2366,14 @@ def set_min_cpu_platform( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -2206,10 +2457,14 @@ def set_scheduling( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -2293,10 +2548,14 @@ def set_service_account( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -2384,10 +2643,14 @@ def set_shielded_instance_integrity_policy( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -2471,10 +2734,14 @@ def set_tags( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -2550,10 +2817,14 @@ def simulate_maintenance_event( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -2630,10 +2901,14 @@ def start( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -2717,10 +2992,14 @@ def start_with_encryption_key( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -2796,10 +3075,14 @@ def stop( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -2853,10 +3136,14 @@ def test_iam_permissions( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.TestPermissionsResponse.from_json( @@ -2948,10 +3235,14 @@ def update( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.put(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.put(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -3037,10 +3328,14 @@ def update_access_config( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -3124,10 +3419,14 @@ def update_display_device( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -3213,10 +3512,14 @@ def update_network_interface( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -3301,10 +3604,14 @@ def update_shielded_instance_config( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) 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 f2ad8da5edc5..d52aab4cd7c3 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 @@ -52,7 +52,7 @@ class InterconnectAttachmentsClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[InterconnectAttachmentsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -75,7 +75,8 @@ class InterconnectAttachmentsClient(metaclass=InterconnectAttachmentsClientMeta) @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -109,7 +110,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -126,7 +128,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -145,16 +147,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> InterconnectAttachmentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - InterconnectAttachmentsTransport: The transport used by the client instance. + InterconnectAttachmentsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -167,7 +170,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -178,7 +181,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -189,7 +192,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -200,7 +203,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -219,7 +222,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the interconnect attachments client. + """Instantiates the interconnect attachments client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -274,9 +277,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -288,12 +292,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -308,8 +314,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_attachments/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_attachments/transports/base.py index 121c8a8d48ed..23091650bda0 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_attachments/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_attachments/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class InterconnectAttachmentsTransport(abc.ABC): """Abstract transport class for InterconnectAttachments.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_attachments/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_attachments/transports/rest.py index b8f2f8396897..bed80622bfce 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_attachments/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_attachments/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -150,10 +151,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.InterconnectAttachmentAggregatedList.from_json( @@ -232,10 +237,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -289,10 +298,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.InterconnectAttachment.from_json( @@ -377,10 +390,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -437,10 +454,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.InterconnectAttachmentList.from_json( @@ -526,10 +547,14 @@ def patch( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_locations/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_locations/client.py index 72e6b7507055..8a22f3ca38dd 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_locations/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_locations/client.py @@ -52,7 +52,7 @@ class InterconnectLocationsClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[InterconnectLocationsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -75,7 +75,8 @@ class InterconnectLocationsClient(metaclass=InterconnectLocationsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -109,7 +110,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -126,7 +128,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -145,16 +147,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> InterconnectLocationsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - InterconnectLocationsTransport: The transport used by the client instance. + InterconnectLocationsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -167,7 +170,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -178,7 +181,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -189,7 +192,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -200,7 +203,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -219,7 +222,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the interconnect locations client. + """Instantiates the interconnect locations client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -274,9 +277,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -288,12 +292,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -308,8 +314,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_locations/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_locations/transports/base.py index f380ce641d20..1fe9646b00f4 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_locations/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_locations/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class InterconnectLocationsTransport(abc.ABC): """Abstract transport class for InterconnectLocations.""" @@ -120,10 +121,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -144,27 +144,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_locations/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_locations/transports/rest.py index 0d1c0d7a07a1..c85766d964f6 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_locations/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_locations/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -141,10 +142,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.InterconnectLocation.from_json( @@ -203,10 +208,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 return compute.InterconnectLocationList.from_json( diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnects/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnects/client.py index 53106779b22f..990e41185051 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnects/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnects/client.py @@ -48,7 +48,7 @@ class InterconnectsClientMeta(type): _transport_registry["rest"] = InterconnectsRestTransport def get_transport_class(cls, label: str = None,) -> Type[InterconnectsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class InterconnectsClient(metaclass=InterconnectsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> InterconnectsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - InterconnectsTransport: The transport used by the client instance. + InterconnectsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the interconnects client. + """Instantiates the interconnects client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnects/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnects/transports/base.py index 8dc2b526280b..5592165ad843 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnects/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnects/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class InterconnectsTransport(abc.ABC): """Abstract transport class for Interconnects.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnects/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnects/transports/rest.py index c210d4970be8..56a3cd00c561 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnects/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnects/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -162,10 +163,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -216,10 +221,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Interconnect.from_json( @@ -267,10 +276,14 @@ def get_diagnostics( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.InterconnectsGetDiagnosticsResponse.from_json( @@ -353,10 +366,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -412,10 +429,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.InterconnectList.from_json( @@ -498,10 +519,14 @@ def patch( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/client.py index e124cef56a42..19c0bf585f7a 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/client.py @@ -47,7 +47,7 @@ class LicenseCodesClientMeta(type): _transport_registry["rest"] = LicenseCodesRestTransport def get_transport_class(cls, label: str = None,) -> Type[LicenseCodesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -70,7 +70,8 @@ class LicenseCodesClient(metaclass=LicenseCodesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -104,7 +105,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -121,7 +123,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -140,16 +142,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> LicenseCodesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - LicenseCodesTransport: The transport used by the client instance. + LicenseCodesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -162,7 +165,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -173,7 +176,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -184,7 +187,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -195,7 +198,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -214,7 +217,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the license codes client. + """Instantiates the license codes client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -269,9 +272,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -283,12 +287,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -303,8 +309,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/transports/base.py index f9134fe1caa8..02063d77770f 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class LicenseCodesTransport(abc.ABC): """Abstract transport class for LicenseCodes.""" @@ -120,10 +121,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -144,27 +144,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/transports/rest.py index a5654f343fe4..3e5e11f7c3df 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -139,10 +140,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.LicenseCode.from_json( @@ -195,10 +200,14 @@ def test_iam_permissions( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.TestPermissionsResponse.from_json( diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/licenses/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/licenses/client.py index 6a407fac9cb8..d6edd088756d 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/licenses/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/licenses/client.py @@ -48,7 +48,7 @@ class LicensesClientMeta(type): _transport_registry["rest"] = LicensesRestTransport def get_transport_class(cls, label: str = None,) -> Type[LicensesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class LicensesClient(metaclass=LicensesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> LicensesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - LicensesTransport: The transport used by the client instance. + LicensesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the licenses client. + """Instantiates the licenses client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/licenses/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/licenses/transports/base.py index 1c94a953e7d7..d3ff14836b2d 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/licenses/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/licenses/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class LicensesTransport(abc.ABC): """Abstract transport class for Licenses.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/licenses/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/licenses/transports/rest.py index e61526e69e73..2077ae269635 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/licenses/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/licenses/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -164,10 +165,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -219,10 +224,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.License.from_json(response.content, ignore_unknown_fields=True) @@ -323,10 +332,14 @@ def get_iam_policy( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Policy.from_json(response.content, ignore_unknown_fields=True) @@ -407,10 +420,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -463,10 +480,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.LicensesListResponse.from_json( @@ -569,10 +590,14 @@ def set_iam_policy( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Policy.from_json(response.content, ignore_unknown_fields=True) @@ -623,10 +648,14 @@ def test_iam_permissions( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.TestPermissionsResponse.from_json( 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 45f00878748c..5084fea19673 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 @@ -48,7 +48,7 @@ class MachineTypesClientMeta(type): _transport_registry["rest"] = MachineTypesRestTransport def get_transport_class(cls, label: str = None,) -> Type[MachineTypesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class MachineTypesClient(metaclass=MachineTypesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> MachineTypesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - MachineTypesTransport: The transport used by the client instance. + MachineTypesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the machine types client. + """Instantiates the machine types client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/machine_types/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/machine_types/transports/base.py index c59db0130db9..587a0521ff41 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/machine_types/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/machine_types/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class MachineTypesTransport(abc.ABC): """Abstract transport class for MachineTypes.""" @@ -120,10 +121,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -144,27 +144,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/machine_types/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/machine_types/transports/rest.py index 1bff48975167..7ccc4c533295 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/machine_types/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/machine_types/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -144,10 +145,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.MachineTypeAggregatedList.from_json( @@ -202,10 +207,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.MachineType.from_json( @@ -261,10 +270,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 return compute.MachineTypeList.from_json( 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 316988e95f58..f17226fd6378 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 @@ -52,7 +52,7 @@ class NetworkEndpointGroupsClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[NetworkEndpointGroupsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -75,7 +75,8 @@ class NetworkEndpointGroupsClient(metaclass=NetworkEndpointGroupsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -109,7 +110,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -126,7 +128,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -145,16 +147,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> NetworkEndpointGroupsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - NetworkEndpointGroupsTransport: The transport used by the client instance. + NetworkEndpointGroupsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -167,7 +170,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -178,7 +181,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -189,7 +192,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -200,7 +203,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -219,7 +222,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the network endpoint groups client. + """Instantiates the network endpoint groups client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -274,9 +277,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -288,12 +292,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -308,8 +314,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/network_endpoint_groups/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/network_endpoint_groups/transports/base.py index 8d181e9b7b96..4072d4189ed1 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/network_endpoint_groups/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/network_endpoint_groups/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class NetworkEndpointGroupsTransport(abc.ABC): """Abstract transport class for NetworkEndpointGroups.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/network_endpoint_groups/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/network_endpoint_groups/transports/rest.py index 93999ea36d1f..379877dff657 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/network_endpoint_groups/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/network_endpoint_groups/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -150,10 +151,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.NetworkEndpointGroupAggregatedList.from_json( @@ -242,10 +247,14 @@ def attach_network_endpoints( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -322,10 +331,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -412,10 +425,14 @@ def detach_network_endpoints( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -475,10 +492,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.NetworkEndpointGroup.from_json( @@ -561,10 +582,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -618,10 +643,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.NetworkEndpointGroupList.from_json( @@ -696,10 +725,14 @@ def list_network_endpoints( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.NetworkEndpointGroupsListNetworkEndpoints.from_json( @@ -755,10 +788,14 @@ def test_iam_permissions( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.TestPermissionsResponse.from_json( diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/client.py index 868a50b2ac58..7196c366b9af 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/client.py @@ -48,7 +48,7 @@ class NetworksClientMeta(type): _transport_registry["rest"] = NetworksRestTransport def get_transport_class(cls, label: str = None,) -> Type[NetworksTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class NetworksClient(metaclass=NetworksClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> NetworksTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - NetworksTransport: The transport used by the client instance. + NetworksTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the networks client. + """Instantiates the networks client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -599,6 +605,76 @@ def get( # Done; return the response. return response + def get_effective_firewalls( + self, + request: compute.GetEffectiveFirewallsNetworkRequest = None, + *, + project: str = None, + network: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.NetworksGetEffectiveFirewallsResponse: + r"""Returns the effective firewalls on a given network. + + Args: + request (google.cloud.compute_v1.types.GetEffectiveFirewallsNetworkRequest): + The request object. A request message for + Networks.GetEffectiveFirewalls. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network (str): + Name of the network for this request. + This corresponds to the ``network`` 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.NetworksGetEffectiveFirewallsResponse: + + """ + # Create or coerce a protobuf request object. + # Sanity 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, network]) + if request is 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.GetEffectiveFirewallsNetworkRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.GetEffectiveFirewallsNetworkRequest): + request = compute.GetEffectiveFirewallsNetworkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if network is not None: + request.network = network + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_effective_firewalls] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + def insert( self, request: compute.InsertNetworkRequest = None, diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/transports/base.py index 410f7f8fbc87..b2c5fae2991c 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class NetworksTransport(abc.ABC): """Abstract transport class for Networks.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -176,6 +155,11 @@ def _prep_wrapped_messages(self, client_info): self.get: gapic_v1.method.wrap_method( self.get, default_timeout=None, client_info=client_info, ), + self.get_effective_firewalls: gapic_v1.method.wrap_method( + self.get_effective_firewalls, + default_timeout=None, + client_info=client_info, + ), self.insert: gapic_v1.method.wrap_method( self.insert, default_timeout=None, client_info=client_info, ), @@ -227,6 +211,18 @@ def get( ]: raise NotImplementedError() + @property + def get_effective_firewalls( + self, + ) -> Callable[ + [compute.GetEffectiveFirewallsNetworkRequest], + Union[ + compute.NetworksGetEffectiveFirewallsResponse, + Awaitable[compute.NetworksGetEffectiveFirewallsResponse], + ], + ]: + raise NotImplementedError() + @property def insert( self, diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/transports/rest.py index 44479696a0e0..49cf5043c917 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -169,10 +170,14 @@ def add_peering( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -246,10 +251,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -298,14 +307,71 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Network.from_json(response.content, ignore_unknown_fields=True) + def get_effective_firewalls( + self, + request: compute.GetEffectiveFirewallsNetworkRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.NetworksGetEffectiveFirewallsResponse: + r"""Call the get effective firewalls method over HTTP. + + Args: + request (~.compute.GetEffectiveFirewallsNetworkRequest): + The request object. A request message for + Networks.GetEffectiveFirewalls. See the + method description for details. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.NetworksGetEffectiveFirewallsResponse: + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/projects/{project}/global/networks/{network}/getEffectiveFirewalls".format( + host=self._host, project=request.project, network=request.network, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 + return compute.NetworksGetEffectiveFirewallsResponse.from_json( + response.content, ignore_unknown_fields=True + ) + def insert( self, request: compute.InsertNetworkRequest, @@ -382,10 +448,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -438,10 +508,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.NetworkList.from_json( @@ -503,10 +577,14 @@ def list_peering_routes( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.ExchangedPeeringRoutesList.from_json( @@ -588,10 +666,14 @@ def patch( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -672,10 +754,14 @@ def remove_peering( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -749,10 +835,14 @@ def switch_to_custom_mode( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -833,10 +923,14 @@ def update_peering( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) 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 7887af8d8de0..6e2e173662b3 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 @@ -48,7 +48,7 @@ class NodeGroupsClientMeta(type): _transport_registry["rest"] = NodeGroupsRestTransport def get_transport_class(cls, label: str = None,) -> Type[NodeGroupsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class NodeGroupsClient(metaclass=NodeGroupsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> NodeGroupsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - NodeGroupsTransport: The transport used by the client instance. + NodeGroupsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the node groups client. + """Instantiates the node groups client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/node_groups/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/node_groups/transports/base.py index 7b337846794c..8137c560c9c3 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/node_groups/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/node_groups/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class NodeGroupsTransport(abc.ABC): """Abstract transport class for NodeGroups.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/node_groups/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/node_groups/transports/rest.py index 9a865a09bc49..f8d95986826e 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/node_groups/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/node_groups/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -172,10 +173,14 @@ def add_nodes( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -231,10 +236,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.NodeGroupAggregatedList.from_json( @@ -313,10 +322,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -400,10 +413,14 @@ def delete_nodes( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -458,10 +475,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.NodeGroup.from_json(response.content, ignore_unknown_fields=True) @@ -565,10 +586,14 @@ def get_iam_policy( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Policy.from_json(response.content, ignore_unknown_fields=True) @@ -651,10 +676,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -708,10 +737,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.NodeGroupList.from_json( @@ -770,10 +803,14 @@ def list_nodes( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.NodeGroupsListNodes.from_json( @@ -859,10 +896,14 @@ def patch( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -966,10 +1007,14 @@ def set_iam_policy( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Policy.from_json(response.content, ignore_unknown_fields=True) @@ -1053,10 +1098,14 @@ def set_node_template( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -1110,10 +1159,14 @@ def test_iam_permissions( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.TestPermissionsResponse.from_json( 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 3fb0c8ae525f..1416b6c98246 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 @@ -48,7 +48,7 @@ class NodeTemplatesClientMeta(type): _transport_registry["rest"] = NodeTemplatesRestTransport def get_transport_class(cls, label: str = None,) -> Type[NodeTemplatesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class NodeTemplatesClient(metaclass=NodeTemplatesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> NodeTemplatesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - NodeTemplatesTransport: The transport used by the client instance. + NodeTemplatesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the node templates client. + """Instantiates the node templates client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/node_templates/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/node_templates/transports/base.py index 151433b6ae02..6d1b2d36a3ea 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/node_templates/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/node_templates/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class NodeTemplatesTransport(abc.ABC): """Abstract transport class for NodeTemplates.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/node_templates/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/node_templates/transports/rest.py index 157e41d94b5b..ebc7d23d11fa 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/node_templates/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/node_templates/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -144,10 +145,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.NodeTemplateAggregatedList.from_json( @@ -226,10 +231,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -282,10 +291,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.NodeTemplate.from_json( @@ -391,10 +404,14 @@ def get_iam_policy( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Policy.from_json(response.content, ignore_unknown_fields=True) @@ -475,10 +492,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -532,10 +553,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.NodeTemplateList.from_json( @@ -641,10 +666,14 @@ def set_iam_policy( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Policy.from_json(response.content, ignore_unknown_fields=True) @@ -698,10 +727,14 @@ def test_iam_permissions( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.TestPermissionsResponse.from_json( 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 8e15b2a234b5..47f07a1d323f 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 @@ -48,7 +48,7 @@ class NodeTypesClientMeta(type): _transport_registry["rest"] = NodeTypesRestTransport def get_transport_class(cls, label: str = None,) -> Type[NodeTypesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class NodeTypesClient(metaclass=NodeTypesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> NodeTypesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - NodeTypesTransport: The transport used by the client instance. + NodeTypesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the node types client. + """Instantiates the node types client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/node_types/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/node_types/transports/base.py index e0e78ae1c8cb..dc7874707763 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/node_types/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/node_types/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class NodeTypesTransport(abc.ABC): """Abstract transport class for NodeTypes.""" @@ -120,10 +121,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -144,27 +144,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/node_types/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/node_types/transports/rest.py index 52b73317652b..021b92189cb0 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/node_types/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/node_types/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -144,10 +145,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.NodeTypeAggregatedList.from_json( @@ -204,10 +209,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.NodeType.from_json(response.content, ignore_unknown_fields=True) @@ -260,10 +269,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 return compute.NodeTypeList.from_json( 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 7fd15879e2e3..97756f8f03c9 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 @@ -50,7 +50,7 @@ class PacketMirroringsClientMeta(type): _transport_registry["rest"] = PacketMirroringsRestTransport def get_transport_class(cls, label: str = None,) -> Type[PacketMirroringsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -73,7 +73,8 @@ class PacketMirroringsClient(metaclass=PacketMirroringsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -107,7 +108,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -124,7 +126,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -143,16 +145,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> PacketMirroringsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - PacketMirroringsTransport: The transport used by the client instance. + PacketMirroringsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -165,7 +168,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -176,7 +179,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -187,7 +190,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -198,7 +201,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -217,7 +220,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the packet mirrorings client. + """Instantiates the packet mirrorings client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -272,9 +275,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -286,12 +290,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -306,8 +312,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/packet_mirrorings/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/packet_mirrorings/transports/base.py index 09440be1d6ad..db05b3792a00 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/packet_mirrorings/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/packet_mirrorings/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class PacketMirroringsTransport(abc.ABC): """Abstract transport class for PacketMirrorings.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/packet_mirrorings/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/packet_mirrorings/transports/rest.py index 67e5eaf88c21..a16718654ca7 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/packet_mirrorings/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/packet_mirrorings/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -147,10 +148,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.PacketMirroringAggregatedList.from_json( @@ -229,10 +234,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -288,10 +297,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.PacketMirroring.from_json( @@ -374,10 +387,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -433,10 +450,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.PacketMirroringList.from_json( @@ -522,10 +543,14 @@ def patch( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -579,10 +604,14 @@ def test_iam_permissions( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.TestPermissionsResponse.from_json( 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 96af8e934752..2082c2ab1456 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 @@ -48,7 +48,7 @@ class ProjectsClientMeta(type): _transport_registry["rest"] = ProjectsRestTransport def get_transport_class(cls, label: str = None,) -> Type[ProjectsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class ProjectsClient(metaclass=ProjectsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ProjectsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - ProjectsTransport: The transport used by the client instance. + ProjectsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the projects client. + """Instantiates the projects client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: 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 e97556da040f..8b8d63f3dd51 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 @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class ProjectsTransport(abc.ABC): """Abstract transport class for Projects.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { 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 7c793c9da7b3..b47df2c13512 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 @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -162,10 +163,14 @@ def disable_xpn_host( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -246,10 +251,14 @@ def disable_xpn_resource( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -323,10 +332,14 @@ def enable_xpn_host( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -407,10 +420,14 @@ def enable_xpn_resource( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -459,10 +476,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Project.from_json(response.content, ignore_unknown_fields=True) @@ -512,10 +533,14 @@ def get_xpn_host( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Project.from_json(response.content, ignore_unknown_fields=True) @@ -569,10 +594,14 @@ def get_xpn_resources( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.ProjectsGetXpnResources.from_json( @@ -635,10 +664,14 @@ def list_xpn_hosts( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.XpnHostList.from_json( @@ -721,10 +754,14 @@ def move_disk( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -805,10 +842,14 @@ def move_instance( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -890,10 +931,14 @@ def set_common_instance_metadata( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -974,10 +1019,14 @@ def set_default_network_tier( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -1058,10 +1107,14 @@ def set_usage_export_bucket( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/public_advertised_prefixes/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/public_advertised_prefixes/__init__.py new file mode 100644 index 000000000000..cc10b372ce19 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/public_advertised_prefixes/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 PublicAdvertisedPrefixesClient + +__all__ = ("PublicAdvertisedPrefixesClient",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/public_advertised_prefixes/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/public_advertised_prefixes/client.py new file mode 100644 index 000000000000..d06116c46542 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/public_advertised_prefixes/client.py @@ -0,0 +1,800 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.compute_v1.services.public_advertised_prefixes import pagers +from google.cloud.compute_v1.types import compute +from .transports.base import PublicAdvertisedPrefixesTransport, DEFAULT_CLIENT_INFO +from .transports.rest import PublicAdvertisedPrefixesRestTransport + + +class PublicAdvertisedPrefixesClientMeta(type): + """Metaclass for the PublicAdvertisedPrefixes 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[PublicAdvertisedPrefixesTransport]] + _transport_registry["rest"] = PublicAdvertisedPrefixesRestTransport + + def get_transport_class( + cls, label: str = None, + ) -> Type[PublicAdvertisedPrefixesTransport]: + """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 PublicAdvertisedPrefixesClient(metaclass=PublicAdvertisedPrefixesClientMeta): + """The PublicAdvertisedPrefixes 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") + + DEFAULT_ENDPOINT = "compute.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @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: + PublicAdvertisedPrefixesClient: 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: + PublicAdvertisedPrefixesClient: 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) -> PublicAdvertisedPrefixesTransport: + """Returns the transport used by the client instance. + + Returns: + PublicAdvertisedPrefixesTransport: 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 {} + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, PublicAdvertisedPrefixesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the public advertised prefixes 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, PublicAdvertisedPrefixesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "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). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS 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. + 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. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, PublicAdvertisedPrefixesTransport): + # transport is a PublicAdvertisedPrefixesTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def delete( + self, + request: compute.DeletePublicAdvertisedPrefixeRequest = None, + *, + project: str = None, + public_advertised_prefix: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Deletes the specified PublicAdvertisedPrefix + + Args: + request (google.cloud.compute_v1.types.DeletePublicAdvertisedPrefixeRequest): + The request object. A request message for + PublicAdvertisedPrefixes.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. + public_advertised_prefix (str): + Name of the PublicAdvertisedPrefix + resource to delete. + + This corresponds to the ``public_advertised_prefix`` 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.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - [Global](/compute/docs/reference/rest/{$api_version}/globalOperations) + \* + [Regional](/compute/docs/reference/rest/{$api_version}/regionOperations) + \* + [Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations) + + 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 + zonalOperations resource. + + For more information, read Global, Regional, and + Zonal Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + # Create or coerce a protobuf request object. + # Sanity 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, public_advertised_prefix]) + if request is 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.DeletePublicAdvertisedPrefixeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.DeletePublicAdvertisedPrefixeRequest): + request = compute.DeletePublicAdvertisedPrefixeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if public_advertised_prefix is not None: + request.public_advertised_prefix = public_advertised_prefix + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get( + self, + request: compute.GetPublicAdvertisedPrefixeRequest = None, + *, + project: str = None, + public_advertised_prefix: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.PublicAdvertisedPrefix: + r"""Returns the specified PublicAdvertisedPrefix + resource. + + Args: + request (google.cloud.compute_v1.types.GetPublicAdvertisedPrefixeRequest): + The request object. A request message for + PublicAdvertisedPrefixes.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. + public_advertised_prefix (str): + Name of the PublicAdvertisedPrefix + resource to return. + + This corresponds to the ``public_advertised_prefix`` 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.PublicAdvertisedPrefix: + A public advertised prefix represents + an aggregated IP prefix or netblock + which customers bring to cloud. The IP + prefix is a single unit of route + advertisement and is announced globally + to the internet. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, public_advertised_prefix]) + if request is 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.GetPublicAdvertisedPrefixeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.GetPublicAdvertisedPrefixeRequest): + request = compute.GetPublicAdvertisedPrefixeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if public_advertised_prefix is not None: + request.public_advertised_prefix = public_advertised_prefix + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def insert( + self, + request: compute.InsertPublicAdvertisedPrefixeRequest = None, + *, + project: str = None, + public_advertised_prefix_resource: compute.PublicAdvertisedPrefix = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Creates a PublicAdvertisedPrefix in the specified + project using the parameters that are included in the + request. + + Args: + request (google.cloud.compute_v1.types.InsertPublicAdvertisedPrefixeRequest): + The request object. A request message for + PublicAdvertisedPrefixes.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. + public_advertised_prefix_resource (google.cloud.compute_v1.types.PublicAdvertisedPrefix): + The body resource for this request + This corresponds to the ``public_advertised_prefix_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.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - [Global](/compute/docs/reference/rest/{$api_version}/globalOperations) + \* + [Regional](/compute/docs/reference/rest/{$api_version}/regionOperations) + \* + [Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations) + + 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 + zonalOperations resource. + + For more information, read Global, Regional, and + Zonal Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + # Create or coerce a protobuf request object. + # Sanity 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, public_advertised_prefix_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.InsertPublicAdvertisedPrefixeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.InsertPublicAdvertisedPrefixeRequest): + request = compute.InsertPublicAdvertisedPrefixeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if public_advertised_prefix_resource is not None: + request.public_advertised_prefix_resource = ( + public_advertised_prefix_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list( + self, + request: compute.ListPublicAdvertisedPrefixesRequest = None, + *, + project: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPager: + r"""Lists the PublicAdvertisedPrefixes for a project. + + Args: + request (google.cloud.compute_v1.types.ListPublicAdvertisedPrefixesRequest): + The request object. A request message for + PublicAdvertisedPrefixes.List. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.compute_v1.services.public_advertised_prefixes.pagers.ListPager: + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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.ListPublicAdvertisedPrefixesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.ListPublicAdvertisedPrefixesRequest): + request = compute.ListPublicAdvertisedPrefixesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list] + + # 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 patch( + self, + request: compute.PatchPublicAdvertisedPrefixeRequest = None, + *, + project: str = None, + public_advertised_prefix: str = None, + public_advertised_prefix_resource: compute.PublicAdvertisedPrefix = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Patches the specified Router resource with the data + included in the request. This method supports PATCH + semantics and uses JSON merge patch format and + processing rules. + + Args: + request (google.cloud.compute_v1.types.PatchPublicAdvertisedPrefixeRequest): + The request object. A request message for + PublicAdvertisedPrefixes.Patch. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + public_advertised_prefix (str): + Name of the PublicAdvertisedPrefix + resource to patch. + + This corresponds to the ``public_advertised_prefix`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + public_advertised_prefix_resource (google.cloud.compute_v1.types.PublicAdvertisedPrefix): + The body resource for this request + This corresponds to the ``public_advertised_prefix_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.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - [Global](/compute/docs/reference/rest/{$api_version}/globalOperations) + \* + [Regional](/compute/docs/reference/rest/{$api_version}/regionOperations) + \* + [Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations) + + 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 + zonalOperations resource. + + For more information, read Global, Regional, and + Zonal Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + # Create or coerce a protobuf request object. + # Sanity 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, public_advertised_prefix, public_advertised_prefix_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.PatchPublicAdvertisedPrefixeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.PatchPublicAdvertisedPrefixeRequest): + request = compute.PatchPublicAdvertisedPrefixeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if public_advertised_prefix is not None: + request.public_advertised_prefix = public_advertised_prefix + if public_advertised_prefix_resource is not None: + request.public_advertised_prefix_resource = ( + public_advertised_prefix_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.patch] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("PublicAdvertisedPrefixesClient",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/public_advertised_prefixes/pagers.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/public_advertised_prefixes/pagers.py new file mode 100644 index 000000000000..65f3e02d8319 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/public_advertised_prefixes/pagers.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, + AsyncIterable, + Awaitable, + Callable, + Iterable, + Sequence, + Tuple, + Optional, +) + +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.PublicAdvertisedPrefixList` 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.PublicAdvertisedPrefixList` + 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.PublicAdvertisedPrefixList], + request: compute.ListPublicAdvertisedPrefixesRequest, + response: compute.PublicAdvertisedPrefixList, + *, + 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.ListPublicAdvertisedPrefixesRequest): + The initial request object. + response (google.cloud.compute_v1.types.PublicAdvertisedPrefixList): + 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.ListPublicAdvertisedPrefixesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[compute.PublicAdvertisedPrefixList]: + 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) -> Iterable[compute.PublicAdvertisedPrefix]: + 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/public_advertised_prefixes/transports/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/public_advertised_prefixes/transports/__init__.py new file mode 100644 index 000000000000..0d6543cf3809 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/public_advertised_prefixes/transports/__init__.py @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 PublicAdvertisedPrefixesTransport +from .rest import PublicAdvertisedPrefixesRestTransport + + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[PublicAdvertisedPrefixesTransport]] +_transport_registry["rest"] = PublicAdvertisedPrefixesRestTransport + +__all__ = ( + "PublicAdvertisedPrefixesTransport", + "PublicAdvertisedPrefixesRestTransport", +) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/public_advertised_prefixes/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/public_advertised_prefixes/transports/base.py new file mode 100644 index 000000000000..4bd53f7c332c --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/public_advertised_prefixes/transports/base.py @@ -0,0 +1,217 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 packaging.version +import pkg_resources +from requests import __version__ as requests_version + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.compute_v1.types import compute + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class PublicAdvertisedPrefixesTransport(abc.ABC): + """Abstract transport class for PublicAdvertisedPrefixes.""" + + 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: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + 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. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_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 + ) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + 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.insert: gapic_v1.method.wrap_method( + self.insert, default_timeout=None, client_info=client_info, + ), + self.list: gapic_v1.method.wrap_method( + self.list, default_timeout=None, client_info=client_info, + ), + self.patch: gapic_v1.method.wrap_method( + self.patch, default_timeout=None, client_info=client_info, + ), + } + + @property + def delete( + self, + ) -> Callable[ + [compute.DeletePublicAdvertisedPrefixeRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def get( + self, + ) -> Callable[ + [compute.GetPublicAdvertisedPrefixeRequest], + Union[ + compute.PublicAdvertisedPrefix, Awaitable[compute.PublicAdvertisedPrefix] + ], + ]: + raise NotImplementedError() + + @property + def insert( + self, + ) -> Callable[ + [compute.InsertPublicAdvertisedPrefixeRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def list( + self, + ) -> Callable[ + [compute.ListPublicAdvertisedPrefixesRequest], + Union[ + compute.PublicAdvertisedPrefixList, + Awaitable[compute.PublicAdvertisedPrefixList], + ], + ]: + raise NotImplementedError() + + @property + def patch( + self, + ) -> Callable[ + [compute.PatchPublicAdvertisedPrefixeRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + +__all__ = ("PublicAdvertisedPrefixesTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/public_advertised_prefixes/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/public_advertised_prefixes/transports/rest.py new file mode 100644 index 000000000000..f08dbd5eb3d8 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/public_advertised_prefixes/transports/rest.py @@ -0,0 +1,486 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # 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.auth.transport.requests import AuthorizedSession + +from google.cloud.compute_v1.types import compute + +from .base import PublicAdvertisedPrefixesTransport, DEFAULT_CLIENT_INFO + + +class PublicAdvertisedPrefixesRestTransport(PublicAdvertisedPrefixesTransport): + """REST backend transport for PublicAdvertisedPrefixes. + + The PublicAdvertisedPrefixes API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "compute.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + 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're developing + your own client library. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, credentials=credentials, client_info=client_info, + ) + 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._prep_wrapped_messages(client_info) + + def delete( + self, + request: compute.DeletePublicAdvertisedPrefixeRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the delete method over HTTP. + + Args: + request (~.compute.DeletePublicAdvertisedPrefixeRequest): + The request object. A request message for + PublicAdvertisedPrefixes.Delete. See the + method description for details. + + 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 ``zonalOperations`` + resource. + + For more information, read Global, Regional, and Zonal + Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/projects/{project}/global/publicAdvertisedPrefixes/{public_advertised_prefix}".format( + host=self._host, + project=request.project, + public_advertised_prefix=request.public_advertised_prefix, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.DeletePublicAdvertisedPrefixeRequest.request_id in request: + query_params["requestId"] = request.request_id + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) + + # 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 + return compute.Operation.from_json(response.content, ignore_unknown_fields=True) + + def get( + self, + request: compute.GetPublicAdvertisedPrefixeRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.PublicAdvertisedPrefix: + r"""Call the get method over HTTP. + + Args: + request (~.compute.GetPublicAdvertisedPrefixeRequest): + The request object. A request message for + PublicAdvertisedPrefixes.Get. See the + method description for details. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.PublicAdvertisedPrefix: + A public advertised prefix represents + an aggregated IP prefix or netblock + which customers bring to cloud. The IP + prefix is a single unit of route + advertisement and is announced globally + to the internet. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/projects/{project}/global/publicAdvertisedPrefixes/{public_advertised_prefix}".format( + host=self._host, + project=request.project, + public_advertised_prefix=request.public_advertised_prefix, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 + return compute.PublicAdvertisedPrefix.from_json( + response.content, ignore_unknown_fields=True + ) + + def insert( + self, + request: compute.InsertPublicAdvertisedPrefixeRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the insert method over HTTP. + + Args: + request (~.compute.InsertPublicAdvertisedPrefixeRequest): + The request object. A request message for + PublicAdvertisedPrefixes.Insert. See the + method description for details. + + 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 ``zonalOperations`` + resource. + + For more information, read Global, Regional, and Zonal + Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + + # Jsonify the request body + body = compute.PublicAdvertisedPrefix.to_json( + request.public_advertised_prefix_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/projects/{project}/global/publicAdvertisedPrefixes".format( + host=self._host, project=request.project, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.InsertPublicAdvertisedPrefixeRequest.request_id in request: + query_params["requestId"] = request.request_id + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 + return compute.Operation.from_json(response.content, ignore_unknown_fields=True) + + def list( + self, + request: compute.ListPublicAdvertisedPrefixesRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.PublicAdvertisedPrefixList: + r"""Call the list method over HTTP. + + Args: + request (~.compute.ListPublicAdvertisedPrefixesRequest): + The request object. A request message for + PublicAdvertisedPrefixes.List. See the + method description for details. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.PublicAdvertisedPrefixList: + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/projects/{project}/global/publicAdvertisedPrefixes".format( + host=self._host, project=request.project, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.ListPublicAdvertisedPrefixesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListPublicAdvertisedPrefixesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListPublicAdvertisedPrefixesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListPublicAdvertisedPrefixesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if ( + compute.ListPublicAdvertisedPrefixesRequest.return_partial_success + in request + ): + query_params["returnPartialSuccess"] = request.return_partial_success + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 + return compute.PublicAdvertisedPrefixList.from_json( + response.content, ignore_unknown_fields=True + ) + + def patch( + self, + request: compute.PatchPublicAdvertisedPrefixeRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the patch method over HTTP. + + Args: + request (~.compute.PatchPublicAdvertisedPrefixeRequest): + The request object. A request message for + PublicAdvertisedPrefixes.Patch. See the + method description for details. + + 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 ``zonalOperations`` + resource. + + For more information, read Global, Regional, and Zonal + Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + + # Jsonify the request body + body = compute.PublicAdvertisedPrefix.to_json( + request.public_advertised_prefix_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/projects/{project}/global/publicAdvertisedPrefixes/{public_advertised_prefix}".format( + host=self._host, + project=request.project, + public_advertised_prefix=request.public_advertised_prefix, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.PatchPublicAdvertisedPrefixeRequest.request_id in request: + query_params["requestId"] = request.request_id + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, 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 + return compute.Operation.from_json(response.content, ignore_unknown_fields=True) + + +__all__ = ("PublicAdvertisedPrefixesRestTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/public_delegated_prefixes/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/public_delegated_prefixes/__init__.py new file mode 100644 index 000000000000..5474619af47e --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/public_delegated_prefixes/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 PublicDelegatedPrefixesClient + +__all__ = ("PublicDelegatedPrefixesClient",) 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 new file mode 100644 index 000000000000..683a538f7623 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/public_delegated_prefixes/client.py @@ -0,0 +1,921 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.compute_v1.services.public_delegated_prefixes import pagers +from google.cloud.compute_v1.types import compute +from .transports.base import PublicDelegatedPrefixesTransport, DEFAULT_CLIENT_INFO +from .transports.rest import PublicDelegatedPrefixesRestTransport + + +class PublicDelegatedPrefixesClientMeta(type): + """Metaclass for the PublicDelegatedPrefixes 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[PublicDelegatedPrefixesTransport]] + _transport_registry["rest"] = PublicDelegatedPrefixesRestTransport + + def get_transport_class( + cls, label: str = None, + ) -> Type[PublicDelegatedPrefixesTransport]: + """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 PublicDelegatedPrefixesClient(metaclass=PublicDelegatedPrefixesClientMeta): + """The PublicDelegatedPrefixes 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") + + DEFAULT_ENDPOINT = "compute.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @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: + PublicDelegatedPrefixesClient: 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: + PublicDelegatedPrefixesClient: 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) -> PublicDelegatedPrefixesTransport: + """Returns the transport used by the client instance. + + Returns: + PublicDelegatedPrefixesTransport: 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 {} + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, PublicDelegatedPrefixesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the public delegated prefixes 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, PublicDelegatedPrefixesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "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). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS 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. + 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. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, PublicDelegatedPrefixesTransport): + # transport is a PublicDelegatedPrefixesTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def aggregated_list( + self, + request: compute.AggregatedListPublicDelegatedPrefixesRequest = None, + *, + project: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.AggregatedListPager: + r"""Lists all PublicDelegatedPrefix resources owned by + the specific project across all scopes. + + Args: + request (google.cloud.compute_v1.types.AggregatedListPublicDelegatedPrefixesRequest): + The request object. A request message for + PublicDelegatedPrefixes.AggregatedList. See the method + description for details. + project (str): + Name of the project scoping this + request. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.compute_v1.services.public_delegated_prefixes.pagers.AggregatedListPager: + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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.AggregatedListPublicDelegatedPrefixesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, compute.AggregatedListPublicDelegatedPrefixesRequest + ): + request = compute.AggregatedListPublicDelegatedPrefixesRequest(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] + + # 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( + self, + request: compute.DeletePublicDelegatedPrefixeRequest = None, + *, + project: str = None, + region: str = None, + public_delegated_prefix: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Deletes the specified PublicDelegatedPrefix in the + given region. + + Args: + request (google.cloud.compute_v1.types.DeletePublicDelegatedPrefixeRequest): + The request object. A request message for + PublicDelegatedPrefixes.Delete. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (str): + Name of the region of this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + public_delegated_prefix (str): + Name of the PublicDelegatedPrefix + resource to delete. + + This corresponds to the ``public_delegated_prefix`` 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.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - [Global](/compute/docs/reference/rest/{$api_version}/globalOperations) + \* + [Regional](/compute/docs/reference/rest/{$api_version}/regionOperations) + \* + [Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations) + + 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 + zonalOperations resource. + + For more information, read Global, Regional, and + Zonal Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + # Create or coerce a protobuf request object. + # Sanity 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, public_delegated_prefix]) + if request is 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.DeletePublicDelegatedPrefixeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.DeletePublicDelegatedPrefixeRequest): + request = compute.DeletePublicDelegatedPrefixeRequest(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 public_delegated_prefix is not None: + request.public_delegated_prefix = public_delegated_prefix + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get( + self, + request: compute.GetPublicDelegatedPrefixeRequest = None, + *, + project: str = None, + region: str = None, + public_delegated_prefix: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.PublicDelegatedPrefix: + r"""Returns the specified PublicDelegatedPrefix resource + in the given region. + + Args: + request (google.cloud.compute_v1.types.GetPublicDelegatedPrefixeRequest): + The request object. A request message for + PublicDelegatedPrefixes.Get. See the method description + for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (str): + Name of the region of this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + public_delegated_prefix (str): + Name of the PublicDelegatedPrefix + resource to return. + + This corresponds to the ``public_delegated_prefix`` 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.PublicDelegatedPrefix: + A PublicDelegatedPrefix resource + represents an IP block within a + PublicAdvertisedPrefix that is + configured within a single cloud scope + (global or region). IPs in the block can + be allocated to resources within that + scope. Public delegated prefixes may be + further broken up into smaller IP blocks + in the same scope as the parent block. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, public_delegated_prefix]) + if request is 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.GetPublicDelegatedPrefixeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.GetPublicDelegatedPrefixeRequest): + request = compute.GetPublicDelegatedPrefixeRequest(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 public_delegated_prefix is not None: + request.public_delegated_prefix = public_delegated_prefix + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def insert( + self, + request: compute.InsertPublicDelegatedPrefixeRequest = None, + *, + project: str = None, + region: str = None, + public_delegated_prefix_resource: compute.PublicDelegatedPrefix = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Creates a PublicDelegatedPrefix in the specified + project in the given region using the parameters that + are included in the request. + + Args: + request (google.cloud.compute_v1.types.InsertPublicDelegatedPrefixeRequest): + The request object. A request message for + PublicDelegatedPrefixes.Insert. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (str): + Name of the region of this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + public_delegated_prefix_resource (google.cloud.compute_v1.types.PublicDelegatedPrefix): + The body resource for this request + This corresponds to the ``public_delegated_prefix_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.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - [Global](/compute/docs/reference/rest/{$api_version}/globalOperations) + \* + [Regional](/compute/docs/reference/rest/{$api_version}/regionOperations) + \* + [Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations) + + 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 + zonalOperations resource. + + For more information, read Global, Regional, and + Zonal Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + # Create or coerce a protobuf request object. + # Sanity 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, public_delegated_prefix_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.InsertPublicDelegatedPrefixeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.InsertPublicDelegatedPrefixeRequest): + request = compute.InsertPublicDelegatedPrefixeRequest(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 public_delegated_prefix_resource is not None: + request.public_delegated_prefix_resource = ( + public_delegated_prefix_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list( + self, + request: compute.ListPublicDelegatedPrefixesRequest = None, + *, + project: str = None, + region: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPager: + r"""Lists the PublicDelegatedPrefixes for a project in + the given region. + + Args: + request (google.cloud.compute_v1.types.ListPublicDelegatedPrefixesRequest): + The request object. A request message for + PublicDelegatedPrefixes.List. See the method description + for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (str): + Name of the region of this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.compute_v1.services.public_delegated_prefixes.pagers.ListPager: + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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.ListPublicDelegatedPrefixesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.ListPublicDelegatedPrefixesRequest): + request = compute.ListPublicDelegatedPrefixesRequest(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] + + # 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 patch( + self, + request: compute.PatchPublicDelegatedPrefixeRequest = None, + *, + project: str = None, + region: str = None, + public_delegated_prefix: str = None, + public_delegated_prefix_resource: compute.PublicDelegatedPrefix = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Patches the specified PublicDelegatedPrefix resource + with the data included in the request. This method + supports PATCH semantics and uses JSON merge patch + format and processing rules. + + Args: + request (google.cloud.compute_v1.types.PatchPublicDelegatedPrefixeRequest): + The request object. A request message for + PublicDelegatedPrefixes.Patch. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (str): + Name of the region for this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + public_delegated_prefix (str): + Name of the PublicDelegatedPrefix + resource to patch. + + This corresponds to the ``public_delegated_prefix`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + public_delegated_prefix_resource (google.cloud.compute_v1.types.PublicDelegatedPrefix): + The body resource for this request + This corresponds to the ``public_delegated_prefix_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.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - [Global](/compute/docs/reference/rest/{$api_version}/globalOperations) + \* + [Regional](/compute/docs/reference/rest/{$api_version}/regionOperations) + \* + [Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations) + + 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 + zonalOperations resource. + + For more information, read Global, Regional, and + Zonal Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + # Create or coerce a protobuf request object. + # Sanity 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, public_delegated_prefix, public_delegated_prefix_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.PatchPublicDelegatedPrefixeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.PatchPublicDelegatedPrefixeRequest): + request = compute.PatchPublicDelegatedPrefixeRequest(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 public_delegated_prefix is not None: + request.public_delegated_prefix = public_delegated_prefix + if public_delegated_prefix_resource is not None: + request.public_delegated_prefix_resource = ( + public_delegated_prefix_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.patch] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("PublicDelegatedPrefixesClient",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/public_delegated_prefixes/pagers.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/public_delegated_prefixes/pagers.py new file mode 100644 index 000000000000..c84a6c416bc2 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/public_delegated_prefixes/pagers.py @@ -0,0 +1,156 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, + AsyncIterable, + Awaitable, + Callable, + Iterable, + Sequence, + Tuple, + Optional, +) + +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.PublicDelegatedPrefixAggregatedList` 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.PublicDelegatedPrefixAggregatedList` + 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.PublicDelegatedPrefixAggregatedList], + request: compute.AggregatedListPublicDelegatedPrefixesRequest, + response: compute.PublicDelegatedPrefixAggregatedList, + *, + 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.AggregatedListPublicDelegatedPrefixesRequest): + The initial request object. + response (google.cloud.compute_v1.types.PublicDelegatedPrefixAggregatedList): + 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.AggregatedListPublicDelegatedPrefixesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[compute.PublicDelegatedPrefixAggregatedList]: + 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, + ) -> Iterable[Tuple[str, compute.PublicDelegatedPrefixesScopedList]]: + for page in self.pages: + yield from page.items.items() + + def get(self, key: str) -> Optional[compute.PublicDelegatedPrefixesScopedList]: + 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.PublicDelegatedPrefixList` 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.PublicDelegatedPrefixList` + 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.PublicDelegatedPrefixList], + request: compute.ListPublicDelegatedPrefixesRequest, + response: compute.PublicDelegatedPrefixList, + *, + 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.ListPublicDelegatedPrefixesRequest): + The initial request object. + response (google.cloud.compute_v1.types.PublicDelegatedPrefixList): + 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.ListPublicDelegatedPrefixesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[compute.PublicDelegatedPrefixList]: + 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) -> Iterable[compute.PublicDelegatedPrefix]: + 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/public_delegated_prefixes/transports/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/public_delegated_prefixes/transports/__init__.py new file mode 100644 index 000000000000..ed6a2106d49a --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/public_delegated_prefixes/transports/__init__.py @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 PublicDelegatedPrefixesTransport +from .rest import PublicDelegatedPrefixesRestTransport + + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[PublicDelegatedPrefixesTransport]] +_transport_registry["rest"] = PublicDelegatedPrefixesRestTransport + +__all__ = ( + "PublicDelegatedPrefixesTransport", + "PublicDelegatedPrefixesRestTransport", +) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/public_delegated_prefixes/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/public_delegated_prefixes/transports/base.py new file mode 100644 index 000000000000..564ce9f44d03 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/public_delegated_prefixes/transports/base.py @@ -0,0 +1,230 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 packaging.version +import pkg_resources +from requests import __version__ as requests_version + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.compute_v1.types import compute + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class PublicDelegatedPrefixesTransport(abc.ABC): + """Abstract transport class for PublicDelegatedPrefixes.""" + + 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: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + 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. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_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 + ) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.aggregated_list: gapic_v1.method.wrap_method( + self.aggregated_list, default_timeout=None, client_info=client_info, + ), + self.delete: gapic_v1.method.wrap_method( + self.delete, default_timeout=None, client_info=client_info, + ), + self.get: gapic_v1.method.wrap_method( + self.get, default_timeout=None, client_info=client_info, + ), + self.insert: gapic_v1.method.wrap_method( + self.insert, default_timeout=None, client_info=client_info, + ), + self.list: gapic_v1.method.wrap_method( + self.list, default_timeout=None, client_info=client_info, + ), + self.patch: gapic_v1.method.wrap_method( + self.patch, default_timeout=None, client_info=client_info, + ), + } + + @property + def aggregated_list( + self, + ) -> Callable[ + [compute.AggregatedListPublicDelegatedPrefixesRequest], + Union[ + compute.PublicDelegatedPrefixAggregatedList, + Awaitable[compute.PublicDelegatedPrefixAggregatedList], + ], + ]: + raise NotImplementedError() + + @property + def delete( + self, + ) -> Callable[ + [compute.DeletePublicDelegatedPrefixeRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def get( + self, + ) -> Callable[ + [compute.GetPublicDelegatedPrefixeRequest], + Union[compute.PublicDelegatedPrefix, Awaitable[compute.PublicDelegatedPrefix]], + ]: + raise NotImplementedError() + + @property + def insert( + self, + ) -> Callable[ + [compute.InsertPublicDelegatedPrefixeRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def list( + self, + ) -> Callable[ + [compute.ListPublicDelegatedPrefixesRequest], + Union[ + compute.PublicDelegatedPrefixList, + Awaitable[compute.PublicDelegatedPrefixList], + ], + ]: + raise NotImplementedError() + + @property + def patch( + self, + ) -> Callable[ + [compute.PatchPublicDelegatedPrefixeRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + +__all__ = ("PublicDelegatedPrefixesTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/public_delegated_prefixes/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/public_delegated_prefixes/transports/rest.py new file mode 100644 index 000000000000..b4f3b5d043cb --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/public_delegated_prefixes/transports/rest.py @@ -0,0 +1,560 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # 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.auth.transport.requests import AuthorizedSession + +from google.cloud.compute_v1.types import compute + +from .base import PublicDelegatedPrefixesTransport, DEFAULT_CLIENT_INFO + + +class PublicDelegatedPrefixesRestTransport(PublicDelegatedPrefixesTransport): + """REST backend transport for PublicDelegatedPrefixes. + + The PublicDelegatedPrefixes API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "compute.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + 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're developing + your own client library. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, credentials=credentials, client_info=client_info, + ) + 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._prep_wrapped_messages(client_info) + + def aggregated_list( + self, + request: compute.AggregatedListPublicDelegatedPrefixesRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.PublicDelegatedPrefixAggregatedList: + r"""Call the aggregated list method over HTTP. + + Args: + request (~.compute.AggregatedListPublicDelegatedPrefixesRequest): + The request object. A request message for + PublicDelegatedPrefixes.AggregatedList. + See the method description for details. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.PublicDelegatedPrefixAggregatedList: + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/projects/{project}/aggregated/publicDelegatedPrefixes".format( + host=self._host, project=request.project, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.AggregatedListPublicDelegatedPrefixesRequest.filter in request: + query_params["filter"] = request.filter + if ( + compute.AggregatedListPublicDelegatedPrefixesRequest.include_all_scopes + in request + ): + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListPublicDelegatedPrefixesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListPublicDelegatedPrefixesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListPublicDelegatedPrefixesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if ( + compute.AggregatedListPublicDelegatedPrefixesRequest.return_partial_success + in request + ): + query_params["returnPartialSuccess"] = request.return_partial_success + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 + return compute.PublicDelegatedPrefixAggregatedList.from_json( + response.content, ignore_unknown_fields=True + ) + + def delete( + self, + request: compute.DeletePublicDelegatedPrefixeRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the delete method over HTTP. + + Args: + request (~.compute.DeletePublicDelegatedPrefixeRequest): + The request object. A request message for + PublicDelegatedPrefixes.Delete. See the + method description for details. + + 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 ``zonalOperations`` + resource. + + For more information, read Global, Regional, and Zonal + Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/projects/{project}/regions/{region}/publicDelegatedPrefixes/{public_delegated_prefix}".format( + host=self._host, + project=request.project, + region=request.region, + public_delegated_prefix=request.public_delegated_prefix, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.DeletePublicDelegatedPrefixeRequest.request_id in request: + query_params["requestId"] = request.request_id + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) + + # 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 + return compute.Operation.from_json(response.content, ignore_unknown_fields=True) + + def get( + self, + request: compute.GetPublicDelegatedPrefixeRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.PublicDelegatedPrefix: + r"""Call the get method over HTTP. + + Args: + request (~.compute.GetPublicDelegatedPrefixeRequest): + The request object. A request message for + PublicDelegatedPrefixes.Get. See the + method description for details. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.PublicDelegatedPrefix: + A PublicDelegatedPrefix resource + represents an IP block within a + PublicAdvertisedPrefix that is + configured within a single cloud scope + (global or region). IPs in the block can + be allocated to resources within that + scope. Public delegated prefixes may be + further broken up into smaller IP blocks + in the same scope as the parent block. + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/projects/{project}/regions/{region}/publicDelegatedPrefixes/{public_delegated_prefix}".format( + host=self._host, + project=request.project, + region=request.region, + public_delegated_prefix=request.public_delegated_prefix, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 + return compute.PublicDelegatedPrefix.from_json( + response.content, ignore_unknown_fields=True + ) + + def insert( + self, + request: compute.InsertPublicDelegatedPrefixeRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the insert method over HTTP. + + Args: + request (~.compute.InsertPublicDelegatedPrefixeRequest): + The request object. A request message for + PublicDelegatedPrefixes.Insert. See the + method description for details. + + 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 ``zonalOperations`` + resource. + + For more information, read Global, Regional, and Zonal + Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + + # Jsonify the request body + body = compute.PublicDelegatedPrefix.to_json( + request.public_delegated_prefix_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/projects/{project}/regions/{region}/publicDelegatedPrefixes".format( + host=self._host, project=request.project, region=request.region, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.InsertPublicDelegatedPrefixeRequest.request_id in request: + query_params["requestId"] = request.request_id + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 + return compute.Operation.from_json(response.content, ignore_unknown_fields=True) + + def list( + self, + request: compute.ListPublicDelegatedPrefixesRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.PublicDelegatedPrefixList: + r"""Call the list method over HTTP. + + Args: + request (~.compute.ListPublicDelegatedPrefixesRequest): + The request object. A request message for + PublicDelegatedPrefixes.List. See the + method description for details. + + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.PublicDelegatedPrefixList: + + """ + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/projects/{project}/regions/{region}/publicDelegatedPrefixes".format( + host=self._host, project=request.project, region=request.region, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.ListPublicDelegatedPrefixesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListPublicDelegatedPrefixesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListPublicDelegatedPrefixesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListPublicDelegatedPrefixesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListPublicDelegatedPrefixesRequest.return_partial_success in request: + query_params["returnPartialSuccess"] = request.return_partial_success + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 + return compute.PublicDelegatedPrefixList.from_json( + response.content, ignore_unknown_fields=True + ) + + def patch( + self, + request: compute.PatchPublicDelegatedPrefixeRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the patch method over HTTP. + + Args: + request (~.compute.PatchPublicDelegatedPrefixeRequest): + The request object. A request message for + PublicDelegatedPrefixes.Patch. See the + method description for details. + + 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 ``zonalOperations`` + resource. + + For more information, read Global, Regional, and Zonal + Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + + # Jsonify the request body + body = compute.PublicDelegatedPrefix.to_json( + request.public_delegated_prefix_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/projects/{project}/regions/{region}/publicDelegatedPrefixes/{public_delegated_prefix}".format( + host=self._host, + project=request.project, + region=request.region, + public_delegated_prefix=request.public_delegated_prefix, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.PatchPublicDelegatedPrefixeRequest.request_id in request: + query_params["requestId"] = request.request_id + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, 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 + return compute.Operation.from_json(response.content, ignore_unknown_fields=True) + + +__all__ = ("PublicDelegatedPrefixesRestTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_autoscalers/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_autoscalers/client.py index 8904a951a466..cadd50e725a9 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_autoscalers/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_autoscalers/client.py @@ -52,7 +52,7 @@ class RegionAutoscalersClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[RegionAutoscalersTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -75,7 +75,8 @@ class RegionAutoscalersClient(metaclass=RegionAutoscalersClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -109,7 +110,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -126,7 +128,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -145,16 +147,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> RegionAutoscalersTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - RegionAutoscalersTransport: The transport used by the client instance. + RegionAutoscalersTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -167,7 +170,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -178,7 +181,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -189,7 +192,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -200,7 +203,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -219,7 +222,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the region autoscalers client. + """Instantiates the region autoscalers client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -274,9 +277,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -288,12 +292,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -308,8 +314,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_autoscalers/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_autoscalers/transports/base.py index ad3c9cc87de8..a5db462862e5 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_autoscalers/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_autoscalers/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class RegionAutoscalersTransport(abc.ABC): """Abstract transport class for RegionAutoscalers.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_autoscalers/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_autoscalers/transports/rest.py index ac44641ef93e..6fec0512219c 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_autoscalers/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_autoscalers/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -165,10 +166,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -235,10 +240,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Autoscaler.from_json( @@ -321,10 +330,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -378,10 +391,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.RegionAutoscalerList.from_json( @@ -466,10 +483,14 @@ def patch( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -552,10 +573,14 @@ def update( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.put(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.put(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_backend_services/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_backend_services/client.py index 2afe38b44d4c..2c4251a27414 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_backend_services/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_backend_services/client.py @@ -52,7 +52,7 @@ class RegionBackendServicesClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[RegionBackendServicesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -75,7 +75,8 @@ class RegionBackendServicesClient(metaclass=RegionBackendServicesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -109,7 +110,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -126,7 +128,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -145,16 +147,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> RegionBackendServicesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - RegionBackendServicesTransport: The transport used by the client instance. + RegionBackendServicesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -167,7 +170,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -178,7 +181,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -189,7 +192,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -200,7 +203,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -219,7 +222,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the region backend services client. + """Instantiates the region backend services client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -274,9 +277,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -288,12 +292,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -308,8 +314,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_backend_services/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_backend_services/transports/base.py index 108410d603e1..e6938dbc342d 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_backend_services/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_backend_services/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class RegionBackendServicesTransport(abc.ABC): """Abstract transport class for RegionBackendServices.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_backend_services/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_backend_services/transports/rest.py index efc88e0eecf8..689be35a9453 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_backend_services/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_backend_services/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -165,10 +166,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -237,10 +242,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.BackendService.from_json( @@ -296,10 +305,14 @@ def get_health( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.BackendServiceGroupHealth.from_json( @@ -382,10 +395,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -441,10 +458,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.BackendServiceList.from_json( @@ -530,10 +551,14 @@ def patch( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -617,10 +642,14 @@ def update( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.put(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.put(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) 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 723aa8140590..6342ada41358 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 @@ -52,7 +52,7 @@ class RegionCommitmentsClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[RegionCommitmentsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -75,7 +75,8 @@ class RegionCommitmentsClient(metaclass=RegionCommitmentsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -109,7 +110,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -126,7 +128,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -145,16 +147,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> RegionCommitmentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - RegionCommitmentsTransport: The transport used by the client instance. + RegionCommitmentsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -167,7 +170,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -178,7 +181,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -189,7 +192,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -200,7 +203,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -219,7 +222,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the region commitments client. + """Instantiates the region commitments client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -274,9 +277,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -288,12 +292,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -308,8 +314,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_commitments/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_commitments/transports/base.py index af6ec798e5a4..3ff989995874 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_commitments/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_commitments/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class RegionCommitmentsTransport(abc.ABC): """Abstract transport class for RegionCommitments.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_commitments/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_commitments/transports/rest.py index 2e10851f441d..7f09ed704a43 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_commitments/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_commitments/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -147,10 +148,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.CommitmentAggregatedList.from_json( @@ -208,10 +213,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Commitment.from_json( @@ -294,10 +303,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -353,10 +366,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 return compute.CommitmentList.from_json( diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disk_types/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disk_types/client.py index 5e8ca89b2d04..fbeeca2b3e20 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disk_types/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disk_types/client.py @@ -50,7 +50,7 @@ class RegionDiskTypesClientMeta(type): _transport_registry["rest"] = RegionDiskTypesRestTransport def get_transport_class(cls, label: str = None,) -> Type[RegionDiskTypesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -73,7 +73,8 @@ class RegionDiskTypesClient(metaclass=RegionDiskTypesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -107,7 +108,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -124,7 +126,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -143,16 +145,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> RegionDiskTypesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - RegionDiskTypesTransport: The transport used by the client instance. + RegionDiskTypesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -165,7 +168,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -176,7 +179,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -187,7 +190,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -198,7 +201,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -217,7 +220,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the region disk types client. + """Instantiates the region disk types client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -272,9 +275,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -286,12 +290,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -306,8 +312,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disk_types/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disk_types/transports/base.py index 830873fbad04..d1eba13781bf 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disk_types/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disk_types/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class RegionDiskTypesTransport(abc.ABC): """Abstract transport class for RegionDiskTypes.""" @@ -120,10 +121,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -144,27 +144,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disk_types/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disk_types/transports/rest.py index 02ef58e2bbe1..b30cf3f3fe3f 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disk_types/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disk_types/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -155,10 +156,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.DiskType.from_json(response.content, ignore_unknown_fields=True) @@ -212,10 +217,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 return compute.RegionDiskTypeList.from_json( diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disks/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disks/client.py index 719a567475a8..4e7cc7c64ab1 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disks/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disks/client.py @@ -48,7 +48,7 @@ class RegionDisksClientMeta(type): _transport_registry["rest"] = RegionDisksRestTransport def get_transport_class(cls, label: str = None,) -> Type[RegionDisksTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class RegionDisksClient(metaclass=RegionDisksClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> RegionDisksTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - RegionDisksTransport: The transport used by the client instance. + RegionDisksTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the region disks client. + """Instantiates the region disks client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disks/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disks/transports/base.py index 3e504f7386a2..4c6b45b9a478 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disks/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disks/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class RegionDisksTransport(abc.ABC): """Abstract transport class for RegionDisks.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disks/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disks/transports/rest.py index d6bc0a83f6d6..8aa9d1e9faa2 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disks/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disks/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -172,10 +173,14 @@ def add_resource_policies( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -259,10 +264,14 @@ def create_snapshot( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -339,10 +348,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -409,10 +422,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Disk.from_json(response.content, ignore_unknown_fields=True) @@ -516,10 +533,14 @@ def get_iam_policy( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Policy.from_json(response.content, ignore_unknown_fields=True) @@ -602,10 +623,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -659,10 +684,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.DiskList.from_json(response.content, ignore_unknown_fields=True) @@ -746,10 +775,14 @@ def remove_resource_policies( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -833,10 +866,14 @@ def resize( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -940,10 +977,14 @@ def set_iam_policy( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Policy.from_json(response.content, ignore_unknown_fields=True) @@ -1027,10 +1068,14 @@ def set_labels( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -1084,10 +1129,14 @@ def test_iam_permissions( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.TestPermissionsResponse.from_json( diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_check_services/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_check_services/client.py index b5b47267860a..0a87cafa52f3 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_check_services/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_check_services/client.py @@ -52,7 +52,7 @@ class RegionHealthCheckServicesClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[RegionHealthCheckServicesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -75,7 +75,8 @@ class RegionHealthCheckServicesClient(metaclass=RegionHealthCheckServicesClientM @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -109,7 +110,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -126,7 +128,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -145,16 +147,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> RegionHealthCheckServicesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - RegionHealthCheckServicesTransport: The transport used by the client instance. + RegionHealthCheckServicesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -167,7 +170,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -178,7 +181,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -189,7 +192,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -200,7 +203,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -219,7 +222,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the region health check services client. + """Instantiates the region health check services client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -274,9 +277,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -288,12 +292,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -308,8 +314,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_check_services/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_check_services/transports/base.py index 3e58104213e5..73603b9abb59 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_check_services/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_check_services/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class RegionHealthCheckServicesTransport(abc.ABC): """Abstract transport class for RegionHealthCheckServices.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_check_services/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_check_services/transports/rest.py index dbeeb24462b0..162ac4fc8476 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_check_services/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_check_services/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -165,10 +166,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -219,10 +224,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.HealthCheckService.from_json( @@ -305,10 +314,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -365,10 +378,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.HealthCheckServicesList.from_json( @@ -454,10 +471,14 @@ def patch( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_checks/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_checks/client.py index d51e9dc99488..d4319a20b495 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_checks/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_checks/client.py @@ -52,7 +52,7 @@ class RegionHealthChecksClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[RegionHealthChecksTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -75,7 +75,8 @@ class RegionHealthChecksClient(metaclass=RegionHealthChecksClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -109,7 +110,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -126,7 +128,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -145,16 +147,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> RegionHealthChecksTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - RegionHealthChecksTransport: The transport used by the client instance. + RegionHealthChecksTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -167,7 +170,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -178,7 +181,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -189,7 +192,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -200,7 +203,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -219,7 +222,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the region health checks client. + """Instantiates the region health checks client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -274,9 +277,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -288,12 +292,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -308,8 +314,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_checks/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_checks/transports/base.py index 54928faea8f0..718974545b0a 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_checks/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_checks/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class RegionHealthChecksTransport(abc.ABC): """Abstract transport class for RegionHealthChecks.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_checks/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_checks/transports/rest.py index d30e690fc86f..2f1892136a0f 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_checks/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_checks/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -165,10 +166,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -243,10 +248,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.HealthCheck.from_json( @@ -329,10 +338,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -388,10 +401,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.HealthCheckList.from_json( @@ -477,10 +494,14 @@ def patch( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -564,10 +585,14 @@ def update( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.put(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.put(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_group_managers/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_group_managers/client.py index 33a67273cc2c..86e099aba5d7 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_group_managers/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_group_managers/client.py @@ -52,7 +52,7 @@ class RegionInstanceGroupManagersClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[RegionInstanceGroupManagersTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -77,7 +77,8 @@ class RegionInstanceGroupManagersClient( @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -111,7 +112,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -128,7 +130,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -147,16 +149,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> RegionInstanceGroupManagersTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - RegionInstanceGroupManagersTransport: The transport used by the client instance. + RegionInstanceGroupManagersTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -169,7 +172,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -180,7 +183,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -191,7 +194,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -202,7 +205,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -221,7 +224,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the region instance group managers client. + """Instantiates the region instance group managers client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -276,9 +279,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -290,12 +294,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -310,8 +316,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -1991,18 +1997,18 @@ def recreate_instances( timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Operation: - r"""Flags the specified instances in the managed instance - group to be immediately recreated. The instances are - deleted and recreated using the current instance - template for the managed instance group. This operation - is marked as DONE when the flag is set even if the - instances have not yet been recreated. You must - separately verify the status of the recreating action - with the listmanagedinstances method. If the group is - part of a backend service that has enabled connection - draining, it can take up to 60 seconds after the - connection draining duration has elapsed before the VM - instance is removed or deleted. + r"""Flags the specified VM instances in the managed + instance group to be immediately recreated. Each + instance is recreated using the group's current + configuration. This operation is marked as DONE when the + flag is set even if the instances have not yet been + recreated. You must separately verify the status of each + instance by checking its currentAction field; for more + information, see Checking the status of managed + instances. If the group is part of a backend service + that has enabled connection draining, it can take up to + 60 seconds after the connection draining duration has + elapsed before the VM instance is removed or deleted. You can specify a maximum of 1000 instances with this method per request. diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_group_managers/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_group_managers/transports/base.py index a4f785236200..445228e5b966 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_group_managers/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_group_managers/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class RegionInstanceGroupManagersTransport(abc.ABC): """Abstract transport class for RegionInstanceGroupManagers.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_group_managers/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_group_managers/transports/rest.py index 88f581b7bd87..5fbb3771f30d 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_group_managers/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_group_managers/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -175,10 +176,14 @@ def abandon_instances( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -261,10 +266,14 @@ def apply_updates_to_instances( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -351,10 +360,14 @@ def create_instances( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -431,10 +444,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -521,10 +538,14 @@ def delete_instances( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -607,10 +628,14 @@ def delete_per_instance_configs( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -671,10 +696,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.InstanceGroupManager.from_json( @@ -757,10 +786,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -819,10 +852,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.RegionInstanceGroupManagerList.from_json( @@ -884,10 +921,14 @@ def list_errors( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.RegionInstanceGroupManagersListErrorsResponse.from_json( @@ -961,10 +1002,14 @@ def list_managed_instances( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.RegionInstanceGroupManagersListInstancesResponse.from_json( @@ -1038,10 +1083,14 @@ def list_per_instance_configs( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.RegionInstanceGroupManagersListInstanceConfigsResp.from_json( @@ -1127,10 +1176,14 @@ def patch( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -1218,10 +1271,14 @@ def patch_per_instance_configs( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -1308,10 +1365,14 @@ def recreate_instances( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -1390,10 +1451,14 @@ def resize( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -1480,10 +1545,14 @@ def set_instance_template( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -1570,10 +1639,14 @@ def set_target_pools( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -1661,10 +1734,14 @@ def update_per_instance_configs( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_groups/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_groups/client.py index a6e73ef21e60..c1accafd413b 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_groups/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_groups/client.py @@ -52,7 +52,7 @@ class RegionInstanceGroupsClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[RegionInstanceGroupsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -75,7 +75,8 @@ class RegionInstanceGroupsClient(metaclass=RegionInstanceGroupsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -109,7 +110,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -126,7 +128,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -145,16 +147,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> RegionInstanceGroupsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - RegionInstanceGroupsTransport: The transport used by the client instance. + RegionInstanceGroupsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -167,7 +170,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -178,7 +181,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -189,7 +192,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -200,7 +203,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -219,7 +222,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the region instance groups client. + """Instantiates the region instance groups client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -274,9 +277,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -288,12 +292,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -308,8 +314,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_groups/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_groups/transports/base.py index 96a16a3a44e9..e99b410c4c7d 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_groups/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_groups/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class RegionInstanceGroupsTransport(abc.ABC): """Abstract transport class for RegionInstanceGroups.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_groups/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_groups/transports/rest.py index df88fbd4f688..ef84b6daceda 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_groups/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_groups/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -155,10 +156,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.InstanceGroup.from_json( @@ -216,10 +221,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.RegionInstanceGroupList.from_json( @@ -288,10 +297,14 @@ def list_instances( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.RegionInstanceGroupsListInstances.from_json( @@ -377,10 +390,14 @@ def set_named_ports( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instances/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instances/__init__.py new file mode 100644 index 000000000000..a5c72036aa14 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instances/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 RegionInstancesClient + +__all__ = ("RegionInstancesClient",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instances/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instances/client.py new file mode 100644 index 000000000000..c98ec09347cc --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instances/client.py @@ -0,0 +1,449 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.compute_v1.types import compute +from .transports.base import RegionInstancesTransport, DEFAULT_CLIENT_INFO +from .transports.rest import RegionInstancesRestTransport + + +class RegionInstancesClientMeta(type): + """Metaclass for the RegionInstances 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[RegionInstancesTransport]] + _transport_registry["rest"] = RegionInstancesRestTransport + + def get_transport_class(cls, label: str = None,) -> Type[RegionInstancesTransport]: + """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 RegionInstancesClient(metaclass=RegionInstancesClientMeta): + """The RegionInstances 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") + + DEFAULT_ENDPOINT = "compute.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @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: + RegionInstancesClient: 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: + RegionInstancesClient: 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) -> RegionInstancesTransport: + """Returns the transport used by the client instance. + + Returns: + RegionInstancesTransport: 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 {} + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, RegionInstancesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the region instances 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, RegionInstancesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "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). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS 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. + 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. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, RegionInstancesTransport): + # transport is a RegionInstancesTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def bulk_insert( + self, + request: compute.BulkInsertRegionInstanceRequest = None, + *, + project: str = None, + region: str = None, + bulk_insert_instance_resource_resource: compute.BulkInsertInstanceResource = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Creates multiple instances in a given region. Count + specifies the number of instances to create. + + Args: + request (google.cloud.compute_v1.types.BulkInsertRegionInstanceRequest): + The request object. A request message for + RegionInstances.BulkInsert. 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. + bulk_insert_instance_resource_resource (google.cloud.compute_v1.types.BulkInsertInstanceResource): + The body resource for this request + This corresponds to the ``bulk_insert_instance_resource_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.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - [Global](/compute/docs/reference/rest/{$api_version}/globalOperations) + \* + [Regional](/compute/docs/reference/rest/{$api_version}/regionOperations) + \* + [Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations) + + 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 + zonalOperations resource. + + For more information, read Global, Regional, and + Zonal Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + # Create or coerce a protobuf request object. + # Sanity 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, bulk_insert_instance_resource_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.BulkInsertRegionInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.BulkInsertRegionInstanceRequest): + request = compute.BulkInsertRegionInstanceRequest(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 bulk_insert_instance_resource_resource is not None: + request.bulk_insert_instance_resource_resource = ( + bulk_insert_instance_resource_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.bulk_insert] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("RegionInstancesClient",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instances/transports/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instances/transports/__init__.py new file mode 100644 index 000000000000..6885a7dadc89 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instances/transports/__init__.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 RegionInstancesTransport +from .rest import RegionInstancesRestTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[RegionInstancesTransport]] +_transport_registry["rest"] = RegionInstancesRestTransport + +__all__ = ( + "RegionInstancesTransport", + "RegionInstancesRestTransport", +) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instances/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instances/transports/base.py new file mode 100644 index 000000000000..1891660e94cf --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instances/transports/base.py @@ -0,0 +1,164 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 packaging.version +import pkg_resources +from requests import __version__ as requests_version + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.compute_v1.types import compute + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class RegionInstancesTransport(abc.ABC): + """Abstract transport class for RegionInstances.""" + + 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: 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, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + 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. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_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 + ) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.bulk_insert: gapic_v1.method.wrap_method( + self.bulk_insert, default_timeout=None, client_info=client_info, + ), + } + + @property + def bulk_insert( + self, + ) -> Callable[ + [compute.BulkInsertRegionInstanceRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + +__all__ = ("RegionInstancesTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instances/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instances/transports/rest.py new file mode 100644 index 000000000000..2231e5fd644d --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instances/transports/rest.py @@ -0,0 +1,186 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # 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.auth.transport.requests import AuthorizedSession + +from google.cloud.compute_v1.types import compute + +from .base import RegionInstancesTransport, DEFAULT_CLIENT_INFO + + +class RegionInstancesRestTransport(RegionInstancesTransport): + """REST backend transport for RegionInstances. + + The RegionInstances API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "compute.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + 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're developing + your own client library. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, credentials=credentials, client_info=client_info, + ) + 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._prep_wrapped_messages(client_info) + + def bulk_insert( + self, + request: compute.BulkInsertRegionInstanceRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the bulk insert method over HTTP. + + Args: + request (~.compute.BulkInsertRegionInstanceRequest): + The request object. A request message for + RegionInstances.BulkInsert. See the + method description for details. + + 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 ``zonalOperations`` + resource. + + For more information, read Global, Regional, and Zonal + Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + + # Jsonify the request body + body = compute.BulkInsertInstanceResource.to_json( + request.bulk_insert_instance_resource_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/projects/{project}/regions/{region}/instances/bulkInsert".format( + host=self._host, project=request.project, region=request.region, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.BulkInsertRegionInstanceRequest.request_id in request: + query_params["requestId"] = request.request_id + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 + return compute.Operation.from_json(response.content, ignore_unknown_fields=True) + + +__all__ = ("RegionInstancesRestTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_network_endpoint_groups/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_network_endpoint_groups/client.py index 339a56287c98..abbe6ce691a3 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_network_endpoint_groups/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_network_endpoint_groups/client.py @@ -52,7 +52,7 @@ class RegionNetworkEndpointGroupsClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[RegionNetworkEndpointGroupsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -77,7 +77,8 @@ class RegionNetworkEndpointGroupsClient( @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -111,7 +112,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -128,7 +130,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -147,16 +149,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> RegionNetworkEndpointGroupsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - RegionNetworkEndpointGroupsTransport: The transport used by the client instance. + RegionNetworkEndpointGroupsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -169,7 +172,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -180,7 +183,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -191,7 +194,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -202,7 +205,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -221,7 +224,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the region network endpoint groups client. + """Instantiates the region network endpoint groups client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -276,9 +279,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -290,12 +294,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -310,8 +316,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_network_endpoint_groups/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_network_endpoint_groups/transports/base.py index f16144a081f2..39098f4f57ff 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_network_endpoint_groups/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_network_endpoint_groups/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class RegionNetworkEndpointGroupsTransport(abc.ABC): """Abstract transport class for RegionNetworkEndpointGroups.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_network_endpoint_groups/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_network_endpoint_groups/transports/rest.py index 36d9cb0987f9..9ae255c0d2f0 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_network_endpoint_groups/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_network_endpoint_groups/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -165,10 +166,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -228,10 +233,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.NetworkEndpointGroup.from_json( @@ -314,10 +323,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -374,10 +387,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 return compute.NetworkEndpointGroupList.from_json( diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_notification_endpoints/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_notification_endpoints/client.py index 21cf85ae167b..d0570c8a614d 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_notification_endpoints/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_notification_endpoints/client.py @@ -52,7 +52,7 @@ class RegionNotificationEndpointsClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[RegionNotificationEndpointsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -77,7 +77,8 @@ class RegionNotificationEndpointsClient( @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -111,7 +112,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -128,7 +130,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -147,16 +149,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> RegionNotificationEndpointsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - RegionNotificationEndpointsTransport: The transport used by the client instance. + RegionNotificationEndpointsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -169,7 +172,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -180,7 +183,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -191,7 +194,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -202,7 +205,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -221,7 +224,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the region notification endpoints client. + """Instantiates the region notification endpoints client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -276,9 +279,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -290,12 +294,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -310,8 +316,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_notification_endpoints/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_notification_endpoints/transports/base.py index af575760b5cd..ec605dee9318 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_notification_endpoints/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_notification_endpoints/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class RegionNotificationEndpointsTransport(abc.ABC): """Abstract transport class for RegionNotificationEndpoints.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_notification_endpoints/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_notification_endpoints/transports/rest.py index af411a4b087d..8d82c8a7a6b2 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_notification_endpoints/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_notification_endpoints/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -165,10 +166,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -225,10 +230,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.NotificationEndpoint.from_json( @@ -311,10 +320,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -371,10 +384,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 return compute.NotificationEndpointList.from_json( diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_operations/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_operations/client.py index fa80494fcd7b..26c947209267 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_operations/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_operations/client.py @@ -50,7 +50,7 @@ class RegionOperationsClientMeta(type): _transport_registry["rest"] = RegionOperationsRestTransport def get_transport_class(cls, label: str = None,) -> Type[RegionOperationsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -73,7 +73,8 @@ class RegionOperationsClient(metaclass=RegionOperationsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -107,7 +108,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -124,7 +126,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -143,16 +145,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> RegionOperationsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - RegionOperationsTransport: The transport used by the client instance. + RegionOperationsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -165,7 +168,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -176,7 +179,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -187,7 +190,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -198,7 +201,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -217,7 +220,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the region operations client. + """Instantiates the region operations client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -272,9 +275,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -286,12 +290,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -306,8 +312,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_operations/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_operations/transports/base.py index 01c86aad28be..1e86fe9be293 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_operations/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_operations/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class RegionOperationsTransport(abc.ABC): """Abstract transport class for RegionOperations.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_operations/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_operations/transports/rest.py index e2448c28c459..a6ad11cb6730 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_operations/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_operations/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -138,10 +139,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.DeleteRegionOperationResponse.from_json( @@ -218,10 +223,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -277,10 +286,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.OperationList.from_json( @@ -357,10 +370,14 @@ def wait( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers,) + + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_ssl_certificates/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_ssl_certificates/client.py index 9a0e999742d6..c6b23615a7b4 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_ssl_certificates/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_ssl_certificates/client.py @@ -52,7 +52,7 @@ class RegionSslCertificatesClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[RegionSslCertificatesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -75,7 +75,8 @@ class RegionSslCertificatesClient(metaclass=RegionSslCertificatesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -109,7 +110,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -126,7 +128,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -145,16 +147,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> RegionSslCertificatesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - RegionSslCertificatesTransport: The transport used by the client instance. + RegionSslCertificatesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -167,7 +170,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -178,7 +181,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -189,7 +192,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -200,7 +203,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -219,7 +222,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the region ssl certificates client. + """Instantiates the region ssl certificates client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -274,9 +277,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -288,12 +292,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -308,8 +314,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_ssl_certificates/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_ssl_certificates/transports/base.py index 39ec28d6d16f..9366e3a4188b 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_ssl_certificates/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_ssl_certificates/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class RegionSslCertificatesTransport(abc.ABC): """Abstract transport class for RegionSslCertificates.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_ssl_certificates/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_ssl_certificates/transports/rest.py index 3dbb7fee3b74..a7a8e166789d 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_ssl_certificates/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_ssl_certificates/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -165,10 +166,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -241,10 +246,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.SslCertificate.from_json( @@ -327,10 +336,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -386,10 +399,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 return compute.SslCertificateList.from_json( diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_http_proxies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_http_proxies/client.py index 244f3d173f94..254d0886e7e4 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_http_proxies/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_http_proxies/client.py @@ -52,7 +52,7 @@ class RegionTargetHttpProxiesClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[RegionTargetHttpProxiesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -75,7 +75,8 @@ class RegionTargetHttpProxiesClient(metaclass=RegionTargetHttpProxiesClientMeta) @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -109,7 +110,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -126,7 +128,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -145,16 +147,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> RegionTargetHttpProxiesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - RegionTargetHttpProxiesTransport: The transport used by the client instance. + RegionTargetHttpProxiesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -167,7 +170,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -178,7 +181,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -189,7 +192,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -200,7 +203,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -219,7 +222,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the region target http proxies client. + """Instantiates the region target http proxies client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -274,9 +277,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -288,12 +292,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -308,8 +314,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_http_proxies/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_http_proxies/transports/base.py index f8c422f73df9..a86add99d5c0 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_http_proxies/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_http_proxies/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class RegionTargetHttpProxiesTransport(abc.ABC): """Abstract transport class for RegionTargetHttpProxies.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_http_proxies/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_http_proxies/transports/rest.py index 5413cc717e91..77fe37895789 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_http_proxies/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_http_proxies/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -165,10 +166,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -238,10 +243,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.TargetHttpProxy.from_json( @@ -324,10 +333,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -381,10 +394,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.TargetHttpProxyList.from_json( @@ -470,10 +487,14 @@ def set_url_map( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_https_proxies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_https_proxies/client.py index 053f65d4a630..73cb8be429fa 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_https_proxies/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_https_proxies/client.py @@ -52,7 +52,7 @@ class RegionTargetHttpsProxiesClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[RegionTargetHttpsProxiesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -75,7 +75,8 @@ class RegionTargetHttpsProxiesClient(metaclass=RegionTargetHttpsProxiesClientMet @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -109,7 +110,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -126,7 +128,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -145,16 +147,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> RegionTargetHttpsProxiesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - RegionTargetHttpsProxiesTransport: The transport used by the client instance. + RegionTargetHttpsProxiesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -167,7 +170,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -178,7 +181,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -189,7 +192,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -200,7 +203,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -219,7 +222,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the region target https proxies client. + """Instantiates the region target https proxies client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -274,9 +277,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -288,12 +292,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -308,8 +314,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_https_proxies/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_https_proxies/transports/base.py index d39837b9894b..06ee8b06d711 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_https_proxies/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_https_proxies/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class RegionTargetHttpsProxiesTransport(abc.ABC): """Abstract transport class for RegionTargetHttpsProxies.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_https_proxies/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_https_proxies/transports/rest.py index 258ffc1a7215..693ef242dcce 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_https_proxies/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_https_proxies/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -165,10 +166,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -237,10 +242,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.TargetHttpsProxy.from_json( @@ -323,10 +332,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -385,10 +398,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.TargetHttpsProxyList.from_json( @@ -477,10 +494,14 @@ def set_ssl_certificates( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -564,10 +585,14 @@ def set_url_map( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_url_maps/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_url_maps/client.py index 1f5ddd5370ca..e5e02e1da7a0 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_url_maps/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_url_maps/client.py @@ -48,7 +48,7 @@ class RegionUrlMapsClientMeta(type): _transport_registry["rest"] = RegionUrlMapsRestTransport def get_transport_class(cls, label: str = None,) -> Type[RegionUrlMapsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class RegionUrlMapsClient(metaclass=RegionUrlMapsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> RegionUrlMapsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - RegionUrlMapsTransport: The transport used by the client instance. + RegionUrlMapsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the region url maps client. + """Instantiates the region url maps client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_url_maps/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_url_maps/transports/base.py index c350691860bb..55db53c6ae72 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_url_maps/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_url_maps/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class RegionUrlMapsTransport(abc.ABC): """Abstract transport class for RegionUrlMaps.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_url_maps/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_url_maps/transports/rest.py index 5f8fbc185b42..9ed6579b1fa7 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_url_maps/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_url_maps/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -165,10 +166,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -247,10 +252,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.UrlMap.from_json(response.content, ignore_unknown_fields=True) @@ -331,10 +340,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -388,10 +401,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.UrlMapList.from_json( @@ -477,10 +494,14 @@ def patch( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -564,10 +585,14 @@ def update( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.put(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.put(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -621,10 +646,14 @@ def validate( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.UrlMapsValidateResponse.from_json( diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/regions/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/regions/client.py index 6b2436eea807..2a363de0bd04 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/regions/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/regions/client.py @@ -48,7 +48,7 @@ class RegionsClientMeta(type): _transport_registry["rest"] = RegionsRestTransport def get_transport_class(cls, label: str = None,) -> Type[RegionsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class RegionsClient(metaclass=RegionsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> RegionsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - RegionsTransport: The transport used by the client instance. + RegionsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the regions client. + """Instantiates the regions client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/regions/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/regions/transports/base.py index 59b2663fddfd..37ff0b0a448d 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/regions/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/regions/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class RegionsTransport(abc.ABC): """Abstract transport class for Regions.""" @@ -120,10 +121,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -144,27 +144,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/regions/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/regions/transports/rest.py index 609d29097bf9..abbaaecf37ff 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/regions/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/regions/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -136,10 +137,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Region.from_json(response.content, ignore_unknown_fields=True) @@ -192,10 +197,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 return compute.RegionList.from_json( 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 679f436b2c98..795722b4c9d6 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 @@ -48,7 +48,7 @@ class ReservationsClientMeta(type): _transport_registry["rest"] = ReservationsRestTransport def get_transport_class(cls, label: str = None,) -> Type[ReservationsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class ReservationsClient(metaclass=ReservationsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ReservationsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - ReservationsTransport: The transport used by the client instance. + ReservationsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the reservations client. + """Instantiates the reservations client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/reservations/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/reservations/transports/base.py index fead04fa4307..c56cccc8bf3e 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/reservations/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/reservations/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class ReservationsTransport(abc.ABC): """Abstract transport class for Reservations.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/reservations/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/reservations/transports/rest.py index 806ea2cc55de..fc1e58093379 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/reservations/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/reservations/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -144,10 +145,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.ReservationAggregatedList.from_json( @@ -226,10 +231,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -281,10 +290,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Reservation.from_json( @@ -390,10 +403,14 @@ def get_iam_policy( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Policy.from_json(response.content, ignore_unknown_fields=True) @@ -474,10 +491,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -531,10 +552,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.ReservationList.from_json( @@ -620,10 +645,14 @@ def resize( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -727,10 +756,14 @@ def set_iam_policy( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Policy.from_json(response.content, ignore_unknown_fields=True) @@ -784,10 +817,14 @@ def test_iam_permissions( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.TestPermissionsResponse.from_json( 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 3c3b394de8e3..cf85ecb271a8 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 @@ -50,7 +50,7 @@ class ResourcePoliciesClientMeta(type): _transport_registry["rest"] = ResourcePoliciesRestTransport def get_transport_class(cls, label: str = None,) -> Type[ResourcePoliciesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -73,7 +73,8 @@ class ResourcePoliciesClient(metaclass=ResourcePoliciesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -107,7 +108,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -124,7 +126,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -143,16 +145,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ResourcePoliciesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - ResourcePoliciesTransport: The transport used by the client instance. + ResourcePoliciesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -165,7 +168,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -176,7 +179,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -187,7 +190,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -198,7 +201,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -217,7 +220,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the resource policies client. + """Instantiates the resource policies client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -272,9 +275,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -286,12 +290,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -306,8 +312,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/resource_policies/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/resource_policies/transports/base.py index d1317d0072d5..46617a0366bd 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/resource_policies/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/resource_policies/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class ResourcePoliciesTransport(abc.ABC): """Abstract transport class for ResourcePolicies.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/resource_policies/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/resource_policies/transports/rest.py index c69a57e673f9..3160a86ac110 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/resource_policies/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/resource_policies/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -147,10 +148,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.ResourcePolicyAggregatedList.from_json( @@ -229,10 +234,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -285,10 +294,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.ResourcePolicy.from_json( @@ -394,10 +407,14 @@ def get_iam_policy( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Policy.from_json(response.content, ignore_unknown_fields=True) @@ -478,10 +495,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -535,10 +556,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.ResourcePolicyList.from_json( @@ -644,10 +669,14 @@ def set_iam_policy( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Policy.from_json(response.content, ignore_unknown_fields=True) @@ -701,10 +730,14 @@ def test_iam_permissions( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.TestPermissionsResponse.from_json( 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 a5f5a35d4e50..90536eb719a3 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 @@ -48,7 +48,7 @@ class RoutersClientMeta(type): _transport_registry["rest"] = RoutersRestTransport def get_transport_class(cls, label: str = None,) -> Type[RoutersTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class RoutersClient(metaclass=RoutersClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> RoutersTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - RoutersTransport: The transport used by the client instance. + RoutersTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the routers client. + """Instantiates the routers client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/transports/base.py index df2f3e078b32..11c81a8a7eae 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class RoutersTransport(abc.ABC): """Abstract transport class for Routers.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/transports/rest.py index 7e94404dfcd6..f8adad2b49ca 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -144,10 +145,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.RouterAggregatedList.from_json( @@ -225,10 +230,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -277,10 +286,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Router.from_json(response.content, ignore_unknown_fields=True) @@ -339,10 +352,14 @@ def get_nat_mapping_info( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.VmEndpointNatMappingsList.from_json( @@ -391,10 +408,14 @@ def get_router_status( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.RouterStatusResponse.from_json( @@ -476,10 +497,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -532,10 +557,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.RouterList.from_json( @@ -620,10 +649,14 @@ def patch( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -677,10 +710,14 @@ def preview( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.RoutersPreviewResponse.from_json( @@ -765,10 +802,14 @@ def update( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.put(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.put(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/routes/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/routes/client.py index 71867bee0e19..15a059f511e7 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/routes/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/routes/client.py @@ -48,7 +48,7 @@ class RoutesClientMeta(type): _transport_registry["rest"] = RoutesRestTransport def get_transport_class(cls, label: str = None,) -> Type[RoutesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class RoutesClient(metaclass=RoutesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> RoutesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - RoutesTransport: The transport used by the client instance. + RoutesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the routes client. + """Instantiates the routes client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/routes/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/routes/transports/base.py index 6b6c6d84cba0..521530b01f72 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/routes/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/routes/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class RoutesTransport(abc.ABC): """Abstract transport class for Routes.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/routes/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/routes/transports/rest.py index a0f4f9d52fb5..71d37948db58 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/routes/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/routes/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -161,10 +162,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -214,10 +219,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Route.from_json(response.content, ignore_unknown_fields=True) @@ -297,10 +306,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -353,10 +366,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 return compute.RouteList.from_json(response.content, ignore_unknown_fields=True) 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 7957504ec2b0..9440c793a4e7 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 @@ -50,7 +50,7 @@ class SecurityPoliciesClientMeta(type): _transport_registry["rest"] = SecurityPoliciesRestTransport def get_transport_class(cls, label: str = None,) -> Type[SecurityPoliciesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -73,7 +73,8 @@ class SecurityPoliciesClient(metaclass=SecurityPoliciesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -107,7 +108,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -124,7 +126,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -143,16 +145,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SecurityPoliciesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - SecurityPoliciesTransport: The transport used by the client instance. + SecurityPoliciesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -165,7 +168,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -176,7 +179,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -187,7 +190,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -198,7 +201,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -217,7 +220,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the security policies client. + """Instantiates the security policies client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -272,9 +275,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -286,12 +290,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -306,8 +312,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/security_policies/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/security_policies/transports/base.py index 985a99f72de3..4b4a7d916a57 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/security_policies/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/security_policies/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class SecurityPoliciesTransport(abc.ABC): """Abstract transport class for SecurityPolicies.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/security_policies/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/security_policies/transports/rest.py index 8479cb74d120..6daf2952b2c4 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/security_policies/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/security_policies/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -169,10 +170,14 @@ def add_rule( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -248,10 +253,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -304,10 +313,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.SecurityPolicy.from_json( @@ -361,10 +374,14 @@ def get_rule( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.SecurityPolicyRule.from_json( @@ -447,10 +464,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -504,10 +525,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.SecurityPolicyList.from_json( @@ -579,10 +604,14 @@ def list_preconfigured_expression_sets( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse.from_json( @@ -667,10 +696,14 @@ def patch( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -753,10 +786,14 @@ def patch_rule( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -832,10 +869,14 @@ def remove_rule( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers,) + + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/snapshots/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/snapshots/client.py index 57057c0089f0..50a39cbfa23e 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/snapshots/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/snapshots/client.py @@ -48,7 +48,7 @@ class SnapshotsClientMeta(type): _transport_registry["rest"] = SnapshotsRestTransport def get_transport_class(cls, label: str = None,) -> Type[SnapshotsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class SnapshotsClient(metaclass=SnapshotsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SnapshotsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - SnapshotsTransport: The transport used by the client instance. + SnapshotsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the snapshots client. + """Instantiates the snapshots client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/snapshots/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/snapshots/transports/base.py index 30c94a21c16b..d3981daf12b5 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/snapshots/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/snapshots/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class SnapshotsTransport(abc.ABC): """Abstract transport class for Snapshots.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/snapshots/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/snapshots/transports/rest.py index f7806d93a458..5262e7b57349 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/snapshots/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/snapshots/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -162,10 +163,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -214,10 +219,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Snapshot.from_json(response.content, ignore_unknown_fields=True) @@ -318,10 +327,14 @@ def get_iam_policy( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Policy.from_json(response.content, ignore_unknown_fields=True) @@ -376,10 +389,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.SnapshotList.from_json( @@ -482,10 +499,14 @@ def set_iam_policy( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Policy.from_json(response.content, ignore_unknown_fields=True) @@ -564,10 +585,14 @@ def set_labels( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -618,10 +643,14 @@ def test_iam_permissions( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.TestPermissionsResponse.from_json( 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 30b62ed9e636..0ca1750665dc 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 @@ -50,7 +50,7 @@ class SslCertificatesClientMeta(type): _transport_registry["rest"] = SslCertificatesRestTransport def get_transport_class(cls, label: str = None,) -> Type[SslCertificatesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -73,7 +73,8 @@ class SslCertificatesClient(metaclass=SslCertificatesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -107,7 +108,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -124,7 +126,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -143,16 +145,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SslCertificatesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - SslCertificatesTransport: The transport used by the client instance. + SslCertificatesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -165,7 +168,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -176,7 +179,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -187,7 +190,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -198,7 +201,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -217,7 +220,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the ssl certificates client. + """Instantiates the ssl certificates client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -272,9 +275,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -286,12 +290,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -306,8 +312,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_certificates/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_certificates/transports/base.py index b582f1a4ee16..9012f2be672c 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_certificates/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_certificates/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class SslCertificatesTransport(abc.ABC): """Abstract transport class for SslCertificates.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_certificates/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_certificates/transports/rest.py index 9d36ca619d6d..05641956a5b4 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_certificates/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_certificates/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -147,10 +148,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.SslCertificateAggregatedList.from_json( @@ -228,10 +233,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -303,10 +312,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.SslCertificate.from_json( @@ -389,10 +402,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -448,10 +465,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 return compute.SslCertificateList.from_json( 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 837648affb87..420837eb8046 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 @@ -48,7 +48,7 @@ class SslPoliciesClientMeta(type): _transport_registry["rest"] = SslPoliciesRestTransport def get_transport_class(cls, label: str = None,) -> Type[SslPoliciesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class SslPoliciesClient(metaclass=SslPoliciesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SslPoliciesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - SslPoliciesTransport: The transport used by the client instance. + SslPoliciesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the ssl policies client. + """Instantiates the ssl policies client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_policies/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_policies/transports/base.py index 0999ec7ac218..d50542c46962 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_policies/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_policies/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class SslPoliciesTransport(abc.ABC): """Abstract transport class for SslPolicies.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_policies/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_policies/transports/rest.py index ac2e008509f2..879c1e41d409 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_policies/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_policies/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -162,10 +163,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -216,10 +221,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.SslPolicy.from_json(response.content, ignore_unknown_fields=True) @@ -300,10 +309,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -357,10 +370,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.SslPoliciesList.from_json( @@ -419,10 +436,14 @@ def list_available_features( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.SslPoliciesListAvailableFeaturesResponse.from_json( @@ -505,10 +526,14 @@ def patch( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) 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 02e6a793a58c..bffcb1a39324 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 @@ -48,7 +48,7 @@ class SubnetworksClientMeta(type): _transport_registry["rest"] = SubnetworksRestTransport def get_transport_class(cls, label: str = None,) -> Type[SubnetworksTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class SubnetworksClient(metaclass=SubnetworksClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SubnetworksTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - SubnetworksTransport: The transport used by the client instance. + SubnetworksTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the subnetworks client. + """Instantiates the subnetworks client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/subnetworks/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/subnetworks/transports/base.py index e9fc688c49b7..62c836563864 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/subnetworks/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/subnetworks/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class SubnetworksTransport(abc.ABC): """Abstract transport class for Subnetworks.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/subnetworks/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/subnetworks/transports/rest.py index 58cb7744d93d..da10ad4bde95 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/subnetworks/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/subnetworks/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -144,10 +145,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.SubnetworkAggregatedList.from_json( @@ -226,10 +231,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -313,10 +322,14 @@ def expand_ip_cidr_range( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -370,10 +383,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Subnetwork.from_json( @@ -479,10 +496,14 @@ def get_iam_policy( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Policy.from_json(response.content, ignore_unknown_fields=True) @@ -563,10 +584,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -622,10 +647,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.SubnetworkList.from_json( @@ -681,10 +710,14 @@ def list_usable( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.UsableSubnetworksAggregatedList.from_json( @@ -772,10 +805,14 @@ def patch( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -879,10 +916,14 @@ def set_iam_policy( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Policy.from_json(response.content, ignore_unknown_fields=True) @@ -967,10 +1008,14 @@ def set_private_ip_google_access( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -1024,10 +1069,14 @@ def test_iam_permissions( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.TestPermissionsResponse.from_json( diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_grpc_proxies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_grpc_proxies/client.py index 2441137154e1..be103940306b 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_grpc_proxies/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_grpc_proxies/client.py @@ -52,7 +52,7 @@ class TargetGrpcProxiesClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[TargetGrpcProxiesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -75,7 +75,8 @@ class TargetGrpcProxiesClient(metaclass=TargetGrpcProxiesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -109,7 +110,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -126,7 +128,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -145,16 +147,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> TargetGrpcProxiesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - TargetGrpcProxiesTransport: The transport used by the client instance. + TargetGrpcProxiesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -167,7 +170,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -178,7 +181,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -189,7 +192,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -200,7 +203,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -219,7 +222,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the target grpc proxies client. + """Instantiates the target grpc proxies client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -274,9 +277,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -288,12 +292,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -308,8 +314,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -463,10 +469,11 @@ def get( Represents a Target gRPC Proxy resource. A target gRPC proxy is a component of load balancers - intended for load balancing gRPC traffic. Global - forwarding rules reference a target gRPC proxy. The - Target gRPC Proxy references a URL map which - specifies how traffic routes to gRPC backend + intended for load balancing gRPC traffic. Only global + forwarding rules with load balancing scheme + INTERNAL_SELF_MANAGED can reference a target gRPC + proxy. The target gRPC Proxy references a URL map + that specifies how traffic is routed to gRPC backend services. (== resource_for {$api_version}.targetGrpcProxies ==) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_grpc_proxies/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_grpc_proxies/transports/base.py index 57d27673fa36..215c7f87fd95 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_grpc_proxies/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_grpc_proxies/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class TargetGrpcProxiesTransport(abc.ABC): """Abstract transport class for TargetGrpcProxies.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_grpc_proxies/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_grpc_proxies/transports/rest.py index 30ffb7631244..8080fea9352b 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_grpc_proxies/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_grpc_proxies/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -164,10 +165,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -194,11 +199,13 @@ def get( Represents a Target gRPC Proxy resource. A target gRPC proxy is a component of load balancers - intended for load balancing gRPC traffic. Global - forwarding rules reference a target gRPC proxy. The - Target gRPC Proxy references a URL map which specifies - how traffic routes to gRPC backend services. (== - resource_for {$api_version}.targetGrpcProxies ==) + intended for load balancing gRPC traffic. Only global + forwarding rules with load balancing scheme + INTERNAL_SELF_MANAGED can reference a target gRPC proxy. + The target gRPC Proxy references a URL map that + specifies how traffic is routed to gRPC backend + services. (== resource_for + {$api_version}.targetGrpcProxies ==) """ @@ -221,10 +228,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.TargetGrpcProxy.from_json( @@ -307,10 +318,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -364,10 +379,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.TargetGrpcProxyList.from_json( @@ -452,10 +471,14 @@ def patch( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) 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 c5108a6ffc16..80c89743c364 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 @@ -52,7 +52,7 @@ class TargetHttpProxiesClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[TargetHttpProxiesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -75,7 +75,8 @@ class TargetHttpProxiesClient(metaclass=TargetHttpProxiesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -109,7 +110,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -126,7 +128,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -145,16 +147,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> TargetHttpProxiesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - TargetHttpProxiesTransport: The transport used by the client instance. + TargetHttpProxiesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -167,7 +170,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -178,7 +181,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -189,7 +192,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -200,7 +203,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -219,7 +222,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the target http proxies client. + """Instantiates the target http proxies client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -274,9 +277,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -288,12 +292,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -308,8 +314,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_http_proxies/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_http_proxies/transports/base.py index 91acce6c4bbd..dd4c72f5cce2 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_http_proxies/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_http_proxies/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class TargetHttpProxiesTransport(abc.ABC): """Abstract transport class for TargetHttpProxies.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_http_proxies/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_http_proxies/transports/rest.py index 9f9dce2aacad..e25f2db5b16d 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_http_proxies/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_http_proxies/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -147,10 +148,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.TargetHttpProxyAggregatedList.from_json( @@ -228,10 +233,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -300,10 +309,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.TargetHttpProxy.from_json( @@ -386,10 +399,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -443,10 +460,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.TargetHttpProxyList.from_json( @@ -531,10 +552,14 @@ def patch( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -617,10 +642,14 @@ def set_url_map( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) 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 8850aae52350..87ccb296aab5 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 @@ -52,7 +52,7 @@ class TargetHttpsProxiesClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[TargetHttpsProxiesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -75,7 +75,8 @@ class TargetHttpsProxiesClient(metaclass=TargetHttpsProxiesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -109,7 +110,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -126,7 +128,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -145,16 +147,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> TargetHttpsProxiesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - TargetHttpsProxiesTransport: The transport used by the client instance. + TargetHttpsProxiesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -167,7 +170,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -178,7 +181,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -189,7 +192,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -200,7 +203,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -219,7 +222,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the target https proxies client. + """Instantiates the target https proxies client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -274,9 +277,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -288,12 +292,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -308,8 +314,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -762,6 +768,116 @@ def list( # Done; return the response. return response + def patch( + self, + request: compute.PatchTargetHttpsProxyRequest = None, + *, + project: str = None, + target_https_proxy: str = None, + target_https_proxy_resource: compute.TargetHttpsProxy = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Patches the specified TargetHttpsProxy resource with the data + included in the request. This method supports PATCH semantics + and uses JSON merge patch format and processing rules. (== + suppress_warning http-rest-shadowed ==) + + Args: + request (google.cloud.compute_v1.types.PatchTargetHttpsProxyRequest): + The request object. A request message for + TargetHttpsProxies.Patch. See the method description for + details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + target_https_proxy (str): + Name of the TargetHttpsProxy resource + to patch. + + This corresponds to the ``target_https_proxy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + target_https_proxy_resource (google.cloud.compute_v1.types.TargetHttpsProxy): + The body resource for this request + This corresponds to the ``target_https_proxy_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.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - [Global](/compute/docs/reference/rest/{$api_version}/globalOperations) + \* + [Regional](/compute/docs/reference/rest/{$api_version}/regionOperations) + \* + [Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations) + + 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 + zonalOperations resource. + + For more information, read Global, Regional, and + Zonal Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + # Create or coerce a protobuf request object. + # Sanity 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, target_https_proxy, target_https_proxy_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.PatchTargetHttpsProxyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.PatchTargetHttpsProxyRequest): + request = compute.PatchTargetHttpsProxyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if target_https_proxy is not None: + request.target_https_proxy = target_https_proxy + if target_https_proxy_resource is not None: + request.target_https_proxy_resource = target_https_proxy_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.patch] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + def set_quic_override( self, request: compute.SetQuicOverrideTargetHttpsProxyRequest = None, diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_https_proxies/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_https_proxies/transports/base.py index 620a8bf28bd6..b61aa7ea7fa8 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_https_proxies/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_https_proxies/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class TargetHttpsProxiesTransport(abc.ABC): """Abstract transport class for TargetHttpsProxies.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -182,6 +161,9 @@ def _prep_wrapped_messages(self, client_info): self.list: gapic_v1.method.wrap_method( self.list, default_timeout=None, client_info=client_info, ), + self.patch: gapic_v1.method.wrap_method( + self.patch, default_timeout=None, client_info=client_info, + ), self.set_quic_override: gapic_v1.method.wrap_method( self.set_quic_override, default_timeout=None, client_info=client_info, ), @@ -246,6 +228,15 @@ def list( ]: raise NotImplementedError() + @property + def patch( + self, + ) -> Callable[ + [compute.PatchTargetHttpsProxyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + @property def set_quic_override( self, diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_https_proxies/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_https_proxies/transports/rest.py index 5118937a133b..78323edfc25f 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_https_proxies/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_https_proxies/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -150,10 +151,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.TargetHttpsProxyAggregatedList.from_json( @@ -231,10 +236,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -302,10 +311,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.TargetHttpsProxy.from_json( @@ -388,10 +401,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -447,16 +464,110 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.TargetHttpsProxyList.from_json( response.content, ignore_unknown_fields=True ) + def patch( + self, + request: compute.PatchTargetHttpsProxyRequest, + *, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the patch method over HTTP. + + Args: + request (~.compute.PatchTargetHttpsProxyRequest): + The request object. A request message for + TargetHttpsProxies.Patch. See the method + description for details. + + 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 ``zonalOperations`` + resource. + + For more information, read Global, Regional, and Zonal + Resources. (== resource_for + {$api_version}.globalOperations ==) (== resource_for + {$api_version}.regionOperations ==) (== resource_for + {$api_version}.zoneOperations ==) + + """ + + # Jsonify the request body + body = compute.TargetHttpsProxy.to_json( + request.target_https_proxy_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + + # TODO(yon-mg): need to handle grpc transcoding and parse url correctly + # current impl assumes basic case of grpc transcoding + url = "https://{host}/compute/v1/projects/{project}/global/targetHttpsProxies/{target_https_proxy}".format( + host=self._host, + project=request.project, + target_https_proxy=request.target_https_proxy, + ) + + # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields + # not required for GCE + query_params = {} + if compute.PatchTargetHttpsProxyRequest.request_id in request: + query_params["requestId"] = request.request_id + + # TODO(yon-mg): further discussion needed whether 'python truthiness' is appropriate here + # discards default values + # TODO(yon-mg): add test for proper url encoded strings + query_params = ["{k}={v}".format(k=k, v=v) for k, v in query_params.items()] + url += "?{}".format("&".join(query_params)).replace(" ", "+") + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, 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 + return compute.Operation.from_json(response.content, ignore_unknown_fields=True) + def set_quic_override( self, request: compute.SetQuicOverrideTargetHttpsProxyRequest, @@ -535,10 +646,14 @@ def set_quic_override( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -621,10 +736,14 @@ def set_ssl_certificates( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -707,10 +826,14 @@ def set_ssl_policy( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -793,10 +916,14 @@ def set_url_map( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) 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 bf9d84dafb22..6c213d161ff8 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 @@ -50,7 +50,7 @@ class TargetInstancesClientMeta(type): _transport_registry["rest"] = TargetInstancesRestTransport def get_transport_class(cls, label: str = None,) -> Type[TargetInstancesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -73,7 +73,8 @@ class TargetInstancesClient(metaclass=TargetInstancesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -107,7 +108,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -124,7 +126,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -143,16 +145,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> TargetInstancesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - TargetInstancesTransport: The transport used by the client instance. + TargetInstancesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -165,7 +168,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -176,7 +179,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -187,7 +190,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -198,7 +201,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -217,7 +220,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the target instances client. + """Instantiates the target instances client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -272,9 +275,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -286,12 +290,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -306,8 +312,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_instances/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_instances/transports/base.py index 71933229c173..f8ac05a910c7 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_instances/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_instances/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class TargetInstancesTransport(abc.ABC): """Abstract transport class for TargetInstances.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_instances/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_instances/transports/rest.py index 0c2cbd282d06..fa1ce2cfa172 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_instances/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_instances/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -147,10 +148,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.TargetInstanceAggregatedList.from_json( @@ -229,10 +234,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -287,10 +296,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.TargetInstance.from_json( @@ -373,10 +386,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -432,10 +449,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 return compute.TargetInstanceList.from_json( 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 cfecc1177117..370f46a4034b 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 @@ -48,7 +48,7 @@ class TargetPoolsClientMeta(type): _transport_registry["rest"] = TargetPoolsRestTransport def get_transport_class(cls, label: str = None,) -> Type[TargetPoolsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class TargetPoolsClient(metaclass=TargetPoolsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> TargetPoolsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - TargetPoolsTransport: The transport used by the client instance. + TargetPoolsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the target pools client. + """Instantiates the target pools client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_pools/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_pools/transports/base.py index b8df7bf2a230..b52bab2b208e 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_pools/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_pools/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class TargetPoolsTransport(abc.ABC): """Abstract transport class for TargetPools.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_pools/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_pools/transports/rest.py index b9ee4a33e5f6..a3c4b8576084 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_pools/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_pools/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -172,10 +173,14 @@ def add_health_check( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -259,10 +264,14 @@ def add_instance( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -318,10 +327,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.TargetPoolAggregatedList.from_json( @@ -400,10 +413,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -458,10 +475,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.TargetPool.from_json( @@ -517,10 +538,14 @@ def get_health( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.TargetPoolInstanceHealth.from_json( @@ -603,10 +628,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -662,10 +691,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.TargetPoolList.from_json( @@ -751,10 +784,14 @@ def remove_health_check( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -838,10 +875,14 @@ def remove_instance( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -927,10 +968,14 @@ def set_backup( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_ssl_proxies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_ssl_proxies/client.py index 4a23ebd2940d..e1f75e026d6e 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_ssl_proxies/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_ssl_proxies/client.py @@ -50,7 +50,7 @@ class TargetSslProxiesClientMeta(type): _transport_registry["rest"] = TargetSslProxiesRestTransport def get_transport_class(cls, label: str = None,) -> Type[TargetSslProxiesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -73,7 +73,8 @@ class TargetSslProxiesClient(metaclass=TargetSslProxiesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -107,7 +108,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -124,7 +126,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -143,16 +145,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> TargetSslProxiesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - TargetSslProxiesTransport: The transport used by the client instance. + TargetSslProxiesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -165,7 +168,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -176,7 +179,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -187,7 +190,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -198,7 +201,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -217,7 +220,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the target ssl proxies client. + """Instantiates the target ssl proxies client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -272,9 +275,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -286,12 +290,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -306,8 +312,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_ssl_proxies/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_ssl_proxies/transports/base.py index bd2d3580e31e..915977f488e6 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_ssl_proxies/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_ssl_proxies/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class TargetSslProxiesTransport(abc.ABC): """Abstract transport class for TargetSslProxies.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_ssl_proxies/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_ssl_proxies/transports/rest.py index 2959e1786b95..0353da0ab24d 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_ssl_proxies/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_ssl_proxies/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -164,10 +165,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -221,10 +226,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.TargetSslProxy.from_json( @@ -307,10 +316,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -366,10 +379,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.TargetSslProxyList.from_json( @@ -454,10 +471,14 @@ def set_backend_service( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -540,10 +561,14 @@ def set_proxy_header( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -626,10 +651,14 @@ def set_ssl_certificates( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -712,10 +741,14 @@ def set_ssl_policy( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) 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 81fc4e06cbe1..bd3139fee613 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 @@ -50,7 +50,7 @@ class TargetTcpProxiesClientMeta(type): _transport_registry["rest"] = TargetTcpProxiesRestTransport def get_transport_class(cls, label: str = None,) -> Type[TargetTcpProxiesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -73,7 +73,8 @@ class TargetTcpProxiesClient(metaclass=TargetTcpProxiesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -107,7 +108,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -124,7 +126,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -143,16 +145,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> TargetTcpProxiesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - TargetTcpProxiesTransport: The transport used by the client instance. + TargetTcpProxiesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -165,7 +168,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -176,7 +179,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -187,7 +190,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -198,7 +201,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -217,7 +220,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the target tcp proxies client. + """Instantiates the target tcp proxies client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -272,9 +275,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -286,12 +290,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -306,8 +312,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_tcp_proxies/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_tcp_proxies/transports/base.py index 771478189add..fd2e5de69574 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_tcp_proxies/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_tcp_proxies/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class TargetTcpProxiesTransport(abc.ABC): """Abstract transport class for TargetTcpProxies.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_tcp_proxies/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_tcp_proxies/transports/rest.py index 2d42752c40db..6691e2e35ae3 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_tcp_proxies/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_tcp_proxies/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -164,10 +165,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -221,10 +226,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.TargetTcpProxy.from_json( @@ -307,10 +316,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -366,10 +379,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.TargetTcpProxyList.from_json( @@ -454,10 +471,14 @@ def set_backend_service( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -540,10 +561,14 @@ def set_proxy_header( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) 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 d93fd4c27f9c..ed98421d43c0 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 @@ -52,7 +52,7 @@ class TargetVpnGatewaysClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[TargetVpnGatewaysTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -75,7 +75,8 @@ class TargetVpnGatewaysClient(metaclass=TargetVpnGatewaysClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -109,7 +110,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -126,7 +128,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -145,16 +147,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> TargetVpnGatewaysTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - TargetVpnGatewaysTransport: The transport used by the client instance. + TargetVpnGatewaysTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -167,7 +170,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -178,7 +181,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -189,7 +192,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -200,7 +203,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -219,7 +222,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the target vpn gateways client. + """Instantiates the target vpn gateways client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -274,9 +277,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -288,12 +292,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -308,8 +314,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_vpn_gateways/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_vpn_gateways/transports/base.py index 82aa6de8638e..0891f62b630d 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_vpn_gateways/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_vpn_gateways/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class TargetVpnGatewaysTransport(abc.ABC): """Abstract transport class for TargetVpnGateways.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_vpn_gateways/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_vpn_gateways/transports/rest.py index 2ba82a45e519..a7258cb1b9ac 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_vpn_gateways/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_vpn_gateways/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -147,10 +148,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.TargetVpnGatewayAggregatedList.from_json( @@ -229,10 +234,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -285,10 +294,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.TargetVpnGateway.from_json( @@ -371,10 +384,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -430,10 +447,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 return compute.TargetVpnGatewayList.from_json( 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 d6b0899604ec..10ee0eadad55 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 @@ -48,7 +48,7 @@ class UrlMapsClientMeta(type): _transport_registry["rest"] = UrlMapsRestTransport def get_transport_class(cls, label: str = None,) -> Type[UrlMapsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class UrlMapsClient(metaclass=UrlMapsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> UrlMapsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - UrlMapsTransport: The transport used by the client instance. + UrlMapsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the url maps client. + """Instantiates the url maps client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/url_maps/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/url_maps/transports/base.py index 04dd0ae69414..7bc812c6a410 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/url_maps/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/url_maps/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class UrlMapsTransport(abc.ABC): """Abstract transport class for UrlMaps.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/url_maps/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/url_maps/transports/rest.py index 0a92c3fe071b..4b0da7c2ebd8 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/url_maps/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/url_maps/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -144,10 +145,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.UrlMapsAggregatedList.from_json( @@ -222,10 +227,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -300,10 +309,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.UrlMap.from_json(response.content, ignore_unknown_fields=True) @@ -383,10 +396,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -467,10 +484,14 @@ def invalidate_cache( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -523,10 +544,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.UrlMapList.from_json( @@ -608,10 +633,14 @@ def patch( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.patch(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.patch(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -691,10 +720,14 @@ def update( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.put(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.put(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -745,10 +778,14 @@ def validate( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.UrlMapsValidateResponse.from_json( 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 5a67d88cac34..22ca1a123c78 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 @@ -48,7 +48,7 @@ class VpnGatewaysClientMeta(type): _transport_registry["rest"] = VpnGatewaysRestTransport def get_transport_class(cls, label: str = None,) -> Type[VpnGatewaysTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class VpnGatewaysClient(metaclass=VpnGatewaysClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> VpnGatewaysTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - VpnGatewaysTransport: The transport used by the client instance. + VpnGatewaysTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the vpn gateways client. + """Instantiates the vpn gateways client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_gateways/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_gateways/transports/base.py index effc0dec40cf..0c5df8dc60ca 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_gateways/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_gateways/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class VpnGatewaysTransport(abc.ABC): """Abstract transport class for VpnGateways.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_gateways/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_gateways/transports/rest.py index 9095b070ef6d..a2c2367d2a4a 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_gateways/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_gateways/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -144,10 +145,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.VpnGatewayAggregatedList.from_json( @@ -226,10 +231,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -285,10 +294,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.VpnGateway.from_json( @@ -337,10 +350,14 @@ def get_status( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.VpnGatewaysGetStatusResponse.from_json( @@ -423,10 +440,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -482,10 +503,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.VpnGatewayList.from_json( @@ -571,10 +596,14 @@ def set_labels( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -628,10 +657,14 @@ def test_iam_permissions( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, 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 return compute.TestPermissionsResponse.from_json( 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 a805f8b4b61b..f0a893b6f37e 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 @@ -48,7 +48,7 @@ class VpnTunnelsClientMeta(type): _transport_registry["rest"] = VpnTunnelsRestTransport def get_transport_class(cls, label: str = None,) -> Type[VpnTunnelsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class VpnTunnelsClient(metaclass=VpnTunnelsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> VpnTunnelsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - VpnTunnelsTransport: The transport used by the client instance. + VpnTunnelsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the vpn tunnels client. + """Instantiates the vpn tunnels client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_tunnels/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_tunnels/transports/base.py index cf36f3605f7b..b741537d44c3 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_tunnels/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_tunnels/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class VpnTunnelsTransport(abc.ABC): """Abstract transport class for VpnTunnels.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_tunnels/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_tunnels/transports/rest.py index 4879f5062705..ae8cde6830a4 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_tunnels/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_tunnels/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -144,10 +145,14 @@ def aggregated_list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.VpnTunnelAggregatedList.from_json( @@ -226,10 +231,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -279,10 +288,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.VpnTunnel.from_json(response.content, ignore_unknown_fields=True) @@ -363,10 +376,14 @@ def insert( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url, data=body,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers, data=body,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -422,10 +439,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 return compute.VpnTunnelList.from_json( diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/zone_operations/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/zone_operations/client.py index e62b4006b985..993cad0a8783 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/zone_operations/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/zone_operations/client.py @@ -50,7 +50,7 @@ class ZoneOperationsClientMeta(type): _transport_registry["rest"] = ZoneOperationsRestTransport def get_transport_class(cls, label: str = None,) -> Type[ZoneOperationsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -73,7 +73,8 @@ class ZoneOperationsClient(metaclass=ZoneOperationsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -107,7 +108,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -124,7 +126,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -143,16 +145,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ZoneOperationsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - ZoneOperationsTransport: The transport used by the client instance. + ZoneOperationsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -165,7 +168,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -176,7 +179,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -187,7 +190,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -198,7 +201,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -217,7 +220,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the zone operations client. + """Instantiates the zone operations client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -272,9 +275,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -286,12 +290,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -306,8 +312,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/zone_operations/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/zone_operations/transports/base.py index f2f3ddcdb223..2cadcbf5aacf 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/zone_operations/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/zone_operations/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class ZoneOperationsTransport(abc.ABC): """Abstract transport class for ZoneOperations.""" @@ -119,10 +120,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +143,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/zone_operations/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/zone_operations/transports/rest.py index d3810bef050f..d156bf23bbbd 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/zone_operations/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/zone_operations/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -138,10 +139,14 @@ def delete( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.delete(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.delete(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.DeleteZoneOperationResponse.from_json( @@ -218,10 +223,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) @@ -277,10 +286,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.OperationList.from_json( @@ -357,10 +370,14 @@ def wait( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.post(url,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.post(url, headers=headers,) + + # 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 return compute.Operation.from_json(response.content, ignore_unknown_fields=True) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/zones/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/zones/client.py index 9e8f5ffb9bf4..7305b0a98115 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/zones/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/zones/client.py @@ -48,7 +48,7 @@ class ZonesClientMeta(type): _transport_registry["rest"] = ZonesRestTransport def get_transport_class(cls, label: str = None,) -> Type[ZonesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -71,7 +71,8 @@ class ZonesClient(metaclass=ZonesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -105,7 +106,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -122,7 +124,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,16 +143,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ZonesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - ZonesTransport: The transport used by the client instance. + ZonesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -163,7 +166,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -174,7 +177,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -185,7 +188,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -196,7 +199,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -215,7 +218,7 @@ def __init__( client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the zones client. + """Instantiates the zones client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -270,9 +273,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -284,12 +288,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -304,8 +310,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/zones/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/zones/transports/base.py index c2e20fd177d6..e9a50e5f13e3 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/zones/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/zones/transports/base.py @@ -17,6 +17,7 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Union import packaging.version import pkg_resources +from requests import __version__ as requests_version import google.auth # type: ignore import google.api_core # type: ignore @@ -30,6 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, + grpc_version=None, + rest_version=requests_version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class ZonesTransport(abc.ABC): """Abstract transport class for Zones.""" @@ -120,10 +121,9 @@ def __init__( # Save the credentials. self._credentials = credentials - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -144,27 +144,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/zones/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/zones/transports/rest.py index e5d35f7f662e..955c583f0fb6 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/zones/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/zones/transports/rest.py @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import gapic_v1 # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -138,10 +139,14 @@ def get( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + # 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 return compute.Zone.from_json(response.content, ignore_unknown_fields=True) @@ -194,10 +199,14 @@ def list( url += "?{}".format("&".join(query_params)).replace(" ", "+") # Send the request - response = self._session.get(url,) - - # Raise requests.exceptions.HTTPError if the status code is >= 400 - response.raise_for_status() + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = self._session.get(url, headers=headers,) + + # 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 return compute.ZoneList.from_json(response.content, ignore_unknown_fields=True) 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 2e2e4277bdb2..5c242757f417 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 @@ -24,6 +24,7 @@ AcceleratorTypesScopedList, AccessConfig, AddAccessConfigInstanceRequest, + AddAssociationFirewallPolicyRequest, AddHealthCheckTargetPoolRequest, AddInstancesInstanceGroupRequest, AddInstanceTargetPoolRequest, @@ -36,9 +37,11 @@ AddressAggregatedList, AddressesScopedList, AddressList, + AddRuleFirewallPolicyRequest, AddRuleSecurityPolicyRequest, AddSignedUrlKeyBackendBucketRequest, AddSignedUrlKeyBackendServiceRequest, + AdvancedMachineFeatures, AggregatedListAcceleratorTypesRequest, AggregatedListAddressesRequest, AggregatedListAutoscalersRequest, @@ -58,6 +61,7 @@ AggregatedListNodeTemplatesRequest, AggregatedListNodeTypesRequest, AggregatedListPacketMirroringsRequest, + AggregatedListPublicDelegatedPrefixesRequest, AggregatedListRegionCommitmentsRequest, AggregatedListReservationsRequest, AggregatedListResourcePoliciesRequest, @@ -97,13 +101,18 @@ AutoscalingPolicyCustomMetricUtilization, AutoscalingPolicyLoadBalancingUtilization, AutoscalingPolicyScaleInControl, + AutoscalingPolicyScalingSchedule, Backend, BackendBucket, BackendBucketCdnPolicy, + BackendBucketCdnPolicyBypassCacheOnRequestHeader, + BackendBucketCdnPolicyNegativeCachingPolicy, BackendBucketList, BackendService, BackendServiceAggregatedList, BackendServiceCdnPolicy, + BackendServiceCdnPolicyBypassCacheOnRequestHeader, + BackendServiceCdnPolicyNegativeCachingPolicy, BackendServiceFailoverPolicy, BackendServiceGroupHealth, BackendServiceIAP, @@ -112,9 +121,14 @@ BackendServiceReference, BackendServicesScopedList, Binding, + BulkInsertInstanceRequest, + BulkInsertInstanceResource, + BulkInsertInstanceResourcePerInstanceProperties, + BulkInsertRegionInstanceRequest, CacheInvalidationRule, CacheKeyPolicy, CircuitBreakers, + CloneRulesFirewallPolicyRequest, Commitment, CommitmentAggregatedList, CommitmentList, @@ -139,6 +153,7 @@ DeleteBackendServiceRequest, DeleteDiskRequest, DeleteExternalVpnGatewayRequest, + DeleteFirewallPolicyRequest, DeleteFirewallRequest, DeleteForwardingRuleRequest, DeleteGlobalAddressRequest, @@ -148,6 +163,7 @@ DeleteGlobalOperationResponse, DeleteGlobalOrganizationOperationRequest, DeleteGlobalOrganizationOperationResponse, + DeleteGlobalPublicDelegatedPrefixeRequest, DeleteHealthCheckRequest, DeleteImageRequest, DeleteInstanceGroupManagerRequest, @@ -167,6 +183,8 @@ DeletePacketMirroringRequest, DeletePerInstanceConfigsInstanceGroupManagerRequest, DeletePerInstanceConfigsRegionInstanceGroupManagerRequest, + DeletePublicAdvertisedPrefixeRequest, + DeletePublicDelegatedPrefixeRequest, DeleteRegionAutoscalerRequest, DeleteRegionBackendServiceRequest, DeleteRegionDiskRequest, @@ -245,21 +263,33 @@ Firewall, FirewallList, FirewallLogConfig, + FirewallPoliciesListAssociationsResponse, + FirewallPolicy, + FirewallPolicyAssociation, + FirewallPolicyList, + FirewallPolicyRule, + FirewallPolicyRuleMatcher, + FirewallPolicyRuleMatcherLayer4Config, FixedOrPercent, ForwardingRule, ForwardingRuleAggregatedList, ForwardingRuleList, ForwardingRuleReference, + ForwardingRuleServiceDirectoryRegistration, ForwardingRulesScopedList, GetAcceleratorTypeRequest, GetAddressRequest, + GetAssociationFirewallPolicyRequest, GetAutoscalerRequest, GetBackendBucketRequest, GetBackendServiceRequest, GetDiagnosticsInterconnectRequest, GetDiskRequest, GetDiskTypeRequest, + GetEffectiveFirewallsInstanceRequest, + GetEffectiveFirewallsNetworkRequest, GetExternalVpnGatewayRequest, + GetFirewallPolicyRequest, GetFirewallRequest, GetForwardingRuleRequest, GetFromFamilyImageRequest, @@ -268,12 +298,14 @@ GetGlobalNetworkEndpointGroupRequest, GetGlobalOperationRequest, GetGlobalOrganizationOperationRequest, + GetGlobalPublicDelegatedPrefixeRequest, GetGuestAttributesInstanceRequest, GetHealthBackendServiceRequest, GetHealthCheckRequest, GetHealthRegionBackendServiceRequest, GetHealthTargetPoolRequest, GetIamPolicyDiskRequest, + GetIamPolicyFirewallPolicyRequest, GetIamPolicyImageRequest, GetIamPolicyInstanceRequest, GetIamPolicyInstanceTemplateRequest, @@ -304,6 +336,8 @@ GetNodeTypeRequest, GetPacketMirroringRequest, GetProjectRequest, + GetPublicAdvertisedPrefixeRequest, + GetPublicDelegatedPrefixeRequest, GetRegionAutoscalerRequest, GetRegionBackendServiceRequest, GetRegionCommitmentRequest, @@ -326,6 +360,7 @@ GetRouteRequest, GetRouterRequest, GetRouterStatusRouterRequest, + GetRuleFirewallPolicyRequest, GetRuleSecurityPolicyRequest, GetScreenshotInstanceRequest, GetSecurityPolicyRequest, @@ -353,6 +388,7 @@ GetZoneRequest, GlobalNetworkEndpointGroupsAttachEndpointsRequest, GlobalNetworkEndpointGroupsDetachEndpointsRequest, + GlobalOrganizationSetPolicyRequest, GlobalSetLabelsRequest, GlobalSetPolicyRequest, GRPCHealthCheck, @@ -396,11 +432,13 @@ InsertBackendServiceRequest, InsertDiskRequest, InsertExternalVpnGatewayRequest, + InsertFirewallPolicyRequest, InsertFirewallRequest, InsertForwardingRuleRequest, InsertGlobalAddressRequest, InsertGlobalForwardingRuleRequest, InsertGlobalNetworkEndpointGroupRequest, + InsertGlobalPublicDelegatedPrefixeRequest, InsertHealthCheckRequest, InsertImageRequest, InsertInstanceGroupManagerRequest, @@ -415,6 +453,8 @@ InsertNodeGroupRequest, InsertNodeTemplateRequest, InsertPacketMirroringRequest, + InsertPublicAdvertisedPrefixeRequest, + InsertPublicDelegatedPrefixeRequest, InsertRegionAutoscalerRequest, InsertRegionBackendServiceRequest, InsertRegionCommitmentRequest, @@ -492,6 +532,8 @@ InstanceProperties, InstanceReference, InstancesAddResourcePoliciesRequest, + InstancesGetEffectiveFirewallsResponse, + InstancesGetEffectiveFirewallsResponseEffectiveFirewallPolicy, InstancesRemoveResourcePoliciesRequest, InstancesScopedList, InstancesSetLabelsRequest, @@ -533,6 +575,7 @@ LicensesListResponse, ListAcceleratorTypesRequest, ListAddressesRequest, + ListAssociationsFirewallPolicyRequest, ListAutoscalersRequest, ListAvailableFeaturesSslPoliciesRequest, ListBackendBucketsRequest, @@ -542,6 +585,7 @@ ListErrorsInstanceGroupManagersRequest, ListErrorsRegionInstanceGroupManagersRequest, ListExternalVpnGatewaysRequest, + ListFirewallPoliciesRequest, ListFirewallsRequest, ListForwardingRulesRequest, ListGlobalAddressesRequest, @@ -549,6 +593,7 @@ ListGlobalNetworkEndpointGroupsRequest, ListGlobalOperationsRequest, ListGlobalOrganizationOperationsRequest, + ListGlobalPublicDelegatedPrefixesRequest, ListHealthChecksRequest, ListImagesRequest, ListInstanceGroupManagersRequest, @@ -577,6 +622,8 @@ ListPerInstanceConfigsInstanceGroupManagersRequest, ListPerInstanceConfigsRegionInstanceGroupManagersRequest, ListPreconfiguredExpressionSetsSecurityPoliciesRequest, + ListPublicAdvertisedPrefixesRequest, + ListPublicDelegatedPrefixesRequest, ListReferrersInstancesRequest, ListRegionAutoscalersRequest, ListRegionBackendServicesRequest, @@ -620,6 +667,8 @@ ListZoneOperationsRequest, ListZonesRequest, LocalDisk, + LocationPolicy, + LocationPolicyLocation, LogConfig, LogConfigCloudAuditOptions, LogConfigCounterOptions, @@ -637,6 +686,7 @@ MetadataFilter, MetadataFilterLabelMatch, MoveDiskProjectRequest, + MoveFirewallPolicyRequest, MoveInstanceProjectRequest, NamedPort, Network, @@ -658,6 +708,8 @@ NetworkPeering, NetworkRoutingConfig, NetworksAddPeeringRequest, + NetworksGetEffectiveFirewallsResponse, + NetworksGetEffectiveFirewallsResponseEffectiveFirewallPolicy, NetworksRemovePeeringRequest, NetworksUpdatePeeringRequest, NodeGroup, @@ -701,9 +753,11 @@ PatchAutoscalerRequest, PatchBackendBucketRequest, PatchBackendServiceRequest, + PatchFirewallPolicyRequest, PatchFirewallRequest, PatchForwardingRuleRequest, PatchGlobalForwardingRuleRequest, + PatchGlobalPublicDelegatedPrefixeRequest, PatchHealthCheckRequest, PatchImageRequest, PatchInstanceGroupManagerRequest, @@ -714,6 +768,8 @@ PatchPacketMirroringRequest, PatchPerInstanceConfigsInstanceGroupManagerRequest, PatchPerInstanceConfigsRegionInstanceGroupManagerRequest, + PatchPublicAdvertisedPrefixeRequest, + PatchPublicDelegatedPrefixeRequest, PatchRegionAutoscalerRequest, PatchRegionBackendServiceRequest, PatchRegionHealthCheckRequest, @@ -721,12 +777,14 @@ PatchRegionInstanceGroupManagerRequest, PatchRegionUrlMapRequest, PatchRouterRequest, + PatchRuleFirewallPolicyRequest, PatchRuleSecurityPolicyRequest, PatchSecurityPolicyRequest, PatchSslPolicyRequest, PatchSubnetworkRequest, PatchTargetGrpcProxyRequest, PatchTargetHttpProxyRequest, + PatchTargetHttpsProxyRequest, PatchUrlMapRequest, PathMatcher, PathRule, @@ -742,6 +800,14 @@ ProjectsGetXpnResources, ProjectsListXpnHostsRequest, ProjectsSetDefaultNetworkTierRequest, + PublicAdvertisedPrefix, + PublicAdvertisedPrefixList, + PublicAdvertisedPrefixPublicDelegatedPrefix, + PublicDelegatedPrefix, + PublicDelegatedPrefixAggregatedList, + PublicDelegatedPrefixesScopedList, + PublicDelegatedPrefixList, + PublicDelegatedPrefixPublicDelegatedSubPrefix, Quota, RawDisk, RecreateInstancesInstanceGroupManagerRequest, @@ -776,6 +842,7 @@ RegionSetPolicyRequest, RegionTargetHttpsProxiesSetSslCertificatesRequest, RegionUrlMapsValidateRequest, + RemoveAssociationFirewallPolicyRequest, RemoveHealthCheckTargetPoolRequest, RemoveInstancesInstanceGroupRequest, RemoveInstanceTargetPoolRequest, @@ -783,6 +850,7 @@ RemoveResourcePoliciesDiskRequest, RemoveResourcePoliciesInstanceRequest, RemoveResourcePoliciesRegionDiskRequest, + RemoveRuleFirewallPolicyRequest, RemoveRuleSecurityPolicyRequest, RequestMirrorPolicy, Reservation, @@ -805,7 +873,11 @@ ResourcePolicyDailyCycle, ResourcePolicyGroupPlacementPolicy, ResourcePolicyHourlyCycle, + ResourcePolicyInstanceSchedulePolicy, + ResourcePolicyInstanceSchedulePolicySchedule, ResourcePolicyList, + ResourcePolicyResourceStatus, + ResourcePolicyResourceStatusInstanceSchedulePolicyStatus, ResourcePolicySnapshotSchedulePolicy, ResourcePolicySnapshotSchedulePolicyRetentionPolicy, ResourcePolicySnapshotSchedulePolicySchedule, @@ -831,6 +903,7 @@ RouterStatusNatStatus, RouterStatusResponse, Rule, + ScalingScheduleStatus, Scheduling, SchedulingNodeAffinity, ScratchDisks, @@ -855,6 +928,7 @@ SetDeletionProtectionInstanceRequest, SetDiskAutoDeleteInstanceRequest, SetIamPolicyDiskRequest, + SetIamPolicyFirewallPolicyRequest, SetIamPolicyImageRequest, SetIamPolicyInstanceRequest, SetIamPolicyInstanceTemplateRequest, @@ -870,6 +944,8 @@ SetInstanceTemplateRegionInstanceGroupManagerRequest, SetLabelsDiskRequest, SetLabelsExternalVpnGatewayRequest, + SetLabelsForwardingRuleRequest, + SetLabelsGlobalForwardingRuleRequest, SetLabelsImageRequest, SetLabelsInstanceRequest, SetLabelsRegionDiskRequest, @@ -984,6 +1060,7 @@ TestFailure, TestIamPermissionsDiskRequest, TestIamPermissionsExternalVpnGatewayRequest, + TestIamPermissionsFirewallPolicyRequest, TestIamPermissionsImageRequest, TestIamPermissionsInstanceRequest, TestIamPermissionsInstanceTemplateRequest, @@ -1028,6 +1105,7 @@ UrlMapsValidateRequest, UrlMapsValidateResponse, UrlMapTest, + UrlMapTestHeader, UrlMapValidationResult, UrlRewrite, UsableSubnetwork, @@ -1080,6 +1158,7 @@ "AcceleratorTypesScopedList", "AccessConfig", "AddAccessConfigInstanceRequest", + "AddAssociationFirewallPolicyRequest", "AddHealthCheckTargetPoolRequest", "AddInstancesInstanceGroupRequest", "AddInstanceTargetPoolRequest", @@ -1092,9 +1171,11 @@ "AddressAggregatedList", "AddressesScopedList", "AddressList", + "AddRuleFirewallPolicyRequest", "AddRuleSecurityPolicyRequest", "AddSignedUrlKeyBackendBucketRequest", "AddSignedUrlKeyBackendServiceRequest", + "AdvancedMachineFeatures", "AggregatedListAcceleratorTypesRequest", "AggregatedListAddressesRequest", "AggregatedListAutoscalersRequest", @@ -1114,6 +1195,7 @@ "AggregatedListNodeTemplatesRequest", "AggregatedListNodeTypesRequest", "AggregatedListPacketMirroringsRequest", + "AggregatedListPublicDelegatedPrefixesRequest", "AggregatedListRegionCommitmentsRequest", "AggregatedListReservationsRequest", "AggregatedListResourcePoliciesRequest", @@ -1153,13 +1235,18 @@ "AutoscalingPolicyCustomMetricUtilization", "AutoscalingPolicyLoadBalancingUtilization", "AutoscalingPolicyScaleInControl", + "AutoscalingPolicyScalingSchedule", "Backend", "BackendBucket", "BackendBucketCdnPolicy", + "BackendBucketCdnPolicyBypassCacheOnRequestHeader", + "BackendBucketCdnPolicyNegativeCachingPolicy", "BackendBucketList", "BackendService", "BackendServiceAggregatedList", "BackendServiceCdnPolicy", + "BackendServiceCdnPolicyBypassCacheOnRequestHeader", + "BackendServiceCdnPolicyNegativeCachingPolicy", "BackendServiceFailoverPolicy", "BackendServiceGroupHealth", "BackendServiceIAP", @@ -1168,9 +1255,14 @@ "BackendServiceReference", "BackendServicesScopedList", "Binding", + "BulkInsertInstanceRequest", + "BulkInsertInstanceResource", + "BulkInsertInstanceResourcePerInstanceProperties", + "BulkInsertRegionInstanceRequest", "CacheInvalidationRule", "CacheKeyPolicy", "CircuitBreakers", + "CloneRulesFirewallPolicyRequest", "Commitment", "CommitmentAggregatedList", "CommitmentList", @@ -1195,6 +1287,7 @@ "DeleteBackendServiceRequest", "DeleteDiskRequest", "DeleteExternalVpnGatewayRequest", + "DeleteFirewallPolicyRequest", "DeleteFirewallRequest", "DeleteForwardingRuleRequest", "DeleteGlobalAddressRequest", @@ -1204,6 +1297,7 @@ "DeleteGlobalOperationResponse", "DeleteGlobalOrganizationOperationRequest", "DeleteGlobalOrganizationOperationResponse", + "DeleteGlobalPublicDelegatedPrefixeRequest", "DeleteHealthCheckRequest", "DeleteImageRequest", "DeleteInstanceGroupManagerRequest", @@ -1223,6 +1317,8 @@ "DeletePacketMirroringRequest", "DeletePerInstanceConfigsInstanceGroupManagerRequest", "DeletePerInstanceConfigsRegionInstanceGroupManagerRequest", + "DeletePublicAdvertisedPrefixeRequest", + "DeletePublicDelegatedPrefixeRequest", "DeleteRegionAutoscalerRequest", "DeleteRegionBackendServiceRequest", "DeleteRegionDiskRequest", @@ -1301,21 +1397,33 @@ "Firewall", "FirewallList", "FirewallLogConfig", + "FirewallPoliciesListAssociationsResponse", + "FirewallPolicy", + "FirewallPolicyAssociation", + "FirewallPolicyList", + "FirewallPolicyRule", + "FirewallPolicyRuleMatcher", + "FirewallPolicyRuleMatcherLayer4Config", "FixedOrPercent", "ForwardingRule", "ForwardingRuleAggregatedList", "ForwardingRuleList", "ForwardingRuleReference", + "ForwardingRuleServiceDirectoryRegistration", "ForwardingRulesScopedList", "GetAcceleratorTypeRequest", "GetAddressRequest", + "GetAssociationFirewallPolicyRequest", "GetAutoscalerRequest", "GetBackendBucketRequest", "GetBackendServiceRequest", "GetDiagnosticsInterconnectRequest", "GetDiskRequest", "GetDiskTypeRequest", + "GetEffectiveFirewallsInstanceRequest", + "GetEffectiveFirewallsNetworkRequest", "GetExternalVpnGatewayRequest", + "GetFirewallPolicyRequest", "GetFirewallRequest", "GetForwardingRuleRequest", "GetFromFamilyImageRequest", @@ -1324,12 +1432,14 @@ "GetGlobalNetworkEndpointGroupRequest", "GetGlobalOperationRequest", "GetGlobalOrganizationOperationRequest", + "GetGlobalPublicDelegatedPrefixeRequest", "GetGuestAttributesInstanceRequest", "GetHealthBackendServiceRequest", "GetHealthCheckRequest", "GetHealthRegionBackendServiceRequest", "GetHealthTargetPoolRequest", "GetIamPolicyDiskRequest", + "GetIamPolicyFirewallPolicyRequest", "GetIamPolicyImageRequest", "GetIamPolicyInstanceRequest", "GetIamPolicyInstanceTemplateRequest", @@ -1360,6 +1470,8 @@ "GetNodeTypeRequest", "GetPacketMirroringRequest", "GetProjectRequest", + "GetPublicAdvertisedPrefixeRequest", + "GetPublicDelegatedPrefixeRequest", "GetRegionAutoscalerRequest", "GetRegionBackendServiceRequest", "GetRegionCommitmentRequest", @@ -1382,6 +1494,7 @@ "GetRouteRequest", "GetRouterRequest", "GetRouterStatusRouterRequest", + "GetRuleFirewallPolicyRequest", "GetRuleSecurityPolicyRequest", "GetScreenshotInstanceRequest", "GetSecurityPolicyRequest", @@ -1409,6 +1522,7 @@ "GetZoneRequest", "GlobalNetworkEndpointGroupsAttachEndpointsRequest", "GlobalNetworkEndpointGroupsDetachEndpointsRequest", + "GlobalOrganizationSetPolicyRequest", "GlobalSetLabelsRequest", "GlobalSetPolicyRequest", "GRPCHealthCheck", @@ -1452,11 +1566,13 @@ "InsertBackendServiceRequest", "InsertDiskRequest", "InsertExternalVpnGatewayRequest", + "InsertFirewallPolicyRequest", "InsertFirewallRequest", "InsertForwardingRuleRequest", "InsertGlobalAddressRequest", "InsertGlobalForwardingRuleRequest", "InsertGlobalNetworkEndpointGroupRequest", + "InsertGlobalPublicDelegatedPrefixeRequest", "InsertHealthCheckRequest", "InsertImageRequest", "InsertInstanceGroupManagerRequest", @@ -1471,6 +1587,8 @@ "InsertNodeGroupRequest", "InsertNodeTemplateRequest", "InsertPacketMirroringRequest", + "InsertPublicAdvertisedPrefixeRequest", + "InsertPublicDelegatedPrefixeRequest", "InsertRegionAutoscalerRequest", "InsertRegionBackendServiceRequest", "InsertRegionCommitmentRequest", @@ -1548,6 +1666,8 @@ "InstanceProperties", "InstanceReference", "InstancesAddResourcePoliciesRequest", + "InstancesGetEffectiveFirewallsResponse", + "InstancesGetEffectiveFirewallsResponseEffectiveFirewallPolicy", "InstancesRemoveResourcePoliciesRequest", "InstancesScopedList", "InstancesSetLabelsRequest", @@ -1589,6 +1709,7 @@ "LicensesListResponse", "ListAcceleratorTypesRequest", "ListAddressesRequest", + "ListAssociationsFirewallPolicyRequest", "ListAutoscalersRequest", "ListAvailableFeaturesSslPoliciesRequest", "ListBackendBucketsRequest", @@ -1598,6 +1719,7 @@ "ListErrorsInstanceGroupManagersRequest", "ListErrorsRegionInstanceGroupManagersRequest", "ListExternalVpnGatewaysRequest", + "ListFirewallPoliciesRequest", "ListFirewallsRequest", "ListForwardingRulesRequest", "ListGlobalAddressesRequest", @@ -1605,6 +1727,7 @@ "ListGlobalNetworkEndpointGroupsRequest", "ListGlobalOperationsRequest", "ListGlobalOrganizationOperationsRequest", + "ListGlobalPublicDelegatedPrefixesRequest", "ListHealthChecksRequest", "ListImagesRequest", "ListInstanceGroupManagersRequest", @@ -1633,6 +1756,8 @@ "ListPerInstanceConfigsInstanceGroupManagersRequest", "ListPerInstanceConfigsRegionInstanceGroupManagersRequest", "ListPreconfiguredExpressionSetsSecurityPoliciesRequest", + "ListPublicAdvertisedPrefixesRequest", + "ListPublicDelegatedPrefixesRequest", "ListReferrersInstancesRequest", "ListRegionAutoscalersRequest", "ListRegionBackendServicesRequest", @@ -1676,6 +1801,8 @@ "ListZoneOperationsRequest", "ListZonesRequest", "LocalDisk", + "LocationPolicy", + "LocationPolicyLocation", "LogConfig", "LogConfigCloudAuditOptions", "LogConfigCounterOptions", @@ -1693,6 +1820,7 @@ "MetadataFilter", "MetadataFilterLabelMatch", "MoveDiskProjectRequest", + "MoveFirewallPolicyRequest", "MoveInstanceProjectRequest", "NamedPort", "Network", @@ -1714,6 +1842,8 @@ "NetworkPeering", "NetworkRoutingConfig", "NetworksAddPeeringRequest", + "NetworksGetEffectiveFirewallsResponse", + "NetworksGetEffectiveFirewallsResponseEffectiveFirewallPolicy", "NetworksRemovePeeringRequest", "NetworksUpdatePeeringRequest", "NodeGroup", @@ -1757,9 +1887,11 @@ "PatchAutoscalerRequest", "PatchBackendBucketRequest", "PatchBackendServiceRequest", + "PatchFirewallPolicyRequest", "PatchFirewallRequest", "PatchForwardingRuleRequest", "PatchGlobalForwardingRuleRequest", + "PatchGlobalPublicDelegatedPrefixeRequest", "PatchHealthCheckRequest", "PatchImageRequest", "PatchInstanceGroupManagerRequest", @@ -1770,6 +1902,8 @@ "PatchPacketMirroringRequest", "PatchPerInstanceConfigsInstanceGroupManagerRequest", "PatchPerInstanceConfigsRegionInstanceGroupManagerRequest", + "PatchPublicAdvertisedPrefixeRequest", + "PatchPublicDelegatedPrefixeRequest", "PatchRegionAutoscalerRequest", "PatchRegionBackendServiceRequest", "PatchRegionHealthCheckRequest", @@ -1777,12 +1911,14 @@ "PatchRegionInstanceGroupManagerRequest", "PatchRegionUrlMapRequest", "PatchRouterRequest", + "PatchRuleFirewallPolicyRequest", "PatchRuleSecurityPolicyRequest", "PatchSecurityPolicyRequest", "PatchSslPolicyRequest", "PatchSubnetworkRequest", "PatchTargetGrpcProxyRequest", "PatchTargetHttpProxyRequest", + "PatchTargetHttpsProxyRequest", "PatchUrlMapRequest", "PathMatcher", "PathRule", @@ -1798,6 +1934,14 @@ "ProjectsGetXpnResources", "ProjectsListXpnHostsRequest", "ProjectsSetDefaultNetworkTierRequest", + "PublicAdvertisedPrefix", + "PublicAdvertisedPrefixList", + "PublicAdvertisedPrefixPublicDelegatedPrefix", + "PublicDelegatedPrefix", + "PublicDelegatedPrefixAggregatedList", + "PublicDelegatedPrefixesScopedList", + "PublicDelegatedPrefixList", + "PublicDelegatedPrefixPublicDelegatedSubPrefix", "Quota", "RawDisk", "RecreateInstancesInstanceGroupManagerRequest", @@ -1832,6 +1976,7 @@ "RegionSetPolicyRequest", "RegionTargetHttpsProxiesSetSslCertificatesRequest", "RegionUrlMapsValidateRequest", + "RemoveAssociationFirewallPolicyRequest", "RemoveHealthCheckTargetPoolRequest", "RemoveInstancesInstanceGroupRequest", "RemoveInstanceTargetPoolRequest", @@ -1839,6 +1984,7 @@ "RemoveResourcePoliciesDiskRequest", "RemoveResourcePoliciesInstanceRequest", "RemoveResourcePoliciesRegionDiskRequest", + "RemoveRuleFirewallPolicyRequest", "RemoveRuleSecurityPolicyRequest", "RequestMirrorPolicy", "Reservation", @@ -1861,7 +2007,11 @@ "ResourcePolicyDailyCycle", "ResourcePolicyGroupPlacementPolicy", "ResourcePolicyHourlyCycle", + "ResourcePolicyInstanceSchedulePolicy", + "ResourcePolicyInstanceSchedulePolicySchedule", "ResourcePolicyList", + "ResourcePolicyResourceStatus", + "ResourcePolicyResourceStatusInstanceSchedulePolicyStatus", "ResourcePolicySnapshotSchedulePolicy", "ResourcePolicySnapshotSchedulePolicyRetentionPolicy", "ResourcePolicySnapshotSchedulePolicySchedule", @@ -1887,6 +2037,7 @@ "RouterStatusNatStatus", "RouterStatusResponse", "Rule", + "ScalingScheduleStatus", "Scheduling", "SchedulingNodeAffinity", "ScratchDisks", @@ -1911,6 +2062,7 @@ "SetDeletionProtectionInstanceRequest", "SetDiskAutoDeleteInstanceRequest", "SetIamPolicyDiskRequest", + "SetIamPolicyFirewallPolicyRequest", "SetIamPolicyImageRequest", "SetIamPolicyInstanceRequest", "SetIamPolicyInstanceTemplateRequest", @@ -1926,6 +2078,8 @@ "SetInstanceTemplateRegionInstanceGroupManagerRequest", "SetLabelsDiskRequest", "SetLabelsExternalVpnGatewayRequest", + "SetLabelsForwardingRuleRequest", + "SetLabelsGlobalForwardingRuleRequest", "SetLabelsImageRequest", "SetLabelsInstanceRequest", "SetLabelsRegionDiskRequest", @@ -2040,6 +2194,7 @@ "TestFailure", "TestIamPermissionsDiskRequest", "TestIamPermissionsExternalVpnGatewayRequest", + "TestIamPermissionsFirewallPolicyRequest", "TestIamPermissionsImageRequest", "TestIamPermissionsInstanceRequest", "TestIamPermissionsInstanceTemplateRequest", @@ -2084,6 +2239,7 @@ "UrlMapsValidateRequest", "UrlMapsValidateResponse", "UrlMapTest", + "UrlMapTestHeader", "UrlMapValidationResult", "UrlRewrite", "UsableSubnetwork", 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 28acaec38e95..182ce63aebd1 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 @@ -32,6 +32,7 @@ "AddressesScopedList", "AddressAggregatedList", "AddressList", + "AdvancedMachineFeatures", "AliasIpRange", "AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk", "AllocationSpecificSKUAllocationReservedInstanceProperties", @@ -45,6 +46,7 @@ "AuditConfig", "AuthorizationLoggingOptions", "AutoscalingPolicy", + "ScalingScheduleStatus", "AutoscalerStatusDetails", "Autoscaler", "AutoscalersScopedList", @@ -54,10 +56,13 @@ "AutoscalingPolicyCustomMetricUtilization", "AutoscalingPolicyLoadBalancingUtilization", "AutoscalingPolicyScaleInControl", + "AutoscalingPolicyScalingSchedule", "FixedOrPercent", "Backend", "BackendBucketCdnPolicy", "BackendBucket", + "BackendBucketCdnPolicyBypassCacheOnRequestHeader", + "BackendBucketCdnPolicyNegativeCachingPolicy", "BackendBucketList", "BackendServiceCdnPolicy", "CircuitBreakers", @@ -66,18 +71,25 @@ "BackendServiceFailoverPolicy", "BackendServiceIAP", "BackendServiceLogConfig", + "Duration", "OutlierDetection", "SecuritySettings", "BackendService", "BackendServicesScopedList", "BackendServiceAggregatedList", + "BackendServiceCdnPolicyBypassCacheOnRequestHeader", "CacheKeyPolicy", + "BackendServiceCdnPolicyNegativeCachingPolicy", "HealthStatus", "BackendServiceGroupHealth", "BackendServiceList", "BackendServiceReference", "Expr", "Binding", + "InstanceProperties", + "LocationPolicy", + "BulkInsertInstanceResourcePerInstanceProperties", + "BulkInsertInstanceResource", "CacheInvalidationRule", "LicenseResourceCommitment", "Reservation", @@ -89,7 +101,6 @@ "Condition", "ConfidentialInstanceConfig", "ConsistentHashLoadBalancerSettingsHttpCookie", - "Duration", "CorsPolicy", "CustomerEncryptionKeyProtectedDisk", "Disk", @@ -119,7 +130,15 @@ "FirewallLogConfig", "Firewall", "FirewallList", + "FirewallPolicyAssociation", + "FirewallPoliciesListAssociationsResponse", + "FirewallPolicyRule", + "FirewallPolicy", + "FirewallPolicyList", + "FirewallPolicyRuleMatcher", + "FirewallPolicyRuleMatcherLayer4Config", "MetadataFilter", + "ForwardingRuleServiceDirectoryRegistration", "ForwardingRule", "ForwardingRulesScopedList", "ForwardingRuleAggregatedList", @@ -129,8 +148,9 @@ "NetworkEndpoint", "GlobalNetworkEndpointGroupsAttachEndpointsRequest", "GlobalNetworkEndpointGroupsDetachEndpointsRequest", - "GlobalSetLabelsRequest", "Policy", + "GlobalOrganizationSetPolicyRequest", + "GlobalSetLabelsRequest", "GlobalSetPolicyRequest", "GuestAttributesValue", "GuestAttributes", @@ -229,11 +249,12 @@ "InstanceManagedByIgmErrorInstanceActionDetails", "ManagedInstanceVersion", "InstanceMoveRequest", - "InstanceProperties", "SourceInstanceParams", "InstanceTemplate", "InstanceTemplateList", "InstancesAddResourcePoliciesRequest", + "InstancesGetEffectiveFirewallsResponseEffectiveFirewallPolicy", + "InstancesGetEffectiveFirewallsResponse", "InstancesRemoveResourcePoliciesRequest", "InstancesSetLabelsRequest", "InstancesSetMachineResourcesRequest", @@ -266,6 +287,7 @@ "LicenseCode", "LicensesListResponse", "LocalDisk", + "LocationPolicyLocation", "LogConfigCloudAuditOptions", "LogConfigCounterOptions", "LogConfigDataAccessOptions", @@ -300,6 +322,8 @@ "NetworkEndpointGroupsListNetworkEndpoints", "NetworkList", "NetworksAddPeeringRequest", + "NetworksGetEffectiveFirewallsResponseEffectiveFirewallPolicy", + "NetworksGetEffectiveFirewallsResponse", "NetworksRemovePeeringRequest", "NetworksUpdatePeeringRequest", "NodeGroupAutoscalingPolicy", @@ -357,6 +381,14 @@ "ProjectsGetXpnResources", "ProjectsListXpnHostsRequest", "ProjectsSetDefaultNetworkTierRequest", + "PublicAdvertisedPrefixPublicDelegatedPrefix", + "PublicAdvertisedPrefix", + "PublicAdvertisedPrefixList", + "PublicDelegatedPrefixPublicDelegatedSubPrefix", + "PublicDelegatedPrefix", + "PublicDelegatedPrefixesScopedList", + "PublicDelegatedPrefixAggregatedList", + "PublicDelegatedPrefixList", "Region", "RegionAutoscalerList", "RegionDiskTypeList", @@ -395,11 +427,15 @@ "ResourcePolicy", "ResourcePoliciesScopedList", "ResourcePolicyGroupPlacementPolicy", + "ResourcePolicyInstanceSchedulePolicy", + "ResourcePolicyResourceStatus", "ResourcePolicySnapshotSchedulePolicy", "ResourcePolicyAggregatedList", "ResourcePolicyDailyCycle", "ResourcePolicyHourlyCycle", + "ResourcePolicyInstanceSchedulePolicySchedule", "ResourcePolicyList", + "ResourcePolicyResourceStatusInstanceSchedulePolicyStatus", "ResourcePolicySnapshotSchedulePolicyRetentionPolicy", "ResourcePolicySnapshotSchedulePolicySchedule", "ResourcePolicySnapshotSchedulePolicySnapshotProperties", @@ -498,6 +534,7 @@ "TargetVpnGatewaysScopedList", "TargetVpnGatewayAggregatedList", "TargetVpnGatewayList", + "UrlMapTestHeader", "TestFailure", "TestPermissionsRequest", "TestPermissionsResponse", @@ -591,6 +628,24 @@ "ListExternalVpnGatewaysRequest", "SetLabelsExternalVpnGatewayRequest", "TestIamPermissionsExternalVpnGatewayRequest", + "AddAssociationFirewallPolicyRequest", + "AddRuleFirewallPolicyRequest", + "CloneRulesFirewallPolicyRequest", + "DeleteFirewallPolicyRequest", + "GetFirewallPolicyRequest", + "GetAssociationFirewallPolicyRequest", + "GetIamPolicyFirewallPolicyRequest", + "GetRuleFirewallPolicyRequest", + "InsertFirewallPolicyRequest", + "ListFirewallPoliciesRequest", + "ListAssociationsFirewallPolicyRequest", + "MoveFirewallPolicyRequest", + "PatchFirewallPolicyRequest", + "PatchRuleFirewallPolicyRequest", + "RemoveAssociationFirewallPolicyRequest", + "RemoveRuleFirewallPolicyRequest", + "SetIamPolicyFirewallPolicyRequest", + "TestIamPermissionsFirewallPolicyRequest", "DeleteFirewallRequest", "GetFirewallRequest", "InsertFirewallRequest", @@ -603,6 +658,7 @@ "InsertForwardingRuleRequest", "ListForwardingRulesRequest", "PatchForwardingRuleRequest", + "SetLabelsForwardingRuleRequest", "SetTargetForwardingRuleRequest", "DeleteGlobalAddressRequest", "GetGlobalAddressRequest", @@ -613,6 +669,7 @@ "InsertGlobalForwardingRuleRequest", "ListGlobalForwardingRulesRequest", "PatchGlobalForwardingRuleRequest", + "SetLabelsGlobalForwardingRuleRequest", "SetTargetGlobalForwardingRuleRequest", "AttachNetworkEndpointsGlobalNetworkEndpointGroupRequest", "DeleteGlobalNetworkEndpointGroupRequest", @@ -631,6 +688,11 @@ "DeleteGlobalOrganizationOperationResponse", "GetGlobalOrganizationOperationRequest", "ListGlobalOrganizationOperationsRequest", + "DeleteGlobalPublicDelegatedPrefixeRequest", + "GetGlobalPublicDelegatedPrefixeRequest", + "InsertGlobalPublicDelegatedPrefixeRequest", + "ListGlobalPublicDelegatedPrefixesRequest", + "PatchGlobalPublicDelegatedPrefixeRequest", "AggregatedListHealthChecksRequest", "DeleteHealthCheckRequest", "GetHealthCheckRequest", @@ -689,10 +751,12 @@ "AddResourcePoliciesInstanceRequest", "AggregatedListInstancesRequest", "AttachDiskInstanceRequest", + "BulkInsertInstanceRequest", "DeleteInstanceRequest", "DeleteAccessConfigInstanceRequest", "DetachDiskInstanceRequest", "GetInstanceRequest", + "GetEffectiveFirewallsInstanceRequest", "GetGuestAttributesInstanceRequest", "GetIamPolicyInstanceRequest", "GetScreenshotInstanceRequest", @@ -763,6 +827,7 @@ "AddPeeringNetworkRequest", "DeleteNetworkRequest", "GetNetworkRequest", + "GetEffectiveFirewallsNetworkRequest", "InsertNetworkRequest", "ListNetworksRequest", "ListPeeringRoutesNetworksRequest", @@ -814,6 +879,17 @@ "SetCommonInstanceMetadataProjectRequest", "SetDefaultNetworkTierProjectRequest", "SetUsageExportBucketProjectRequest", + "DeletePublicAdvertisedPrefixeRequest", + "GetPublicAdvertisedPrefixeRequest", + "InsertPublicAdvertisedPrefixeRequest", + "ListPublicAdvertisedPrefixesRequest", + "PatchPublicAdvertisedPrefixeRequest", + "AggregatedListPublicDelegatedPrefixesRequest", + "DeletePublicDelegatedPrefixeRequest", + "GetPublicDelegatedPrefixeRequest", + "InsertPublicDelegatedPrefixeRequest", + "ListPublicDelegatedPrefixesRequest", + "PatchPublicDelegatedPrefixeRequest", "DeleteRegionAutoscalerRequest", "GetRegionAutoscalerRequest", "InsertRegionAutoscalerRequest", @@ -879,6 +955,7 @@ "ListRegionInstanceGroupsRequest", "ListInstancesRegionInstanceGroupsRequest", "SetNamedPortsRegionInstanceGroupRequest", + "BulkInsertRegionInstanceRequest", "DeleteRegionNetworkEndpointGroupRequest", "GetRegionNetworkEndpointGroupRequest", "InsertRegionNetworkEndpointGroupRequest", @@ -1004,6 +1081,7 @@ "GetTargetHttpsProxyRequest", "InsertTargetHttpsProxyRequest", "ListTargetHttpsProxiesRequest", + "PatchTargetHttpsProxyRequest", "SetQuicOverrideTargetHttpsProxyRequest", "SetSslCertificatesTargetHttpsProxyRequest", "SetSslPolicyTargetHttpsProxyRequest", @@ -1550,7 +1628,7 @@ class Address(proto.Message): field is not specified, it is assumed to be PREMIUM. prefix_length (int): - The prefix length if the resource reprensents + The prefix length if the resource represents an IP range. purpose (google.cloud.compute_v1.types.Address.Purpose): The purpose of this resource, which can be one of the @@ -1567,13 +1645,13 @@ class Address(proto.Message): automatically reserved for Cloud NAT. - ``IPSEC_INTERCONNECT`` for addresses created from a private IP range that are reserved for a VLAN attachment - in an IPsec encrypted Interconnect configuration. These - addresses are regional resources. + in an IPsec-encrypted Cloud Interconnect configuration. + These addresses are regional resources. region (str): - [Output Only] The URL of the region where the regional - address resides. This field is not applicable to global - addresses. You must specify this field as part of the HTTP - request URL. + [Output Only] The URL of the region where a regional address + resides. For regional addresses, you must specify the region + as a path parameter in the HTTP request URL. This field is + not applicable to global addresses. self_link (str): [Output Only] Server-defined URL for the resource. status (google.cloud.compute_v1.types.Address.Status): @@ -1639,14 +1717,16 @@ class Purpose(proto.Enum): - ``NAT_AUTO`` for addresses that are external IP addresses automatically reserved for Cloud NAT. - ``IPSEC_INTERCONNECT`` for addresses created from a private IP - range that are reserved for a VLAN attachment in an IPsec - encrypted Interconnect configuration. These addresses are - regional resources. + range that are reserved for a VLAN attachment in an + IPsec-encrypted Cloud Interconnect configuration. These addresses + are regional resources. """ UNDEFINED_PURPOSE = 0 DNS_RESOLVER = 476114556 GCE_ENDPOINT = 230515243 + IPSEC_INTERCONNECT = 340437251 NAT_AUTO = 163666477 + PRIVATE_SERVICE_CONNECT = 48134724 SHARED_LOADBALANCER_VIP = 294447572 VPC_PEERING = 400800170 @@ -1785,6 +1865,32 @@ def raw_page(self): ) +class AdvancedMachineFeatures(proto.Message): + r"""Specifies options for controlling advanced machine features. + Options that would traditionally be configured in a BIOS belong + here. Features that require operating system support may have + corresponding entries in the GuestOsFeatures of an Image (e.g., + whether or not the OS in the Image supports nested + virtualization being enabled or disabled). + + Attributes: + enable_nested_virtualization (bool): + Whether to enable nested virtualization or + not (default is false). + threads_per_core (int): + The number of threads per physical core. To + disable simultaneous multithreading (SMT) set + this to 1. If unset, the maximum number of + threads supported per core by the underlying + processor is assumed. + """ + + enable_nested_virtualization = proto.Field( + proto.BOOL, number=16639365, optional=True, + ) + threads_per_core = proto.Field(proto.INT32, number=352611671, optional=True,) + + class AliasIpRange(proto.Message): r"""An alias IP range attached to an instance's network interface. @@ -1849,6 +1955,11 @@ class AllocationSpecificSKUAllocationReservedInstanceProperties(proto.Message): local_ssds (Sequence[google.cloud.compute_v1.types.AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk]): Specifies amount of local ssd to reserve with each instance. The type of disk is local-ssd. + location_hint (str): + An opaque location hint used to place the + allocation close to other resources. This field + is for use by internal tools that use the public + API. machine_type (str): Specifies type of machine (name only) which has fixed number of vCPUs and fixed amount of memory. This also includes @@ -1866,6 +1977,7 @@ class AllocationSpecificSKUAllocationReservedInstanceProperties(proto.Message): number=229951299, message="AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk", ) + location_hint = proto.Field(proto.STRING, number=350519505, optional=True,) machine_type = proto.Field(proto.STRING, number=227711026, optional=True,) min_cpu_platform = proto.Field(proto.STRING, number=242912759, optional=True,) @@ -2001,6 +2113,9 @@ class AttachedDiskInitializeParams(proto.Message): Specifies which action to take on instance update with this disk. Default is to use the existing disk. + provisioned_iops (str): + Indicates how many IOPS must be provisioned + for the disk. resource_policies (Sequence[str]): Resource policies applied to this disk for automatic snapshot creations. Specified using @@ -2077,6 +2192,7 @@ class OnUpdateAction(proto.Enum): on_update_action = proto.Field( proto.ENUM, number=202451980, optional=True, enum=OnUpdateAction, ) + provisioned_iops = proto.Field(proto.STRING, number=186769108, optional=True,) resource_policies = proto.RepeatedField(proto.STRING, number=22220385,) source_image = proto.Field(proto.STRING, number=50443319, optional=True,) source_image_encryption_key = proto.Field( @@ -2424,6 +2540,12 @@ class AutoscalingPolicy(proto.Message): Defines operating mode for this policy. scale_in_control (google.cloud.compute_v1.types.AutoscalingPolicyScaleInControl): + scaling_schedules (Sequence[google.cloud.compute_v1.types.AutoscalingPolicy.ScalingSchedulesEntry]): + Scaling schedules defined for an autoscaler. Multiple + schedules can be set on an autoscaler, and they can overlap. + During overlapping periods the greatest + min_required_replicas of all scaling schedules is applied. + Up to 128 scaling schedules are allowed. """ class Mode(proto.Enum): @@ -2461,6 +2583,42 @@ class Mode(proto.Enum): optional=True, message="AutoscalingPolicyScaleInControl", ) + scaling_schedules = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=355416580, + message="AutoscalingPolicyScalingSchedule", + ) + + +class ScalingScheduleStatus(proto.Message): + r""" + Attributes: + last_start_time (str): + [Output Only] The last time the scaling schedule became + active. Note: this is a timestamp when a schedule actually + became active, not when it was planned to do so. The + timestamp is in RFC3339 text format. + next_start_time (str): + [Output Only] The next time the scaling schedule is to + become active. Note: this is a timestamp when a schedule is + planned to run, but the actual time might be slightly + different. The timestamp is in RFC3339 text format. + state (google.cloud.compute_v1.types.ScalingScheduleStatus.State): + [Output Only] The current state of a scaling schedule. + """ + + class State(proto.Enum): + r"""[Output Only] The current state of a scaling schedule.""" + UNDEFINED_STATE = 0 + ACTIVE = 314733318 + DISABLED = 516696700 + OBSOLETE = 66532761 + READY = 77848963 + + last_start_time = proto.Field(proto.STRING, number=34545107, optional=True,) + next_start_time = proto.Field(proto.STRING, number=97270102, optional=True,) + state = proto.Field(proto.ENUM, number=109757585, optional=True, enum=State,) class AutoscalerStatusDetails(proto.Message): @@ -2586,6 +2744,8 @@ class Type(proto.Enum): NOT_ENOUGH_QUOTA_AVAILABLE = 403101631 REGION_RESOURCE_STOCKOUT = 528622846 SCALING_TARGET_DOES_NOT_EXIST = 122636699 + SCHEDULED_INSTANCES_GREATER_THAN_AUTOSCALER_MAX = 29275586 + SCHEDULED_INSTANCES_LESS_THAN_AUTOSCALER_MIN = 398287669 UNKNOWN = 433141802 UNSUPPORTED_MAX_RATE_LOAD_BALANCING_CONFIGURATION = 330845009 ZONE_RESOURCE_STOCKOUT = 210200502 @@ -2618,8 +2778,8 @@ class Autoscaler(proto.Message): autoscaling_policy (google.cloud.compute_v1.types.AutoscalingPolicy): The configuration parameters for the autoscaling algorithm. You can define one or - more of the policies for an autoscaler: - cpuUtilization, customMetricUtilizations, and + more signals for an autoscaler: cpuUtilization, + customMetricUtilizations, and loadBalancingUtilization. If none of these are specified, the default will be to autoscale based on cpuUtilization to 0.6 or 60%. @@ -2654,6 +2814,9 @@ class Autoscaler(proto.Message): region (str): [Output Only] URL of the region where the instance group resides (for autoscalers living in regional scope). + scaling_schedule_status (Sequence[google.cloud.compute_v1.types.Autoscaler.ScalingScheduleStatusEntry]): + [Output Only] Status information of existing scaling + schedules. self_link (str): [Output Only] Server-defined URL for the resource. status (google.cloud.compute_v1.types.Autoscaler.Status): @@ -2712,6 +2875,9 @@ class Status(proto.Enum): name = proto.Field(proto.STRING, number=3373707, optional=True,) recommended_size = proto.Field(proto.INT32, number=257915749, optional=True,) region = proto.Field(proto.STRING, number=138946292, optional=True,) + scaling_schedule_status = proto.MapField( + proto.STRING, proto.MESSAGE, number=465950178, message="ScalingScheduleStatus", + ) self_link = proto.Field(proto.STRING, number=456214797, optional=True,) status = proto.Field(proto.ENUM, number=181260274, optional=True, enum=Status,) status_details = proto.RepeatedField( @@ -2824,6 +2990,16 @@ def raw_page(self): class AutoscalingPolicyCpuUtilization(proto.Message): r"""CPU utilization policy. Attributes: + predictive_method (google.cloud.compute_v1.types.AutoscalingPolicyCpuUtilization.PredictiveMethod): + Indicates whether predictive autoscaling based on CPU metric + is enabled. Valid values are: + + - NONE (default). No predictive method is used. The + autoscaler scales the group to meet current demand based + on real-time metrics. \* OPTIMIZE_AVAILABILITY. + Predictive autoscaling improves availability by + monitoring daily and weekly load patterns and scaling out + ahead of anticipated demand. utilization_target (float): The target CPU utilization that the autoscaler maintains. Must be a float value in the range (0, 1]. If not specified, @@ -2841,6 +3017,23 @@ class AutoscalingPolicyCpuUtilization(proto.Message): reaches the target utilization. """ + class PredictiveMethod(proto.Enum): + r"""Indicates whether predictive autoscaling based on CPU metric is + enabled. Valid values are: + + - NONE (default). No predictive method is used. The autoscaler + scales the group to meet current demand based on real-time + metrics. \* OPTIMIZE_AVAILABILITY. Predictive autoscaling + improves availability by monitoring daily and weekly load + patterns and scaling out ahead of anticipated demand. + """ + UNDEFINED_PREDICTIVE_METHOD = 0 + NONE = 2402104 + OPTIMIZE_AVAILABILITY = 11629437 + + predictive_method = proto.Field( + proto.ENUM, number=390220737, optional=True, enum=PredictiveMethod, + ) utilization_target = proto.Field(proto.DOUBLE, number=215905870, optional=True,) @@ -2983,6 +3176,56 @@ class AutoscalingPolicyScaleInControl(proto.Message): time_window_sec = proto.Field(proto.INT32, number=36405300, optional=True,) +class AutoscalingPolicyScalingSchedule(proto.Message): + r"""Scaling based on user-defined schedule. The message describes + a single scaling schedule. A scaling schedule changes the + minimum number of VM instances an autoscaler can recommend, + which can trigger scaling out. + + Attributes: + description (str): + A description of a scaling schedule. + disabled (bool): + A boolean value that specifies whether a + scaling schedule can influence autoscaler + recommendations. If set to true, then a scaling + schedule has no effect. This field is optional, + and its value is false by default. + duration_sec (int): + The duration of time intervals, in seconds, + for which this scaling schedule is to run. The + minimum allowed value is 300. This field is + required. + min_required_replicas (int): + The minimum number of VM instances that the + autoscaler will recommend in time intervals + starting according to schedule. This field is + required. + schedule (str): + The start timestamps of time intervals when this scaling + schedule is to provide a scaling signal. This field uses the + extended cron format (with an optional year field). The + expression can describe a single timestamp if the optional + year is set, in which case the scaling schedule runs once. + The schedule is interpreted with respect to time_zone. This + field is required. Note: These timestamps only describe when + autoscaler starts providing the scaling signal. The VMs need + additional time to become serving. + time_zone (str): + The time zone to use when interpreting the schedule. The + value of this field must be a time zone name from the tz + database: http://en.wikipedia.org/wiki/Tz_database. This + field is assigned a default value of ?UTC? if left empty. + """ + + description = proto.Field(proto.STRING, number=422937596, optional=True,) + disabled = proto.Field(proto.BOOL, number=270940796, optional=True,) + duration_sec = proto.Field(proto.INT32, number=212356902, optional=True,) + min_required_replicas = proto.Field(proto.INT32, number=365514414, optional=True,) + schedule = proto.Field(proto.STRING, number=375820951, optional=True,) + time_zone = proto.Field(proto.STRING, number=36848094, optional=True,) + + class FixedOrPercent(proto.Message): r"""Encapsulates numeric value that can be either absolute or relative. @@ -3017,59 +3260,24 @@ class Backend(proto.Message): r"""Message containing information of one individual backend. Attributes: balancing_mode (google.cloud.compute_v1.types.Backend.BalancingMode): - Specifies the balancing mode for the backend. - - When choosing a balancing mode, you need to consider the - loadBalancingScheme, and protocol for the backend service, - as well as the type of backend (instance group or NEG). - - - If the load balancing mode is CONNECTION, then the load - is spread based on how many concurrent connections the - backend can handle. You can use the CONNECTION balancing - mode if the protocol for the backend service is SSL, TCP, - or UDP. - - If the loadBalancingScheme for the backend service is - EXTERNAL (SSL Proxy and TCP Proxy load balancers), you must - also specify exactly one of the following parameters: - maxConnections (except for regional managed instance - groups), maxConnectionsPerInstance, or - maxConnectionsPerEndpoint. - - If the loadBalancingScheme for the backend service is - INTERNAL (internal TCP/UDP Load Balancers) or EXTERNAL - (Network Load Balancing), you cannot specify any additional - parameters. - - - If the load balancing mode is RATE, the load is spread - based on the rate of HTTP requests per second (RPS). You - can use the RATE balancing mode if the protocol for the - backend service is HTTP, HTTP2, or HTTPS. You must - specify exactly one of the following parameters: maxRate - (except for regional managed instance groups), - maxRatePerInstance, or maxRatePerEndpoint. - - - If the load balancing mode is UTILIZATION, the load is - spread based on the backend utilization of instances in - an instance group. You can use the UTILIZATION balancing - mode if the loadBalancingScheme of the backend service is - EXTERNAL (except Network Load Balancing), - INTERNAL_SELF_MANAGED, or INTERNAL_MANAGED and the - backends are instance groups. There are no restrictions - on the backend service protocol. + Specifies how to determine whether the + backend of a load balancer can handle additional + traffic or is fully loaded. For usage + guidelines, see Connection balancing mode. capacity_scaler (float): - A multiplier applied to the group's maximum servicing - capacity (based on UTILIZATION, RATE or CONNECTION). Default - value is 1, which means the group will serve up to 100% of - its configured capacity (depending on balancingMode). A - setting of 0 means the group is completely drained, offering - 0% of its available capacity. Valid range is 0.0 and - [0.1,1.0]. You cannot configure a setting larger than 0 and - smaller than 0.1. You cannot configure a setting of 0 when - there is only one backend attached to the backend service. - - This cannot be used for Internal TCP/UDP Load Balancing and - Network Load Balancing. + A multiplier applied to the backend's target capacity of its + balancing mode. The default value is 1, which means the + group serves up to 100% of its configured capacity + (depending on balancingMode). A setting of 0 means the group + is completely drained, offering 0% of its available + capacity. The valid ranges are 0.0 and [0.1,1.0]. You cannot + configure a setting larger than 0 and smaller than 0.1. You + cannot configure a setting of 0 when there is only one + backend attached to the backend service. + + Not supported by: + + - Internal TCP/UDP Load Balancing - Network Load Balancing description (str): An optional description of this resource. Provide this property when you create the @@ -3105,147 +3313,54 @@ class Backend(proto.Message): or NEG. Partial URLs are not supported. max_connections (int): Defines a target maximum number of - simultaneous connections that the backend can - handle. Valid for network endpoint group and - instance group backends (except for regional - managed instance groups). If the backend's - balancingMode is UTILIZATION, this is an - optional parameter. If the backend's - balancingMode is CONNECTION, and backend is - attached to a backend service whose - loadBalancingScheme is EXTERNAL (except Network - Load Balancing), you must specify either this - parameter, maxConnectionsPerInstance, or - maxConnectionsPerEndpoint. Not available if the - backend's balancingMode is RATE. Cannot be - specified for Network Load Balancing or Internal - TCP/UDP Load Balancing, even though those load - balancers require a balancing mode of - CONNECTION. + simultaneous connections. For usage guidelines, + see Connection balancing mode and Utilization + balancing mode. Not available if the backend's + balancingMode is RATE. Not supported by: - + Internal TCP/UDP Load Balancing - Network Load + Balancing max_connections_per_endpoint (int): Defines a target maximum number of - simultaneous connections for an endpoint of a - NEG. This is multiplied by the number of - endpoints in the NEG to implicitly calculate a - maximum number of target maximum simultaneous - connections for the NEG. If the backend's - balancingMode is CONNECTION, and backend is - attached to a backend service whose - loadBalancingScheme is EXTERNAL (except Network - Load Balancing), you must specify either this - parameter, maxConnections, or - maxConnectionsPerInstance. Not available if the - backend's balancingMode is RATE. Cannot be - specified for Network Load Balancing or Internal - TCP/UDP Load Balancing, even though those load - balancers require a balancing mode of - CONNECTION. + simultaneous connections. For usage guidelines, + see Connection balancing mode and Utilization + balancing mode. Not available if the backend's + balancingMode is RATE. Not supported by: + - Internal TCP/UDP Load Balancing - Network Load + Balancing. max_connections_per_instance (int): Defines a target maximum number of - simultaneous connections for a single VM in a - backend instance group. This is multiplied by - the number of instances in the instance group to - implicitly calculate a target maximum number of - simultaneous connections for the whole instance - group. If the backend's balancingMode is - UTILIZATION, this is an optional parameter. If - the backend's balancingMode is CONNECTION, and - backend is attached to a backend service whose - loadBalancingScheme is EXTERNAL (except Network - Load Balancing), you must specify either this - parameter, maxConnections, or - maxConnectionsPerEndpoint. Not available if the - backend's balancingMode is RATE. Cannot be - specified for Network Load Balancing or Internal - TCP/UDP Load Balancing, even though those load - balancers require a balancing mode of - CONNECTION. + simultaneous connections. For usage guidelines, + see Connection balancing mode and Utilization + balancing mode. Not available if the backend's + balancingMode is RATE. Not supported by: + - Internal TCP/UDP Load Balancing - Network Load + Balancing. max_rate (int): Defines a maximum number of HTTP requests per - second (RPS) that the backend can handle. Valid - for network endpoint group and instance group - backends (except for regional managed instance - groups). Must not be defined if the backend is a - managed instance group that uses autoscaling - based on load balancing. If the backend's - balancingMode is UTILIZATION, this is an - optional parameter. If the backend's - balancingMode is RATE, you must specify maxRate, - maxRatePerInstance, or maxRatePerEndpoint. + second (RPS). For usage guidelines, see Rate + balancing mode and Utilization balancing mode. Not available if the backend's balancingMode is CONNECTION. max_rate_per_endpoint (float): Defines a maximum target for requests per - second (RPS) for an endpoint of a NEG. This is - multiplied by the number of endpoints in the NEG - to implicitly calculate a target maximum rate - for the NEG. If the backend's balancingMode is - RATE, you must specify either this parameter, - maxRate (except for regional managed instance - groups), or maxRatePerInstance. + second (RPS). For usage guidelines, see Rate + balancing mode and Utilization balancing mode. Not available if the backend's balancingMode is CONNECTION. max_rate_per_instance (float): Defines a maximum target for requests per - second (RPS) for a single VM in a backend - instance group. This is multiplied by the number - of instances in the instance group to implicitly - calculate a target maximum rate for the whole - instance group. If the backend's balancingMode - is UTILIZATION, this is an optional parameter. - If the backend's balancingMode is RATE, you must - specify either this parameter, maxRate (except - for regional managed instance groups), or - maxRatePerEndpoint. + second (RPS). For usage guidelines, see Rate + balancing mode and Utilization balancing mode. Not available if the backend's balancingMode is CONNECTION. max_utilization (float): - Defines the maximum average backend utilization of a backend - VM in an instance group. The valid range is [0.0, 1.0]. This - is an optional parameter if the backend's balancingMode is - UTILIZATION. - This parameter can be used in conjunction with maxRate, - maxRatePerInstance, maxConnections (except for regional - managed instance groups), or maxConnectionsPerInstance. """ class BalancingMode(proto.Enum): - r"""Specifies the balancing mode for the backend. - - When choosing a balancing mode, you need to consider the - loadBalancingScheme, and protocol for the backend service, as well - as the type of backend (instance group or NEG). - - - If the load balancing mode is CONNECTION, then the load is spread - based on how many concurrent connections the backend can handle. - You can use the CONNECTION balancing mode if the protocol for the - backend service is SSL, TCP, or UDP. - - If the loadBalancingScheme for the backend service is EXTERNAL (SSL - Proxy and TCP Proxy load balancers), you must also specify exactly - one of the following parameters: maxConnections (except for regional - managed instance groups), maxConnectionsPerInstance, or - maxConnectionsPerEndpoint. - - If the loadBalancingScheme for the backend service is INTERNAL - (internal TCP/UDP Load Balancers) or EXTERNAL (Network Load - Balancing), you cannot specify any additional parameters. - - - If the load balancing mode is RATE, the load is spread based on - the rate of HTTP requests per second (RPS). You can use the RATE - balancing mode if the protocol for the backend service is HTTP, - HTTP2, or HTTPS. You must specify exactly one of the following - parameters: maxRate (except for regional managed instance - groups), maxRatePerInstance, or maxRatePerEndpoint. - - - If the load balancing mode is UTILIZATION, the load is spread - based on the backend utilization of instances in an instance - group. You can use the UTILIZATION balancing mode if the - loadBalancingScheme of the backend service is EXTERNAL (except - Network Load Balancing), INTERNAL_SELF_MANAGED, or - INTERNAL_MANAGED and the backends are instance groups. There are - no restrictions on the backend service protocol. + r"""Specifies how to determine whether the backend of a load + balancer can handle additional traffic or is fully loaded. For + usage guidelines, see Connection balancing mode. """ UNDEFINED_BALANCING_MODE = 0 CONNECTION = 246311646 @@ -3277,6 +3392,12 @@ class BackendBucketCdnPolicy(proto.Message): bucket. Attributes: + bypass_cache_on_request_headers (Sequence[google.cloud.compute_v1.types.BackendBucketCdnPolicyBypassCacheOnRequestHeader]): + Bypass the cache when the specified request + headers are matched - e.g. Pragma or + Authorization headers. Up to 5 headers can be + specified. The cache is bypassed for all + cdnPolicy.cacheMode settings. cache_mode (google.cloud.compute_v1.types.BackendBucketCdnPolicy.CacheMode): Specifies the cache setting for all responses from this backend. The possible values are: @@ -3298,11 +3419,17 @@ class BackendBucketCdnPolicy(proto.Message): are marked as uncacheable, as well as dynamic content (including HTML), will not be cached. client_ttl (int): - Specifies a separate client (e.g. browser - client) TTL, separate from the TTL for Cloud - CDN's edge caches. Leaving this empty will use - the same cache TTL for both Cloud CDN and the - client-facing response. The maximum allowed + Specifies a separate client (e.g. browser client) maximum + TTL. This is used to clamp the max-age (or Expires) value + sent to the client. With FORCE_CACHE_ALL, the lesser of + client_ttl and default_ttl is used for the response max-age + directive, along with a "public" directive. For cacheable + content in CACHE_ALL_STATIC mode, client_ttl clamps the + max-age from the origin (if specified), or else sets the + response max-age directive to the lesser of the client_ttl + and default_ttl, and also ensures a "public" cache-control + directive is present. If a client TTL is not specified, a + default value (1 hour) will be used. The maximum allowed value is 86400s (1 day). default_ttl (int): Specifies the default TTL for cached content served by this @@ -3328,6 +3455,53 @@ class BackendBucketCdnPolicy(proto.Message): maximum allowed value is 31,622,400s (1 year), noting that infrequently accessed objects may be evicted from the cache before the defined TTL. + negative_caching (bool): + Negative caching allows per-status code TTLs to be set, in + order to apply fine-grained caching for common errors or + redirects. This can reduce the load on your origin and + improve end-user experience by reducing response latency. + When the cache mode is set to CACHE_ALL_STATIC or + USE_ORIGIN_HEADERS, negative caching applies to responses + with the specified response code that lack any + Cache-Control, Expires, or Pragma: no-cache directives. When + the cache mode is set to FORCE_CACHE_ALL, negative caching + applies to all responses with the specified response code, + and override any caching headers. By default, Cloud CDN will + apply the following default TTLs to these status codes: HTTP + 300 (Multiple Choice), 301, 308 (Permanent Redirects): 10m + HTTP 404 (Not Found), 410 (Gone), 451 (Unavailable For Legal + Reasons): 120s HTTP 405 (Method Not Found), 421 (Misdirected + Request), 501 (Not Implemented): 60s. These defaults can be + overridden in negative_caching_policy. + negative_caching_policy (Sequence[google.cloud.compute_v1.types.BackendBucketCdnPolicyNegativeCachingPolicy]): + Sets a cache TTL for the specified HTTP status code. + negative_caching must be enabled to configure + negative_caching_policy. Omitting the policy and leaving + negative_caching enabled will use Cloud CDN's default cache + TTLs. Note that when specifying an explicit + negative_caching_policy, you should take care to specify a + cache TTL for all response codes that you wish to cache. + Cloud CDN will not apply any default negative caching when a + policy exists. + request_coalescing (bool): + If true then Cloud CDN will combine multiple + concurrent cache fill requests into a small + number of requests to the origin. + serve_while_stale (int): + Serve existing content from the cache (if + available) when revalidating content with the + origin, or when an error is encountered when + refreshing the cache. This setting defines the + default "max-stale" duration for any cached + responses that do not specify a max-stale + directive. Stale responses that exceed the TTL + configured here will not be served. The default + limit (max-stale) is 86400s (1 day), which will + allow stale content to be served up to this + limit beyond the max-age (or s-max-age) of a + cached response. The maximum allowed value is + 604800 (1 week). Set this to zero (0) to disable + serve-while-stale. signed_url_cache_max_age_sec (str): Maximum number of seconds the response to a signed URL request will be considered fresh. After this time period, @@ -3369,12 +3543,25 @@ class CacheMode(proto.Enum): INVALID_CACHE_MODE = 381295560 USE_ORIGIN_HEADERS = 55380261 + bypass_cache_on_request_headers = proto.RepeatedField( + proto.MESSAGE, + number=486203082, + message="BackendBucketCdnPolicyBypassCacheOnRequestHeader", + ) cache_mode = proto.Field( proto.ENUM, number=28877888, optional=True, enum=CacheMode, ) client_ttl = proto.Field(proto.INT32, number=29034360, optional=True,) default_ttl = proto.Field(proto.INT32, number=100253422, optional=True,) max_ttl = proto.Field(proto.INT32, number=307578001, optional=True,) + negative_caching = proto.Field(proto.BOOL, number=336110005, optional=True,) + negative_caching_policy = proto.RepeatedField( + proto.MESSAGE, + number=155359996, + message="BackendBucketCdnPolicyNegativeCachingPolicy", + ) + request_coalescing = proto.Field(proto.BOOL, number=532808276, optional=True,) + serve_while_stale = proto.Field(proto.INT32, number=236682203, optional=True,) signed_url_cache_max_age_sec = proto.Field( proto.STRING, number=269374534, optional=True, ) @@ -3439,6 +3626,41 @@ class BackendBucket(proto.Message): self_link = proto.Field(proto.STRING, number=456214797, optional=True,) +class BackendBucketCdnPolicyBypassCacheOnRequestHeader(proto.Message): + r"""Bypass the cache when the specified request headers are present, + e.g. Pragma or Authorization headers. Values are case insensitive. + The presence of such a header overrides the cache_mode setting. + + Attributes: + header_name (str): + The header field name to match on when + bypassing cache. Values are case-insensitive. + """ + + header_name = proto.Field(proto.STRING, number=110223613, optional=True,) + + +class BackendBucketCdnPolicyNegativeCachingPolicy(proto.Message): + r"""Specify CDN TTLs for response error codes. + Attributes: + code (int): + The HTTP status code to define a TTL against. + Only HTTP status codes 300, 301, 302, 307, 308, + 404, 405, 410, 421, 451 and 501 are can be + specified as values, and you cannot specify a + status code more than once. + ttl (int): + The TTL (in seconds) for which to cache + responses with the corresponding status code. + The maximum allowed value is 1800s (30 minutes), + noting that infrequently accessed objects may be + evicted from the cache before the defined TTL. + """ + + code = proto.Field(proto.INT32, number=3059181, optional=True,) + ttl = proto.Field(proto.INT32, number=115180, optional=True,) + + class BackendBucketList(proto.Message): r"""Contains a list of BackendBucket resources. Attributes: @@ -3483,6 +3705,12 @@ class BackendServiceCdnPolicy(proto.Message): service. Attributes: + bypass_cache_on_request_headers (Sequence[google.cloud.compute_v1.types.BackendServiceCdnPolicyBypassCacheOnRequestHeader]): + Bypass the cache when the specified request + headers are matched - e.g. Pragma or + Authorization headers. Up to 5 headers can be + specified. The cache is bypassed for all + cdnPolicy.cacheMode settings. cache_key_policy (google.cloud.compute_v1.types.CacheKeyPolicy): The CacheKeyPolicy for this CdnPolicy. cache_mode (google.cloud.compute_v1.types.BackendServiceCdnPolicy.CacheMode): @@ -3506,11 +3734,17 @@ class BackendServiceCdnPolicy(proto.Message): are marked as uncacheable, as well as dynamic content (including HTML), will not be cached. client_ttl (int): - Specifies a separate client (e.g. browser - client) TTL, separate from the TTL for Cloud - CDN's edge caches. Leaving this empty will use - the same cache TTL for both Cloud CDN and the - client-facing response. The maximum allowed + Specifies a separate client (e.g. browser client) maximum + TTL. This is used to clamp the max-age (or Expires) value + sent to the client. With FORCE_CACHE_ALL, the lesser of + client_ttl and default_ttl is used for the response max-age + directive, along with a "public" directive. For cacheable + content in CACHE_ALL_STATIC mode, client_ttl clamps the + max-age from the origin (if specified), or else sets the + response max-age directive to the lesser of the client_ttl + and default_ttl, and also ensures a "public" cache-control + directive is present. If a client TTL is not specified, a + default value (1 hour) will be used. The maximum allowed value is 86400s (1 day). default_ttl (int): Specifies the default TTL for cached content served by this @@ -3536,6 +3770,53 @@ class BackendServiceCdnPolicy(proto.Message): maximum allowed value is 31,622,400s (1 year), noting that infrequently accessed objects may be evicted from the cache before the defined TTL. + negative_caching (bool): + Negative caching allows per-status code TTLs to be set, in + order to apply fine-grained caching for common errors or + redirects. This can reduce the load on your origin and + improve end-user experience by reducing response latency. + When the cache mode is set to CACHE_ALL_STATIC or + USE_ORIGIN_HEADERS, negative caching applies to responses + with the specified response code that lack any + Cache-Control, Expires, or Pragma: no-cache directives. When + the cache mode is set to FORCE_CACHE_ALL, negative caching + applies to all responses with the specified response code, + and override any caching headers. By default, Cloud CDN will + apply the following default TTLs to these status codes: HTTP + 300 (Multiple Choice), 301, 308 (Permanent Redirects): 10m + HTTP 404 (Not Found), 410 (Gone), 451 (Unavailable For Legal + Reasons): 120s HTTP 405 (Method Not Found), 421 (Misdirected + Request), 501 (Not Implemented): 60s. These defaults can be + overridden in negative_caching_policy. + negative_caching_policy (Sequence[google.cloud.compute_v1.types.BackendServiceCdnPolicyNegativeCachingPolicy]): + Sets a cache TTL for the specified HTTP status code. + negative_caching must be enabled to configure + negative_caching_policy. Omitting the policy and leaving + negative_caching enabled will use Cloud CDN's default cache + TTLs. Note that when specifying an explicit + negative_caching_policy, you should take care to specify a + cache TTL for all response codes that you wish to cache. + Cloud CDN will not apply any default negative caching when a + policy exists. + request_coalescing (bool): + If true then Cloud CDN will combine multiple + concurrent cache fill requests into a small + number of requests to the origin. + serve_while_stale (int): + Serve existing content from the cache (if + available) when revalidating content with the + origin, or when an error is encountered when + refreshing the cache. This setting defines the + default "max-stale" duration for any cached + responses that do not specify a max-stale + directive. Stale responses that exceed the TTL + configured here will not be served. The default + limit (max-stale) is 86400s (1 day), which will + allow stale content to be served up to this + limit beyond the max-age (or s-max-age) of a + cached response. The maximum allowed value is + 604800 (1 week). Set this to zero (0) to disable + serve-while-stale. signed_url_cache_max_age_sec (str): Maximum number of seconds the response to a signed URL request will be considered fresh. After this time period, @@ -3577,6 +3858,11 @@ class CacheMode(proto.Enum): INVALID_CACHE_MODE = 381295560 USE_ORIGIN_HEADERS = 55380261 + bypass_cache_on_request_headers = proto.RepeatedField( + proto.MESSAGE, + number=486203082, + message="BackendServiceCdnPolicyBypassCacheOnRequestHeader", + ) cache_key_policy = proto.Field( proto.MESSAGE, number=159263727, optional=True, message="CacheKeyPolicy", ) @@ -3586,6 +3872,14 @@ class CacheMode(proto.Enum): client_ttl = proto.Field(proto.INT32, number=29034360, optional=True,) default_ttl = proto.Field(proto.INT32, number=100253422, optional=True,) max_ttl = proto.Field(proto.INT32, number=307578001, optional=True,) + negative_caching = proto.Field(proto.BOOL, number=336110005, optional=True,) + negative_caching_policy = proto.RepeatedField( + proto.MESSAGE, + number=155359996, + message="BackendServiceCdnPolicyNegativeCachingPolicy", + ) + request_coalescing = proto.Field(proto.BOOL, number=532808276, optional=True,) + serve_while_stale = proto.Field(proto.INT32, number=236682203, optional=True,) signed_url_cache_max_age_sec = proto.Field( proto.STRING, number=269374534, optional=True, ) @@ -3635,9 +3929,10 @@ class ConnectionDraining(proto.Message): r"""Message containing connection draining configuration. Attributes: draining_timeout_sec (int): - The amount of time in seconds to allow existing connections - to persist while on unhealthy backend VMs. Only applicable - if the protocol is not UDP. The valid range is [0, 3600]. + Configures a duration timeout for existing + requests on a removed backend instance. For + supported load balancers and protocols, as + described in Enabling connection draining. """ draining_timeout_sec = proto.Field(proto.INT32, number=225127070, optional=True,) @@ -3775,6 +4070,29 @@ class BackendServiceLogConfig(proto.Message): sample_rate = proto.Field(proto.FLOAT, number=153193045, optional=True,) +class Duration(proto.Message): + r"""A Duration represents a fixed-length span of time represented + as a count of seconds and fractions of seconds at nanosecond + resolution. It is independent of any calendar and concepts like + "day" or "month". Range is approximately 10,000 years. + + Attributes: + nanos (int): + Span of time that's a fraction of a second at nanosecond + resolution. Durations less than one second are represented + with a 0 ``seconds`` field and a positive ``nanos`` field. + Must be from 0 to 999,999,999 inclusive. + seconds (str): + Span of time at a resolution of a second. Must be from 0 to + 315,576,000,000 inclusive. Note: these bounds are computed + from: 60 sec/min \* 60 min/hr \* 24 hr/day \* 365.25 + days/year \* 10000 years + """ + + nanos = proto.Field(proto.INT32, number=104586303, optional=True,) + seconds = proto.Field(proto.STRING, number=359484031, optional=True,) + + class OutlierDetection(proto.Message): r"""Settings controlling the eviction of unhealthy hosts from the load balancing pool for the backend service. @@ -3955,9 +4273,8 @@ class BackendService(proto.Message): BackendService. cdn_policy (google.cloud.compute_v1.types.BackendServiceCdnPolicy): Cloud CDN configuration for this - BackendService. Not available for Internal - TCP/UDP Load Balancing and Network Load - Balancing. + BackendService. Only available for external + HTTP(S) Load Balancing. circuit_breakers (google.cloud.compute_v1.types.CircuitBreakers): Settings controlling the volume of connections to a backend service. If not set, this feature is considered disabled. @@ -4109,6 +4426,15 @@ class BackendService(proto.Message): the load balancer traffic served by this backend service. If logging is enabled, logs will be exported to Stackdriver. + max_stream_duration (google.cloud.compute_v1.types.Duration): + Specifies the default maximum duration (timeout) for streams + to this service. Duration is computed from the beginning of + the stream until the response has been completely processed, + including all retries. A stream that does not complete in + this duration is closed. If not specified, there will be no + timeout limit, i.e. the maximum duration is infinite. This + field is only allowed when the loadBalancingScheme of the + backend service is INTERNAL_SELF_MANAGED. name (str): Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, @@ -4142,9 +4468,9 @@ class BackendService(proto.Message): port (int): Deprecated in favor of portName. The TCP port to connect on the backend. The default value is - 80. This cannot be used if the - loadBalancingScheme is INTERNAL (Internal - TCP/UDP Load Balancing). + 80. Backend services for Internal TCP/UDP Load + Balancing and Network Load Balancing require you + omit port. port_name (str): A named port on a backend instance group representing the port for communication to the backend VMs in that group. @@ -4214,7 +4540,9 @@ class BackendService(proto.Message): The backend service timeout has a different meaning depending on the type of load balancer. For more information see, Backend service - settings The default is 30 seconds. + settings The default is 30 seconds. The full + range of timeout values allowed is 1 - + 2,147,483,647 seconds. """ class LoadBalancingScheme(proto.Enum): @@ -4323,6 +4651,7 @@ class SessionAffinity(proto.Enum): """ UNDEFINED_SESSION_AFFINITY = 0 CLIENT_IP = 345665051 + CLIENT_IP_NO_DESTINATION = 106122516 CLIENT_IP_PORT_PROTO = 221722926 CLIENT_IP_PROTO = 25322148 GENERATED_COOKIE = 370321204 @@ -4380,6 +4709,9 @@ class SessionAffinity(proto.Enum): optional=True, message="BackendServiceLogConfig", ) + max_stream_duration = proto.Field( + proto.MESSAGE, number=61428376, optional=True, message="Duration", + ) name = proto.Field(proto.STRING, number=3373707, optional=True,) network = proto.Field(proto.STRING, number=232872494, optional=True,) outlier_detection = proto.Field( @@ -4465,6 +4797,20 @@ def raw_page(self): ) +class BackendServiceCdnPolicyBypassCacheOnRequestHeader(proto.Message): + r"""Bypass the cache when the specified request headers are present, + e.g. Pragma or Authorization headers. Values are case insensitive. + The presence of such a header overrides the cache_mode setting. + + Attributes: + header_name (str): + The header field name to match on when + bypassing cache. Values are case-insensitive. + """ + + header_name = proto.Field(proto.STRING, number=110223613, optional=True,) + + class CacheKeyPolicy(proto.Message): r"""Message containing what to include in the cache key for a request for Cloud CDN. @@ -4503,19 +4849,49 @@ class CacheKeyPolicy(proto.Message): query_string_whitelist = proto.RepeatedField(proto.STRING, number=52456496,) +class BackendServiceCdnPolicyNegativeCachingPolicy(proto.Message): + r"""Specify CDN TTLs for response error codes. + Attributes: + code (int): + The HTTP status code to define a TTL against. + Only HTTP status codes 300, 301, 302, 307, 308, + 404, 405, 410, 421, 451 and 501 are can be + specified as values, and you cannot specify a + status code more than once. + ttl (int): + The TTL (in seconds) for which to cache + responses with the corresponding status code. + The maximum allowed value is 1800s (30 minutes), + noting that infrequently accessed objects may be + evicted from the cache before the defined TTL. + """ + + code = proto.Field(proto.INT32, number=3059181, optional=True,) + ttl = proto.Field(proto.INT32, number=115180, optional=True,) + + class HealthStatus(proto.Message): r""" Attributes: annotations (Sequence[google.cloud.compute_v1.types.HealthStatus.AnnotationsEntry]): Metadata defined as annotations for network endpoint. + forwarding_rule (str): + URL of the forwarding rule associated with + the health status of the instance. + forwarding_rule_ip (str): + A forwarding rule IP address assigned to this + instance. health_state (google.cloud.compute_v1.types.HealthStatus.HealthState): Health state of the instance. instance (str): URL of the instance resource. ip_address (str): - A forwarding rule IP address assigned to this - instance. + For target pool based Network Load Balancing, + it indicates the forwarding rule's IP address + assigned to this instance. For other types of + load balancing, the field indicates VM internal + ip. port (int): The named port of the instance group, not necessarily the port that is health-checked. @@ -4540,6 +4916,8 @@ class WeightError(proto.Enum): WEIGHT_NONE = 502428831 annotations = proto.MapField(proto.STRING, proto.STRING, number=112032548,) + forwarding_rule = proto.Field(proto.STRING, number=269964030, optional=True,) + forwarding_rule_ip = proto.Field(proto.STRING, number=172250632, optional=True,) health_state = proto.Field( proto.ENUM, number=324007150, optional=True, enum=HealthState, ) @@ -4767,6 +5145,250 @@ class Binding(proto.Message): role = proto.Field(proto.STRING, number=3506294, optional=True,) +class InstanceProperties(proto.Message): + r""" + Attributes: + advanced_machine_features (google.cloud.compute_v1.types.AdvancedMachineFeatures): + Controls for advanced machine-related + behavior features. + can_ip_forward (bool): + Enables instances created based on these + properties to send packets with source IP + addresses other than their own and receive + packets with destination IP addresses other than + their own. If these instances will be used as an + IP gateway or it will be set as the next-hop in + a Route resource, specify true. If unsure, leave + this set to false. See the Enable IP forwarding + documentation for more information. + confidential_instance_config (google.cloud.compute_v1.types.ConfidentialInstanceConfig): + Specifies the Confidential Instance options. + description (str): + An optional text description for the + instances that are created from these + properties. + disks (Sequence[google.cloud.compute_v1.types.AttachedDisk]): + An array of disks that are associated with + the instances that are created from these + properties. + guest_accelerators (Sequence[google.cloud.compute_v1.types.AcceleratorConfig]): + A list of guest accelerator cards' type and + count to use for instances created from these + properties. + labels (Sequence[google.cloud.compute_v1.types.InstanceProperties.LabelsEntry]): + Labels to apply to instances that are created + from these properties. + machine_type (str): + The machine type to use for instances that + are created from these properties. + metadata (google.cloud.compute_v1.types.Metadata): + The metadata key/value pairs to assign to + instances that are created from these + properties. These pairs can consist of custom + metadata or predefined keys. See Project and + instance metadata for more information. + min_cpu_platform (str): + Minimum cpu/platform to be used by instances. + The instance may be scheduled on the specified + or newer cpu/platform. Applicable values are the + friendly names of CPU platforms, such as + minCpuPlatform: "Intel Haswell" or + minCpuPlatform: "Intel Sandy Bridge". For more + information, read Specifying a Minimum CPU + Platform. + network_interfaces (Sequence[google.cloud.compute_v1.types.NetworkInterface]): + An array of network access configurations for + this interface. + private_ipv6_google_access (google.cloud.compute_v1.types.InstanceProperties.PrivateIpv6GoogleAccess): + The private IPv6 google access type for VMs. If not + specified, use INHERIT_FROM_SUBNETWORK as default. + reservation_affinity (google.cloud.compute_v1.types.ReservationAffinity): + Specifies the reservations that instances can + consume from. + resource_policies (Sequence[str]): + Resource policies (names, not ULRs) applied + to instances created from these properties. + scheduling (google.cloud.compute_v1.types.Scheduling): + Specifies the scheduling options for the + instances that are created from these + properties. + service_accounts (Sequence[google.cloud.compute_v1.types.ServiceAccount]): + A list of service accounts with specified + scopes. Access tokens for these service accounts + are available to the instances that are created + from these properties. Use metadata queries to + obtain the access tokens for these instances. + shielded_instance_config (google.cloud.compute_v1.types.ShieldedInstanceConfig): + + tags (google.cloud.compute_v1.types.Tags): + A list of tags to apply to the instances that + are created from these properties. The tags + identify valid sources or targets for network + firewalls. The setTags method can modify this + list of tags. Each tag within the list must + comply with RFC1035. + """ + + class PrivateIpv6GoogleAccess(proto.Enum): + r"""The private IPv6 google access type for VMs. If not specified, use + INHERIT_FROM_SUBNETWORK as default. + """ + UNDEFINED_PRIVATE_IPV6_GOOGLE_ACCESS = 0 + ENABLE_BIDIRECTIONAL_ACCESS_TO_GOOGLE = 427975994 + ENABLE_OUTBOUND_VM_ACCESS_TO_GOOGLE = 288210263 + INHERIT_FROM_SUBNETWORK = 530256959 + + advanced_machine_features = proto.Field( + proto.MESSAGE, + number=409646002, + optional=True, + message="AdvancedMachineFeatures", + ) + can_ip_forward = proto.Field(proto.BOOL, number=467731324, optional=True,) + confidential_instance_config = proto.Field( + proto.MESSAGE, + number=490637685, + optional=True, + message="ConfidentialInstanceConfig", + ) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + disks = proto.RepeatedField(proto.MESSAGE, number=95594102, message="AttachedDisk",) + guest_accelerators = proto.RepeatedField( + proto.MESSAGE, number=463595119, message="AcceleratorConfig", + ) + labels = proto.MapField(proto.STRING, proto.STRING, number=500195327,) + machine_type = proto.Field(proto.STRING, number=227711026, optional=True,) + metadata = proto.Field( + proto.MESSAGE, number=86866735, optional=True, message="Metadata", + ) + min_cpu_platform = proto.Field(proto.STRING, number=242912759, optional=True,) + network_interfaces = proto.RepeatedField( + proto.MESSAGE, number=52735243, message="NetworkInterface", + ) + private_ipv6_google_access = proto.Field( + proto.ENUM, number=48277006, optional=True, enum=PrivateIpv6GoogleAccess, + ) + reservation_affinity = proto.Field( + proto.MESSAGE, number=157850683, optional=True, message="ReservationAffinity", + ) + resource_policies = proto.RepeatedField(proto.STRING, number=22220385,) + scheduling = proto.Field( + proto.MESSAGE, number=386688404, optional=True, message="Scheduling", + ) + service_accounts = proto.RepeatedField( + proto.MESSAGE, number=277537328, message="ServiceAccount", + ) + shielded_instance_config = proto.Field( + proto.MESSAGE, number=12862901, optional=True, message="ShieldedInstanceConfig", + ) + tags = proto.Field(proto.MESSAGE, number=3552281, optional=True, message="Tags",) + + +class LocationPolicy(proto.Message): + r"""Configuration for location policy among multiple possible + locations (e.g. preferences for zone selection among zones in a + single region). + + Attributes: + locations (Sequence[google.cloud.compute_v1.types.LocationPolicy.LocationsEntry]): + Location configurations mapped by location + name. Currently only zone names are supported + and must be represented as valid internal URLs, + such as zones/us-central1-a. + """ + + locations = proto.MapField( + proto.STRING, proto.MESSAGE, number=413423454, message="LocationPolicyLocation", + ) + + +class BulkInsertInstanceResourcePerInstanceProperties(proto.Message): + r"""Per-instance properties to be set on individual instances. To + be extended in the future. + + Attributes: + name (str): + This field is only temporary. It will be + removed. Do not use it. + """ + + name = proto.Field(proto.STRING, number=3373707, optional=True,) + + +class BulkInsertInstanceResource(proto.Message): + r""" + Attributes: + count (str): + The maximum number of instances to create. + instance_properties (google.cloud.compute_v1.types.InstanceProperties): + The instance properties defining the VM + instances to be created. Required if + sourceInstanceTemplate is not provided. + location_policy (google.cloud.compute_v1.types.LocationPolicy): + Policy for chosing target zone. + min_count (str): + The minimum number of instances to create. If no min_count + is specified then count is used as the default value. If + min_count instances cannot be created, then no instances + will be created and instances already created will be + deleted. + name_pattern (str): + The string pattern used for the names of the VMs. Either + name_pattern or per_instance_properties must be set. The + pattern should contain one continuous sequence of + placeholder hash characters (#) with each character + corresponding to one digit of the generated instance name. + Example: name_pattern of inst-#### will generate instance + names such as inst-0001, inst-0002, ... . If there already + exist instance(s) whose names match the name pattern in the + same project and zone, then the generated instance numbers + will start after the biggest existing number. For example, + if there exists an instance with name inst-0050, then + instance names generated using the pattern inst-#### will be + inst-0051, inst-0052, etc. The name pattern placeholder + #...# can contain up to 18 characters. + per_instance_properties (Sequence[google.cloud.compute_v1.types.BulkInsertInstanceResource.PerInstancePropertiesEntry]): + Per-instance properties to be set on individual instances. + Keys of this map specify requested instance names. Can be + empty if name_pattern is used. + source_instance_template (str): + Specifies the instance template from which to + create instances. You may combine + sourceInstanceTemplate with instanceProperties + to override specific values from an existing + instance template. Bulk API follows the + semantics of JSON Merge Patch described by RFC + 7396. It can be a full or partial URL. For + example, the following are all valid URLs to an + instance template: - + https://www.googleapis.com/compute/v1/projects/project/global/instanceTemplates/instanceTemplate + - + projects/project/global/instanceTemplates/instanceTemplate + - global/instanceTemplates/instanceTemplate + + This field is optional. + """ + + count = proto.Field(proto.STRING, number=94851343, optional=True,) + instance_properties = proto.Field( + proto.MESSAGE, number=215355165, optional=True, message="InstanceProperties", + ) + location_policy = proto.Field( + proto.MESSAGE, number=465689852, optional=True, message="LocationPolicy", + ) + min_count = proto.Field(proto.STRING, number=523228386, optional=True,) + name_pattern = proto.Field(proto.STRING, number=413815260, optional=True,) + per_instance_properties = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=108502267, + message="BulkInsertInstanceResourcePerInstanceProperties", + ) + source_instance_template = proto.Field( + proto.STRING, number=332423616, optional=True, + ) + + class CacheInvalidationRule(proto.Message): r""" Attributes: @@ -4831,6 +5453,8 @@ class Reservation(proto.Message): 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. + satisfies_pzs (bool): + [Output Only] Reserved for future use. self_link (str): [Output Only] Server-defined fully-qualified URL for this resource. @@ -4866,6 +5490,7 @@ class Status(proto.Enum): id = proto.Field(proto.STRING, number=3355, optional=True,) kind = proto.Field(proto.STRING, number=3292052, optional=True,) name = proto.Field(proto.STRING, number=3373707, optional=True,) + satisfies_pzs = proto.Field(proto.BOOL, number=480964267, optional=True,) self_link = proto.Field(proto.STRING, number=456214797, optional=True,) specific_reservation = proto.Field( proto.MESSAGE, @@ -5206,29 +5831,6 @@ class ConsistentHashLoadBalancerSettingsHttpCookie(proto.Message): ttl = proto.Field(proto.MESSAGE, number=115180, optional=True, message="Duration",) -class Duration(proto.Message): - r"""A Duration represents a fixed-length span of time represented - as a count of seconds and fractions of seconds at nanosecond - resolution. It is independent of any calendar and concepts like - "day" or "month". Range is approximately 10,000 years. - - Attributes: - nanos (int): - Span of time that's a fraction of a second at nanosecond - resolution. Durations less than one second are represented - with a 0 ``seconds`` field and a positive ``nanos`` field. - Must be from 0 to 999,999,999 inclusive. - seconds (str): - Span of time at a resolution of a second. Must be from 0 to - 315,576,000,000 inclusive. Note: these bounds are computed - from: 60 sec/min \* 60 min/hr \* 24 hr/day \* 365.25 - days/year \* 10000 years - """ - - nanos = proto.Field(proto.INT32, number=104586303, optional=True,) - seconds = proto.Field(proto.STRING, number=359484031, optional=True,) - - class CorsPolicy(proto.Message): r"""The specification for allowing client side cross-origin requests. Please see W3C Recommendation for Cross Origin @@ -5251,10 +5853,9 @@ class CorsPolicy(proto.Message): Specifies the regualar expression patterns that match allowed origins. For regular expression grammar please see - en.cppreference.com/w/cpp/regex/ecmascript An - origin is allowed if it matches either an item - in allowOrigins or an item in - allowOriginRegexes. + github.com/google/re2/wiki/Syntax An origin is + allowed if it matches either an item in + allowOrigins or an item in allowOriginRegexes. allow_origins (Sequence[str]): Specifies the list of origins that will be allowed to do CORS requests. An origin is @@ -5381,6 +5982,10 @@ class Disk(proto.Message): licenses (Sequence[str]): A list of publicly visible licenses. Reserved for Google's use. + location_hint (str): + An opaque location hint used to place the + disk close to other resources. This field is for + use by internal tools that use the public API. name (str): Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, @@ -5400,6 +6005,9 @@ class Disk(proto.Message): an unsupported value is requested, the error message will list the supported values for the caller's project. + provisioned_iops (str): + Indicates how many IOPS must be provisioned + for the disk. region (str): [Output Only] URL of the region where the disk resides. Only applicable for regional resources. You must specify this @@ -5412,6 +6020,8 @@ class Disk(proto.Message): resource_policies (Sequence[str]): Resource policies applied to this disk for automatic snapshot creations. + satisfies_pzs (bool): + [Output Only] Reserved for future use. self_link (str): [Output Only] Server-defined fully-qualified URL for this resource. @@ -5431,8 +6041,12 @@ class Disk(proto.Message): resource. 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 source_disk_id (str): [Output Only] The unique ID of the disk used to create this disk. This value identifies the exact disk that was used to @@ -5495,11 +6109,25 @@ class Disk(proto.Message): deleted and recreated under the same name, the source snapshot ID would identify the exact version of the snapshot that was used. + source_storage_object (str): + The full Google Cloud Storage URI where the + disk image is stored. This file must be a gzip- + compressed tarball whose name ends in .tar.gz or + virtual machine disk whose name ends in vmdk. + Valid URIs may start with gs:// or + https://storage.googleapis.com/. This flag is + not optimized for creating multiple disks from a + source storage object. To create many disks from + a source storage object, use gcloud compute + images import instead. status (google.cloud.compute_v1.types.Disk.Status): - [Output Only] The status of disk creation. CREATING: Disk is - provisioning. RESTORING: Source data is being copied into - the disk. FAILED: Disk creation failed. READY: Disk is ready - for use. DELETING: Disk is deleting. + [Output Only] The status of disk creation. + + - CREATING: Disk is provisioning. + - RESTORING: Source data is being copied into the disk. + - FAILED: Disk creation failed. + - READY: Disk is ready for use. + - DELETING: Disk is deleting. type_ (str): URL of the disk type resource describing which disk type to use to create the disk. @@ -5518,10 +6146,13 @@ class Disk(proto.Message): """ class Status(proto.Enum): - r"""[Output Only] The status of disk creation. CREATING: Disk is - provisioning. RESTORING: Source data is being copied into the disk. - FAILED: Disk creation failed. READY: Disk is ready for use. - DELETING: Disk is deleting. + r"""[Output Only] The status of disk creation. + + - CREATING: Disk is provisioning. + - RESTORING: Source data is being copied into the disk. + - FAILED: Disk creation failed. + - READY: Disk is ready for use. + - DELETING: Disk is deleting. """ UNDEFINED_STATUS = 0 CREATING = 455564985 @@ -5546,14 +6177,17 @@ class Status(proto.Enum): last_detach_timestamp = proto.Field(proto.STRING, number=56471027, optional=True,) license_codes = proto.RepeatedField(proto.STRING, number=45482664,) licenses = proto.RepeatedField(proto.STRING, number=337642578,) + location_hint = proto.Field(proto.STRING, number=350519505, optional=True,) name = proto.Field(proto.STRING, number=3373707, optional=True,) options = proto.Field(proto.STRING, number=361137822, optional=True,) physical_block_size_bytes = proto.Field( proto.STRING, number=420007943, optional=True, ) + provisioned_iops = proto.Field(proto.STRING, number=186769108, optional=True,) region = proto.Field(proto.STRING, number=138946292, optional=True,) replica_zones = proto.RepeatedField(proto.STRING, number=48438272,) resource_policies = proto.RepeatedField(proto.STRING, number=22220385,) + satisfies_pzs = proto.Field(proto.BOOL, number=480964267, optional=True,) self_link = proto.Field(proto.STRING, number=456214797, optional=True,) size_gb = proto.Field(proto.STRING, number=494929369, optional=True,) source_disk = proto.Field(proto.STRING, number=451753793, optional=True,) @@ -5568,6 +6202,7 @@ class Status(proto.Enum): proto.MESSAGE, number=303679322, optional=True, message="CustomerEncryptionKey", ) source_snapshot_id = proto.Field(proto.STRING, number=98962258, optional=True,) + source_storage_object = proto.Field(proto.STRING, number=233052711, optional=True,) status = proto.Field(proto.ENUM, number=181260274, optional=True, enum=Status,) type_ = proto.Field(proto.STRING, number=3575610, optional=True,) users = proto.RepeatedField(proto.STRING, number=111578632,) @@ -5992,11 +6627,29 @@ class DistributionPolicyZoneConfiguration(proto.Message): class DistributionPolicy(proto.Message): r""" Attributes: + target_shape (google.cloud.compute_v1.types.DistributionPolicy.TargetShape): + The distribution shape to which the group + converges either proactively or on resize events + (depending on the value set in + updatePolicy.instanceRedistributionType). zones (Sequence[google.cloud.compute_v1.types.DistributionPolicyZoneConfiguration]): Zones where the regional managed instance group will create and manage its instances. """ + class TargetShape(proto.Enum): + r"""The distribution shape to which the group converges either + proactively or on resize events (depending on the value set in + updatePolicy.instanceRedistributionType). + """ + UNDEFINED_TARGET_SHAPE = 0 + ANY = 64972 + BALANCED = 468409608 + EVEN = 2140442 + + target_shape = proto.Field( + proto.ENUM, number=338621299, optional=True, enum=TargetShape, + ) zones = proto.RepeatedField( proto.MESSAGE, number=116085319, message="DistributionPolicyZoneConfiguration", ) @@ -6260,7 +6913,7 @@ class FileType(proto.Enum): class Allowed(proto.Message): r""" Attributes: - i_p_protocol (str): + I_p_protocol (str): The IP protocol to which this rule applies. The protocol type is required when creating a firewall rule. This value can either be one of @@ -6278,14 +6931,14 @@ class Allowed(proto.Message): ["12345-12349"]. """ - i_p_protocol = proto.Field(proto.STRING, number=323774237, optional=True,) + I_p_protocol = proto.Field(proto.STRING, number=488094525, optional=True,) ports = proto.RepeatedField(proto.STRING, number=106854418,) class Denied(proto.Message): r""" Attributes: - i_p_protocol (str): + I_p_protocol (str): The IP protocol to which this rule applies. The protocol type is required when creating a firewall rule. This value can either be one of @@ -6303,7 +6956,7 @@ class Denied(proto.Message): ["12345-12349"]. """ - i_p_protocol = proto.Field(proto.STRING, number=323774237, optional=True,) + I_p_protocol = proto.Field(proto.STRING, number=488094525, optional=True,) ports = proto.RepeatedField(proto.STRING, number=106854418,) @@ -6557,6 +7210,312 @@ def raw_page(self): ) +class FirewallPolicyAssociation(proto.Message): + r""" + Attributes: + attachment_target (str): + The target that the firewall policy is + attached to. + display_name (str): + [Output Only] Deprecated, please use short name instead. The + display name of the firewall policy of the association. + firewall_policy_id (str): + [Output Only] The firewall policy ID of the association. + name (str): + The name for an association. + short_name (str): + [Output Only] The short name of the firewall policy of the + association. + """ + + attachment_target = proto.Field(proto.STRING, number=175773741, optional=True,) + display_name = proto.Field(proto.STRING, number=4473832, optional=True,) + firewall_policy_id = proto.Field(proto.STRING, number=357211849, optional=True,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + short_name = proto.Field(proto.STRING, number=492051566, optional=True,) + + +class FirewallPoliciesListAssociationsResponse(proto.Message): + r""" + Attributes: + associations (Sequence[google.cloud.compute_v1.types.FirewallPolicyAssociation]): + A list of associations. + kind (str): + [Output Only] Type of firewallPolicy associations. Always + compute#FirewallPoliciesListAssociations for lists of + firewallPolicy associations. + """ + + associations = proto.RepeatedField( + proto.MESSAGE, number=508736530, message="FirewallPolicyAssociation", + ) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) + + +class FirewallPolicyRule(proto.Message): + r"""Represents a rule that describes one or more match conditions + along with the action to be taken when traffic matches this + condition (allow or deny). + + Attributes: + action (str): + The Action to perform when the client + connection triggers the rule. Can currently be + either "allow" or "deny()" where valid values + for status are 403, 404, and 502. + description (str): + An optional description for this resource. + direction (google.cloud.compute_v1.types.FirewallPolicyRule.Direction): + The direction in which this rule applies. + disabled (bool): + Denotes whether the firewall policy rule is + disabled. When set to true, the firewall policy + rule is not enforced and traffic behaves as if + it did not exist. If this is unspecified, the + firewall policy rule will be enabled. + enable_logging (bool): + Denotes whether to enable logging for a particular rule. If + logging is enabled, logs will be exported to the configured + export destination in Stackdriver. Logs may be exported to + BigQuery or Pub/Sub. Note: you cannot enable logging on + "goto_next" rules. + kind (str): + [Output only] Type of the resource. Always + compute#firewallPolicyRule for firewall policy rules + match (google.cloud.compute_v1.types.FirewallPolicyRuleMatcher): + A match condition that incoming traffic is + evaluated against. If it evaluates to true, the + corresponding 'action' is enforced. + priority (int): + An integer indicating the priority of a rule + in the list. The priority must be a positive + value between 0 and 2147483647. Rules are + evaluated from highest to lowest priority where + 0 is the highest priority and 2147483647 is the + lowest prority. + rule_tuple_count (int): + [Output Only] Calculation of the complexity of a single + firewall policy rule. + target_resources (Sequence[str]): + A list of network resource URLs to which this + rule applies. This field allows you to control + which network's VMs get this rule. If this field + is left blank, all VMs within the organization + will receive the rule. + target_service_accounts (Sequence[str]): + A list of service accounts indicating the + sets of instances that are applied with this + rule. + """ + + class Direction(proto.Enum): + r"""The direction in which this rule applies.""" + UNDEFINED_DIRECTION = 0 + EGRESS = 432880501 + INGRESS = 516931221 + + action = proto.Field(proto.STRING, number=187661878, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + direction = proto.Field( + proto.ENUM, number=111150975, optional=True, enum=Direction, + ) + disabled = proto.Field(proto.BOOL, number=270940796, optional=True,) + enable_logging = proto.Field(proto.BOOL, number=295396515, optional=True,) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) + match = proto.Field( + proto.MESSAGE, + number=103668165, + optional=True, + message="FirewallPolicyRuleMatcher", + ) + priority = proto.Field(proto.INT32, number=445151652, optional=True,) + rule_tuple_count = proto.Field(proto.INT32, number=388342037, optional=True,) + target_resources = proto.RepeatedField(proto.STRING, number=528230647,) + target_service_accounts = proto.RepeatedField(proto.STRING, number=457639710,) + + +class FirewallPolicy(proto.Message): + r"""Represents a Firewall Policy resource. (== resource_for + {$api_version}.firewallPolicies ==) + + Attributes: + associations (Sequence[google.cloud.compute_v1.types.FirewallPolicyAssociation]): + A list of associations that belong to this + firewall policy. + creation_timestamp (str): + [Output Only] Creation timestamp in RFC3339 text format. + description (str): + An optional description of this resource. + Provide this property when you create the + resource. + display_name (str): + Depreacted, please use short name instead. User-provided + name of the Organization firewall plicy. The name should be + unique in the organization in which the firewall policy 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. + fingerprint (str): + Specifies a fingerprint for this resource, + which is essentially a hash of the metadata's + contents and used for optimistic locking. The + fingerprint is initially generated by Compute + Engine and changes after every request to modify + or update metadata. You must always provide an + up-to-date fingerprint hash in order to update + or change metadata, otherwise the request will + fail with error 412 conditionNotMet. To see the + latest fingerprint, make get() request to the + firewall policy. + id (str): + [Output Only] The unique identifier for the resource. This + identifier is defined by the server. + kind (str): + [Output only] Type of the resource. Always + compute#firewallPolicyfor firewall policies + name (str): + [Output Only] Name of the resource. It is a numeric ID + allocated by GCP which uniquely identifies the Firewall + Policy. + parent (str): + [Output Only] The parent of the firewall policy. + rule_tuple_count (int): + [Output Only] Total count of all firewall policy rule + tuples. A firewall policy can not exceed a set number of + tuples. + rules (Sequence[google.cloud.compute_v1.types.FirewallPolicyRule]): + A list of rules that belong to this policy. There must + always be a default rule (rule with priority 2147483647 and + match "*"). If no rules are provided when creating a + firewall policy, a default rule with action "allow" will be + added. + self_link (str): + [Output Only] Server-defined URL for the resource. + self_link_with_id (str): + [Output Only] Server-defined URL for this resource with the + resource id. + short_name (str): + User-provided name of the Organization firewall plicy. The + name should be unique in the organization in which the + firewall policy 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. + """ + + associations = proto.RepeatedField( + proto.MESSAGE, number=508736530, message="FirewallPolicyAssociation", + ) + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + display_name = proto.Field(proto.STRING, number=4473832, optional=True,) + fingerprint = proto.Field(proto.STRING, number=234678500, optional=True,) + id = proto.Field(proto.STRING, number=3355, optional=True,) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + parent = proto.Field(proto.STRING, number=78317738, optional=True,) + rule_tuple_count = proto.Field(proto.INT32, number=388342037, optional=True,) + rules = proto.RepeatedField( + proto.MESSAGE, number=108873975, message="FirewallPolicyRule", + ) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + self_link_with_id = proto.Field(proto.STRING, number=44520962, optional=True,) + short_name = proto.Field(proto.STRING, number=492051566, optional=True,) + + +class FirewallPolicyList(proto.Message): + r""" + Attributes: + id (str): + [Output Only] Unique identifier for the resource; defined by + the server. + items (Sequence[google.cloud.compute_v1.types.FirewallPolicy]): + A list of FirewallPolicy resources. + kind (str): + [Output Only] Type of resource. Always + compute#firewallPolicyList for listsof FirewallPolicies + 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. + warning (google.cloud.compute_v1.types.Warning): + [Output Only] Informational warning message. + """ + + @property + def raw_page(self): + return self + + id = proto.Field(proto.STRING, number=3355, optional=True,) + items = proto.RepeatedField( + proto.MESSAGE, number=100526016, message="FirewallPolicy", + ) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) + next_page_token = proto.Field(proto.STRING, number=79797525, optional=True,) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", + ) + + +class FirewallPolicyRuleMatcher(proto.Message): + r"""Represents a match condition that incoming traffic is + evaluated against. Exactly one field must be specified. + + Attributes: + dest_ip_ranges (Sequence[str]): + CIDR IP address range. Maximum number of + destination CIDR IP ranges allowed is 256. + layer4_configs (Sequence[google.cloud.compute_v1.types.FirewallPolicyRuleMatcherLayer4Config]): + Pairs of IP protocols and ports that the rule + should match. + src_ip_ranges (Sequence[str]): + CIDR IP address range. Maximum number of + source CIDR IP ranges allowed is 256. + """ + + dest_ip_ranges = proto.RepeatedField(proto.STRING, number=337357713,) + layer4_configs = proto.RepeatedField( + proto.MESSAGE, + number=373534261, + message="FirewallPolicyRuleMatcherLayer4Config", + ) + src_ip_ranges = proto.RepeatedField(proto.STRING, number=432128083,) + + +class FirewallPolicyRuleMatcherLayer4Config(proto.Message): + r""" + Attributes: + ip_protocol (str): + The IP protocol to which this rule applies. + The protocol type is required when creating a + firewall rule. This value can either be one of + the following well known protocol strings (tcp, + udp, icmp, esp, ah, ipip, sctp), or the IP + protocol number. + ports (Sequence[str]): + An optional list of ports to which this rule applies. This + field is only applicable for UDP or TCP protocol. Each entry + must be either an integer or a range. If not specified, this + rule applies to connections through any port. + + Example inputs include: ["22"], ["80","443"], and + ["12345-12349"]. + """ + + ip_protocol = proto.Field(proto.STRING, number=475958960, optional=True,) + ports = proto.RepeatedField(proto.STRING, number=106854418,) + + class MetadataFilter(proto.Message): r"""Opaque filter criteria used by loadbalancers to restrict routing configuration to a limited set of loadbalancing proxies. Proxies and @@ -6615,6 +7574,34 @@ class FilterMatchCriteria(proto.Enum): ) +class ForwardingRuleServiceDirectoryRegistration(proto.Message): + r"""Describes the auto-registration of the Forwarding Rule to + Service Directory. The region and project of the Service + Directory resource generated from this registration will be the + same as this Forwarding Rule. + + Attributes: + namespace (str): + Service Directory namespace to register the + forwarding rule under. + service (str): + Service Directory service to register the + forwarding rule under. + service_directory_region (str): + [Optional] Service Directory region to register this global + forwarding rule under. Default to "us-central1". Only used + for PSC for Google APIs. All PSC for Google APIs Forwarding + Rules on the same network should use the same Service + Directory region. + """ + + namespace = proto.Field(proto.STRING, number=178476379, optional=True,) + service = proto.Field(proto.STRING, number=373540533, optional=True,) + service_directory_region = proto.Field( + proto.STRING, number=74030416, optional=True, + ) + + class ForwardingRule(proto.Message): r"""Represents a Forwarding Rule resource. @@ -6638,46 +7625,7 @@ class ForwardingRule(proto.Message): {$api_version}.regionForwardingRules ==) Attributes: - all_ports (bool): - This field is used along with the backend_service field for - internal load balancing or with the target field for - internal TargetInstance. This field cannot be used with port - or portRange fields. - - When the load balancing scheme is INTERNAL and protocol is - TCP/UDP, specify this field to allow packets addressed to - any ports will be forwarded to the backends configured with - this forwarding rule. - allow_global_access (bool): - This field is used along with the backend_service field for - internal load balancing or with the target field for - internal TargetInstance. If the field is set to TRUE, - clients can access ILB from all regions. Otherwise only - allows access from clients in the same region as the - internal load balancer. - backend_service (str): - Identifies the backend service to which the - forwarding rule sends traffic. Required for - Internal TCP/UDP Load Balancing and Network Load - Balancing; must be omitted for all other load - balancer types. - creation_timestamp (str): - [Output Only] Creation timestamp in RFC3339 text format. - description (str): - An optional description of this resource. - Provide this property when you create the - resource. - fingerprint (str): - Fingerprint of this resource. A hash of the - contents stored in this object. This field is - used in optimistic locking. This field will be - ignored when inserting a ForwardingRule. Include - the fingerprint in patch request to ensure that - you do not overwrite changes that were applied - from another concurrent request. To see the - latest fingerprint, make a get() request to - retrieve a ForwardingRule. - i_p_address (str): + I_p_address (str): IP address that this forwarding rule serves. When a client sends traffic to this IP address, the forwarding rule directs the traffic to the target that you specify in the @@ -6707,7 +7655,7 @@ class ForwardingRule(proto.Message): For Private Service Connect forwarding rules that forward traffic to Google APIs, IP address must be provided. - i_p_protocol (google.cloud.compute_v1.types.ForwardingRule.IPProtocol): + I_p_protocol (google.cloud.compute_v1.types.ForwardingRule.IPProtocol): The IP protocol to which this rule applies. For protocol forwarding, valid options are TCP, UDP, ESP, @@ -6726,6 +7674,45 @@ class ForwardingRule(proto.Message): load balancing scheme is EXTERNAL and only TCP is valid. - Network Load Balancing: The load balancing scheme is EXTERNAL, and one of TCP or UDP is valid. + all_ports (bool): + This field is used along with the backend_service field for + internal load balancing or with the target field for + internal TargetInstance. This field cannot be used with port + or portRange fields. + + When the load balancing scheme is INTERNAL and protocol is + TCP/UDP, specify this field to allow packets addressed to + any ports will be forwarded to the backends configured with + this forwarding rule. + allow_global_access (bool): + This field is used along with the backend_service field for + internal load balancing or with the target field for + internal TargetInstance. If the field is set to TRUE, + clients can access ILB from all regions. Otherwise only + allows access from clients in the same region as the + internal load balancer. + backend_service (str): + Identifies the backend service to which the + forwarding rule sends traffic. Required for + Internal TCP/UDP Load Balancing and Network Load + Balancing; must be omitted for all other load + balancer types. + creation_timestamp (str): + [Output Only] Creation timestamp in RFC3339 text format. + description (str): + An optional description of this resource. + Provide this property when you create the + resource. + fingerprint (str): + Fingerprint of this resource. A hash of the + contents stored in this object. This field is + used in optimistic locking. This field will be + ignored when inserting a ForwardingRule. Include + the fingerprint in patch request to ensure that + you do not overwrite changes that were applied + from another concurrent request. To see the + latest fingerprint, make a get() request to + retrieve a ForwardingRule. id (str): [Output Only] The unique identifier for the resource. This identifier is defined by the server. @@ -6746,6 +7733,23 @@ class ForwardingRule(proto.Message): kind (str): [Output Only] Type of the resource. Always compute#forwardingRule for Forwarding Rule resources. + label_fingerprint (str): + A fingerprint for the labels being applied to + this resource, 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 ForwardingRule. + labels (Sequence[google.cloud.compute_v1.types.ForwardingRule.LabelsEntry]): + Labels for this resource. These can only be + added or modified by the setLabels method. Each + label key/value pair must comply with RFC1035. + Label values may be empty. load_balancing_scheme (google.cloud.compute_v1.types.ForwardingRule.LoadBalancingScheme): Specifies the forwarding rule type. @@ -6854,6 +7858,9 @@ class ForwardingRule(proto.Message): For more information, see `Port specifications `__. + psc_connection_id (str): + [Output Only] The PSC connection id of the PSC Forwarding + Rule. region (str): [Output Only] URL of the region where the regional forwarding rule resides. This field is not applicable to @@ -6862,6 +7869,12 @@ class ForwardingRule(proto.Message): the request body. self_link (str): [Output Only] Server-defined URL for the resource. + service_directory_registrations (Sequence[google.cloud.compute_v1.types.ForwardingRuleServiceDirectoryRegistration]): + Service Directory resources to register this + forwarding rule with. Currently, only supports a + single Service Directory resource. It is only + supported for Internal TCP/UDP Load Balancing + and Internal HTTP(S) Load Balancing. service_label (str): An optional prefix to the service name for this Forwarding Rule. If specified, the prefix is the first label of the @@ -6892,27 +7905,7 @@ class ForwardingRule(proto.Message): is in custom subnet mode, a subnetwork must be specified. target (str): - The URL of the target resource to receive the matched - traffic. For regional forwarding rules, this target must be - in the same region as the forwarding rule. For global - forwarding rules, this target must be a global load - balancing resource. The forwarded traffic must be of a type - appropriate to the target object. For more information, see - the "Target" column in `Port - specifications `__. - For Private Service Connect forwarding rules that forward - traffic to Google APIs, provide the name of a supported - Google API bundle. Currently, the supported Google API - bundles include: - - - vpc-sc - GCP APIs that support VPC Service Controls. For - more information about which APIs support VPC Service - Controls, refer to VPC-SC supported products and - limitations. - - all-apis - All GCP APIs. For more information about which - APIs are supported with this bundle, refer to Private - Google Access-specific domains and VIPs. """ class IPProtocol(proto.Enum): @@ -6992,22 +7985,24 @@ class NetworkTier(proto.Enum): PREMIUM = 399530551 STANDARD = 484642493 + I_p_address = proto.Field(proto.STRING, number=42976943, optional=True,) + I_p_protocol = proto.Field( + proto.ENUM, number=488094525, optional=True, enum=IPProtocol, + ) all_ports = proto.Field(proto.BOOL, number=445175796, optional=True,) allow_global_access = proto.Field(proto.BOOL, number=499409674, optional=True,) backend_service = proto.Field(proto.STRING, number=306946058, optional=True,) creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) description = proto.Field(proto.STRING, number=422937596, optional=True,) fingerprint = proto.Field(proto.STRING, number=234678500, optional=True,) - i_p_address = proto.Field(proto.STRING, number=522591951, optional=True,) - i_p_protocol = proto.Field( - proto.ENUM, number=323774237, optional=True, enum=IPProtocol, - ) id = proto.Field(proto.STRING, number=3355, optional=True,) ip_version = proto.Field( proto.ENUM, number=294959552, optional=True, enum=IpVersion, ) is_mirroring_collector = proto.Field(proto.BOOL, number=119255164, optional=True,) kind = proto.Field(proto.STRING, number=3292052, optional=True,) + label_fingerprint = proto.Field(proto.STRING, number=178124825, optional=True,) + labels = proto.MapField(proto.STRING, proto.STRING, number=500195327,) load_balancing_scheme = proto.Field( proto.ENUM, number=363890244, optional=True, enum=LoadBalancingScheme, ) @@ -7021,8 +8016,14 @@ class NetworkTier(proto.Enum): ) port_range = proto.Field(proto.STRING, number=217518079, optional=True,) ports = proto.RepeatedField(proto.STRING, number=106854418,) + psc_connection_id = proto.Field(proto.STRING, number=292082397, optional=True,) region = proto.Field(proto.STRING, number=138946292, optional=True,) self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + service_directory_registrations = proto.RepeatedField( + proto.MESSAGE, + number=223549694, + message="ForwardingRuleServiceDirectoryRegistration", + ) service_label = proto.Field(proto.STRING, number=417008874, optional=True,) service_name = proto.Field(proto.STRING, number=359880149, optional=True,) subnetwork = proto.Field(proto.STRING, number=307827694, optional=True,) @@ -7234,10 +8235,9 @@ class NetworkEndpoint(proto.Message): VM instance in the network that the network endpoint group belongs to will be used. port (int): - Optional port number of network endpoint. If not specified - and the NetworkEndpointGroup.network_endpoint_type is - GCE_IP_PORT, the defaultPort for the network endpoint group - will be used. + Optional port number of network endpoint. If + not specified, the defaultPort for the network + endpoint group will be used. """ annotations = proto.MapField(proto.STRING, proto.STRING, number=112032548,) @@ -7271,36 +8271,6 @@ class GlobalNetworkEndpointGroupsDetachEndpointsRequest(proto.Message): ) -class GlobalSetLabelsRequest(proto.Message): - r""" - Attributes: - label_fingerprint (str): - The fingerprint of the previous set of labels - for this resource, used to detect conflicts. 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 when updating or - changing labels, otherwise the request will fail - with error 412 conditionNotMet. Make a get() - request to the resource to get the latest - fingerprint. - labels (Sequence[google.cloud.compute_v1.types.GlobalSetLabelsRequest.LabelsEntry]): - A list of labels to apply for this resource. Each label key - & value must 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. - For example, "webserver-frontend": "images". A label value - can also be empty (e.g. "my-label": ""). - """ - - label_fingerprint = proto.Field(proto.STRING, number=178124825, optional=True,) - labels = proto.MapField(proto.STRING, proto.STRING, number=500195327,) - - class Policy(proto.Message): r"""An Identity and Access Management (IAM) policy, which specifies access controls for Google Cloud resources. @@ -7425,6 +8395,62 @@ class Policy(proto.Message): version = proto.Field(proto.INT32, number=351608024, optional=True,) +class GlobalOrganizationSetPolicyRequest(proto.Message): + r""" + Attributes: + bindings (Sequence[google.cloud.compute_v1.types.Binding]): + Flatten Policy to create a backward + compatible wire-format. Deprecated. Use 'policy' + to specify bindings. + etag (str): + Flatten Policy to create a backward + compatible wire-format. Deprecated. Use 'policy' + to specify the etag. + policy (google.cloud.compute_v1.types.Policy): + REQUIRED: The complete policy to be applied + to the 'resource'. The size of the policy is + limited to a few 10s of KB. An empty policy is + in general a valid policy but certain services + (like Projects) might reject them. + """ + + bindings = proto.RepeatedField(proto.MESSAGE, number=403251854, message="Binding",) + etag = proto.Field(proto.STRING, number=3123477, optional=True,) + policy = proto.Field( + proto.MESSAGE, number=91071794, optional=True, message="Policy", + ) + + +class GlobalSetLabelsRequest(proto.Message): + r""" + Attributes: + label_fingerprint (str): + The fingerprint of the previous set of labels + for this resource, used to detect conflicts. 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 when updating or + changing labels, otherwise the request will fail + with error 412 conditionNotMet. Make a get() + request to the resource to get the latest + fingerprint. + labels (Sequence[google.cloud.compute_v1.types.GlobalSetLabelsRequest.LabelsEntry]): + A list of labels to apply for this resource. Each label key + & value must 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. + For example, "webserver-frontend": "images". A label value + can also be empty (e.g. "my-label": ""). + """ + + label_fingerprint = proto.Field(proto.STRING, number=178124825, optional=True,) + labels = proto.MapField(proto.STRING, proto.STRING, number=500195327,) + + class GlobalSetPolicyRequest(proto.Message): r""" Attributes: @@ -7974,12 +9000,13 @@ class HealthCheck(proto.Message): 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. + and comply with RFC1035. For example, a name that is 1-63 + characters long, matches the regular expression + ``[a-z]([-a-z0-9]*[a-z0-9])?``, and otherwise complies with + RFC1035. This regular expression describes a name where the + first character is a lowercase letter, and all following + characters are a dash, lowercase letter, or digit, except + the last character, which isn't a dash. region (str): [Output Only] Region where the health check resides. Not applicable to global health checks. @@ -8628,8 +9655,8 @@ class HttpHeaderMatch(proto.Message): regex_match (str): The value of the header must match the regular expression specified in regexMatch. For regular expression grammar, - please see: en.cppreference.com/w/cpp/regex/ecmascript For - matching against a port specified in the HTTP request, use a + please see: github.com/google/re2/wiki/Syntax For matching + against a port specified in the HTTP request, use a headerMatch with headerName set to PORT and a regular expression that satisfies the RFC2616 Host header's port specifier. Only one of exactMatch, prefixMatch, suffixMatch, @@ -8677,10 +9704,10 @@ class HttpQueryParameterMatch(proto.Message): The queryParameterMatch matches if the value of the parameter matches the regular expression specified by regexMatch. For the regular expression grammar, please see - en.cppreference.com/w/cpp/regex/ecmascript Only one of - presentMatch, exactMatch or regexMatch must be set. Note - that regexMatch only applies when the loadBalancingScheme is - set to INTERNAL_SELF_MANAGED. + github.com/google/re2/wiki/Syntax Only one of presentMatch, + exactMatch or regexMatch must be set. Note that regexMatch + only applies when the loadBalancingScheme is set to + INTERNAL_SELF_MANAGED. """ exact_match = proto.Field(proto.STRING, number=457641093, optional=True,) @@ -8936,6 +9963,19 @@ class HttpRouteAction(proto.Message): fault_injection_policy. Not supported when the URL map is bound to target gRPC proxy that has validateForProxyless field set to true. + max_stream_duration (google.cloud.compute_v1.types.Duration): + Specifies the maximum duration (timeout) for streams on the + selected route. Unlike the timeout field where the timeout + duration starts from the time the request has been fully + processed (i.e. end-of-stream), the duration in this field + is computed from the beginning of the stream until the + response has been completely processed, including all + retries. A stream that does not complete in this duration is + closed. If not specified, will use the largest + maxStreamDuration among all backend services associated with + the route. This field is only allowed if the Url map is used + with backend services with loadBalancingScheme set to + INTERNAL_SELF_MANAGED. request_mirror_policy (google.cloud.compute_v1.types.RequestMirrorPolicy): Specifies the policy on how requests intended for the route's backends are shadowed to a @@ -8992,6 +10032,9 @@ class HttpRouteAction(proto.Message): fault_injection_policy = proto.Field( proto.MESSAGE, number=412781079, optional=True, message="HttpFaultInjection", ) + max_stream_duration = proto.Field( + proto.MESSAGE, number=61428376, optional=True, message="Duration", + ) request_mirror_policy = proto.Field( proto.MESSAGE, number=220196866, optional=True, message="RequestMirrorPolicy", ) @@ -9072,11 +10115,11 @@ class HttpRouteRuleMatch(proto.Message): request must satisfy the regular expression specified in regexMatch after removing any query parameters and anchor supplied with the original URL. For regular expression - grammar please see - en.cppreference.com/w/cpp/regex/ecmascript Only one of - prefixMatch, fullPathMatch or regexMatch must be specified. - Note that regexMatch only applies to Loadbalancers that have - their loadBalancingScheme set to INTERNAL_SELF_MANAGED. + grammar please see github.com/google/re2/wiki/Syntax Only + one of prefixMatch, fullPathMatch or regexMatch must be + specified. Note that regexMatch only applies to + Loadbalancers that have their loadBalancingScheme set to + INTERNAL_SELF_MANAGED. """ full_path_match = proto.Field(proto.STRING, number=214598875, optional=True,) @@ -9315,6 +10358,8 @@ class Image(proto.Message): except the last character, which cannot be a dash. raw_disk (google.cloud.compute_v1.types.RawDisk): The parameters of the raw disk image. + satisfies_pzs (bool): + [Output Only] Reserved for future use. self_link (str): [Output Only] Server-defined URL for the resource. shielded_instance_initial_state (google.cloud.compute_v1.types.InitialStateConfig): @@ -9433,6 +10478,7 @@ class Status(proto.Enum): raw_disk = proto.Field( proto.MESSAGE, number=503113556, optional=True, message="RawDisk", ) + satisfies_pzs = proto.Field(proto.BOOL, number=480964267, optional=True,) self_link = proto.Field(proto.STRING, number=456214797, optional=True,) shielded_instance_initial_state = proto.Field( proto.MESSAGE, number=192356867, optional=True, message="InitialStateConfig", @@ -9542,8 +10588,10 @@ class NetworkInterface(proto.Message): when inserting an Instance or adding a NetworkInterface. An up-to-date fingerprint must be provided in order to update the - NetworkInterface, otherwise the request will - fail with error 412 conditionNotMet. + NetworkInterface. The request will fail with + error 400 Bad Request if the fingerprint is not + provided, or 412 Precondition Failed if the + fingerprint is out of date. ipv6_address (str): [Output Only] An IPv6 internal network address for this network interface. @@ -9653,7 +10701,7 @@ class ConsumeReservationType(proto.Enum): class Scheduling(proto.Message): - r"""Sets the scheduling options for an Instance. NextID: 13 + r"""Sets the scheduling options for an Instance. NextID: 20 Attributes: automatic_restart (bool): Specifies whether the instance should be @@ -9795,6 +10843,9 @@ class Instance(proto.Message): resource_for {$api_version}.instances ==) Attributes: + advanced_machine_features (google.cloud.compute_v1.types.AdvancedMachineFeatures): + Controls for advanced machine-related + behavior features. can_ip_forward (bool): Allows this instance to send and receive packets with non-matching destination or source @@ -9922,6 +10973,8 @@ class Instance(proto.Message): can consume from. resource_policies (Sequence[str]): Resource policies applied to this instance. + satisfies_pzs (bool): + [Output Only] Reserved for future use. scheduling (google.cloud.compute_v1.types.Scheduling): Sets the scheduling options for this instance. @@ -9993,6 +11046,12 @@ class Status(proto.Enum): SUSPENDING = 514206246 TERMINATED = 250018339 + advanced_machine_features = proto.Field( + proto.MESSAGE, + number=409646002, + optional=True, + message="AdvancedMachineFeatures", + ) can_ip_forward = proto.Field(proto.BOOL, number=467731324, optional=True,) confidential_instance_config = proto.Field( proto.MESSAGE, @@ -10038,6 +11097,7 @@ class Status(proto.Enum): proto.MESSAGE, number=157850683, optional=True, message="ReservationAffinity", ) resource_policies = proto.RepeatedField(proto.STRING, number=22220385,) + satisfies_pzs = proto.Field(proto.BOOL, number=480964267, optional=True,) scheduling = proto.Field( proto.MESSAGE, number=386688404, optional=True, message="Scheduling", ) @@ -10497,14 +11557,16 @@ class InstanceGroupManagerUpdatePolicy(proto.Message): max_surge (google.cloud.compute_v1.types.FixedOrPercent): The maximum number of instances that can be created above the specified targetSize during - the update process. By default, a fixed value of - 1 is used. This value can be either a fixed - number or a percentage if the instance group has - 10 or more instances. If you set a percentage, - the number of instances will be rounded up if - necessary. At least one of either maxSurge or - maxUnavailable must be greater than 0. Learn - more about maxSurge. + the update process. This value can be either a + fixed number or, if the group has 10 or more + instances, a percentage. If you set a + percentage, the number of instances is rounded + up if necessary. The default value for maxSurge + is a fixed value equal to the number of zones in + which the managed instance group operates. At + least one of either maxSurge or maxUnavailable + must be greater than 0. Learn more about + maxSurge. max_unavailable (google.cloud.compute_v1.types.FixedOrPercent): The maximum number of instances that can be unavailable during the update process. An @@ -10512,16 +11574,18 @@ class InstanceGroupManagerUpdatePolicy(proto.Message): following conditions are satisfied: - The instance's status is RUNNING. - If there is a health check on the instance - group, the instance's liveness health check - result must be HEALTHY at least once. If there - is no health check on the group, then the - instance only needs to have a status of RUNNING - to be considered available. By default, a fixed - value of 1 is used. This value can be either a - fixed number or a percentage if the instance - group has 10 or more instances. If you set a - percentage, the number of instances will be - rounded up if necessary. + group, the instance's health check status must + be HEALTHY at least once. If there is no health + check on the group, then the instance only needs + to have a status of RUNNING to be considered + available. This value can be either a fixed + number or, if the group has 10 or more + instances, a percentage. If you set a + percentage, the number of instances is rounded + up if necessary. The default value for + maxUnavailable is a fixed value equal to the + number of zones in which the managed instance + group operates. At least one of either maxSurge or maxUnavailable must be greater than 0. Learn more about maxUnavailable. @@ -11768,136 +12832,6 @@ class InstanceMoveRequest(proto.Message): target_instance = proto.Field(proto.STRING, number=289769347, optional=True,) -class InstanceProperties(proto.Message): - r""" - Attributes: - can_ip_forward (bool): - Enables instances created based on these - properties to send packets with source IP - addresses other than their own and receive - packets with destination IP addresses other than - their own. If these instances will be used as an - IP gateway or it will be set as the next-hop in - a Route resource, specify true. If unsure, leave - this set to false. See the Enable IP forwarding - documentation for more information. - confidential_instance_config (google.cloud.compute_v1.types.ConfidentialInstanceConfig): - Specifies the Confidential Instance options. - description (str): - An optional text description for the - instances that are created from these - properties. - disks (Sequence[google.cloud.compute_v1.types.AttachedDisk]): - An array of disks that are associated with - the instances that are created from these - properties. - guest_accelerators (Sequence[google.cloud.compute_v1.types.AcceleratorConfig]): - A list of guest accelerator cards' type and - count to use for instances created from these - properties. - labels (Sequence[google.cloud.compute_v1.types.InstanceProperties.LabelsEntry]): - Labels to apply to instances that are created - from these properties. - machine_type (str): - The machine type to use for instances that - are created from these properties. - metadata (google.cloud.compute_v1.types.Metadata): - The metadata key/value pairs to assign to - instances that are created from these - properties. These pairs can consist of custom - metadata or predefined keys. See Project and - instance metadata for more information. - min_cpu_platform (str): - Minimum cpu/platform to be used by instances. - The instance may be scheduled on the specified - or newer cpu/platform. Applicable values are the - friendly names of CPU platforms, such as - minCpuPlatform: "Intel Haswell" or - minCpuPlatform: "Intel Sandy Bridge". For more - information, read Specifying a Minimum CPU - Platform. - network_interfaces (Sequence[google.cloud.compute_v1.types.NetworkInterface]): - An array of network access configurations for - this interface. - private_ipv6_google_access (google.cloud.compute_v1.types.InstanceProperties.PrivateIpv6GoogleAccess): - The private IPv6 google access type for VMs. If not - specified, use INHERIT_FROM_SUBNETWORK as default. - reservation_affinity (google.cloud.compute_v1.types.ReservationAffinity): - Specifies the reservations that instances can - consume from. - resource_policies (Sequence[str]): - Resource policies (names, not ULRs) applied - to instances created from these properties. - scheduling (google.cloud.compute_v1.types.Scheduling): - Specifies the scheduling options for the - instances that are created from these - properties. - service_accounts (Sequence[google.cloud.compute_v1.types.ServiceAccount]): - A list of service accounts with specified - scopes. Access tokens for these service accounts - are available to the instances that are created - from these properties. Use metadata queries to - obtain the access tokens for these instances. - shielded_instance_config (google.cloud.compute_v1.types.ShieldedInstanceConfig): - - tags (google.cloud.compute_v1.types.Tags): - A list of tags to apply to the instances that - are created from these properties. The tags - identify valid sources or targets for network - firewalls. The setTags method can modify this - list of tags. Each tag within the list must - comply with RFC1035. - """ - - class PrivateIpv6GoogleAccess(proto.Enum): - r"""The private IPv6 google access type for VMs. If not specified, use - INHERIT_FROM_SUBNETWORK as default. - """ - UNDEFINED_PRIVATE_IPV6_GOOGLE_ACCESS = 0 - ENABLE_BIDIRECTIONAL_ACCESS_TO_GOOGLE = 427975994 - ENABLE_OUTBOUND_VM_ACCESS_TO_GOOGLE = 288210263 - INHERIT_FROM_SUBNETWORK = 530256959 - - can_ip_forward = proto.Field(proto.BOOL, number=467731324, optional=True,) - confidential_instance_config = proto.Field( - proto.MESSAGE, - number=490637685, - optional=True, - message="ConfidentialInstanceConfig", - ) - description = proto.Field(proto.STRING, number=422937596, optional=True,) - disks = proto.RepeatedField(proto.MESSAGE, number=95594102, message="AttachedDisk",) - guest_accelerators = proto.RepeatedField( - proto.MESSAGE, number=463595119, message="AcceleratorConfig", - ) - labels = proto.MapField(proto.STRING, proto.STRING, number=500195327,) - machine_type = proto.Field(proto.STRING, number=227711026, optional=True,) - metadata = proto.Field( - proto.MESSAGE, number=86866735, optional=True, message="Metadata", - ) - min_cpu_platform = proto.Field(proto.STRING, number=242912759, optional=True,) - network_interfaces = proto.RepeatedField( - proto.MESSAGE, number=52735243, message="NetworkInterface", - ) - private_ipv6_google_access = proto.Field( - proto.ENUM, number=48277006, optional=True, enum=PrivateIpv6GoogleAccess, - ) - reservation_affinity = proto.Field( - proto.MESSAGE, number=157850683, optional=True, message="ReservationAffinity", - ) - resource_policies = proto.RepeatedField(proto.STRING, number=22220385,) - scheduling = proto.Field( - proto.MESSAGE, number=386688404, optional=True, message="Scheduling", - ) - service_accounts = proto.RepeatedField( - proto.MESSAGE, number=277537328, message="ServiceAccount", - ) - shielded_instance_config = proto.Field( - proto.MESSAGE, number=12862901, optional=True, message="ShieldedInstanceConfig", - ) - tags = proto.Field(proto.MESSAGE, number=3552281, optional=True, message="Tags",) - - class SourceInstanceParams(proto.Message): r"""A specification of the parameters to use when creating the instance template from a source instance. @@ -12032,6 +12966,56 @@ class InstancesAddResourcePoliciesRequest(proto.Message): resource_policies = proto.RepeatedField(proto.STRING, number=22220385,) +class InstancesGetEffectiveFirewallsResponseEffectiveFirewallPolicy(proto.Message): + r""" + Attributes: + display_name (str): + [Output Only] Deprecated, please use short name instead. The + display name of the firewall policy. + name (str): + [Output Only] The name of the firewall policy. + rules (Sequence[google.cloud.compute_v1.types.FirewallPolicyRule]): + The rules that apply to the network. + short_name (str): + [Output Only] The short name of the firewall policy. + type_ (google.cloud.compute_v1.types.InstancesGetEffectiveFirewallsResponseEffectiveFirewallPolicy.Type): + [Output Only] The type of the firewall policy. + """ + + class Type(proto.Enum): + r"""[Output Only] The type of the firewall policy.""" + UNDEFINED_TYPE = 0 + HIERARCHY = 69902869 + UNSPECIFIED = 526786327 + + display_name = proto.Field(proto.STRING, number=4473832, optional=True,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + rules = proto.RepeatedField( + proto.MESSAGE, number=108873975, message="FirewallPolicyRule", + ) + short_name = proto.Field(proto.STRING, number=492051566, optional=True,) + type_ = proto.Field(proto.ENUM, number=3575610, optional=True, enum=Type,) + + +class InstancesGetEffectiveFirewallsResponse(proto.Message): + r""" + Attributes: + firewall_policys (Sequence[google.cloud.compute_v1.types.InstancesGetEffectiveFirewallsResponseEffectiveFirewallPolicy]): + Effective firewalls from firewall policies. + firewalls (Sequence[google.cloud.compute_v1.types.Firewall]): + Effective firewalls on the instance. + """ + + firewall_policys = proto.RepeatedField( + proto.MESSAGE, + number=410985794, + message="InstancesGetEffectiveFirewallsResponseEffectiveFirewallPolicy", + ) + firewalls = proto.RepeatedField( + proto.MESSAGE, number=272245619, message="Firewall", + ) + + class InstancesRemoveResourcePoliciesRequest(proto.Message): r""" Attributes: @@ -12591,6 +13575,20 @@ class InterconnectAttachment(proto.Message): that the provisioned circuit will lie in the specified domain. If not specified, the value will default to AVAILABILITY_DOMAIN_ANY. + encryption (google.cloud.compute_v1.types.InterconnectAttachment.Encryption): + Indicates the user-supplied encryption option + of this interconnect attachment: - NONE is the + default value, which means that the attachment + carries unencrypted traffic. VMs can send + traffic to, or receive traffic from, this type + of attachment. - IPSEC indicates that the + attachment carries only traffic encrypted by an + IPsec device such as an HA VPN gateway. VMs + cannot directly send traffic to, or receive + traffic from, such an attachment. To use IPsec- + encrypted Cloud Interconnect, create the + attachment using this option. Not currently + available in all Interconnect locations. google_reference_id (str): [Output Only] Google reference ID, to be used when raising support tickets with Google or otherwise to debug backend @@ -12602,6 +13600,28 @@ class InterconnectAttachment(proto.Message): URL of the underlying Interconnect object that this attachment's traffic will traverse through. + ipsec_internal_addresses (Sequence[str]): + URL of addresses that have been reserved for + the interconnect attachment, Used only for + interconnect attachment that has the encryption + option as IPSEC. The addresses must be RFC 1918 + IP address ranges. When creating HA VPN gateway + over the interconnect attachment, if the + attachment is configured to use an RFC 1918 IP + address, then the VPN gateway's IP address will + be allocated from the IP address range specified + here. For example, if the HA VPN gateway's + interface 0 is paired to this interconnect + attachment, then an RFC 1918 IP address for the + VPN gateway interface 0 will be allocated from + the IP address specified for this interconnect + attachment. If this field is not specified for + interconnect attachment that has encryption + option as IPSEC, later on when creating HA VPN + gateway on this interconnect attachment, the HA + VPN gateway's IP address will be allocated from + regional external IP address pool. Not currently + available in all Interconnect locations. kind (str): [Output Only] Type of the resource. Always compute#interconnectAttachment for interconnect attachments. @@ -12755,6 +13775,22 @@ class EdgeAvailabilityDomain(proto.Enum): AVAILABILITY_DOMAIN_2 = 349552091 AVAILABILITY_DOMAIN_ANY = 375256373 + class Encryption(proto.Enum): + r"""Indicates the user-supplied encryption option of this + interconnect attachment: - NONE is the default value, which + means that the attachment carries unencrypted traffic. VMs can + send traffic to, or receive traffic from, this type of + attachment. - IPSEC indicates that the attachment carries only + traffic encrypted by an IPsec device such as an HA VPN gateway. + VMs cannot directly send traffic to, or receive traffic from, + such an attachment. To use IPsec-encrypted Cloud Interconnect, + create the attachment using this option. Not currently available + in all Interconnect locations. + """ + UNDEFINED_ENCRYPTION = 0 + IPSEC = 69882282 + NONE = 2402104 + class OperationalStatus(proto.Enum): r"""[Output Only] The current status of whether or not this interconnect attachment is functional, which can take one of the following @@ -12833,9 +13869,13 @@ class Type(proto.Enum): edge_availability_domain = proto.Field( proto.ENUM, number=71289510, optional=True, enum=EdgeAvailabilityDomain, ) + encryption = proto.Field( + proto.ENUM, number=97980291, optional=True, enum=Encryption, + ) google_reference_id = proto.Field(proto.STRING, number=534944469, optional=True,) id = proto.Field(proto.STRING, number=3355, optional=True,) interconnect = proto.Field(proto.STRING, number=224601230, optional=True,) + ipsec_internal_addresses = proto.RepeatedField(proto.STRING, number=407648565,) kind = proto.Field(proto.STRING, number=3292052, optional=True,) mtu = proto.Field(proto.INT32, number=108462, optional=True,) name = proto.Field(proto.STRING, number=3373707, optional=True,) @@ -13609,6 +14649,26 @@ class LocalDisk(proto.Message): disk_type = proto.Field(proto.STRING, number=93009052, optional=True,) +class LocationPolicyLocation(proto.Message): + r""" + Attributes: + preference (google.cloud.compute_v1.types.LocationPolicyLocation.Preference): + Preference for a given locaction: ALLOW or + DENY. + """ + + class Preference(proto.Enum): + r"""Preference for a given locaction: ALLOW or DENY.""" + UNDEFINED_PREFERENCE = 0 + ALLOW = 62368553 + DENY = 2094604 + PREFERENCE_UNSPECIFIED = 496219571 + + preference = proto.Field( + proto.ENUM, number=150781147, optional=True, enum=Preference, + ) + + class LogConfigCloudAuditOptions(proto.Message): r"""Write a Cloud Audit log Attributes: @@ -14203,6 +15263,13 @@ class Network(proto.Message): resource_for {$api_version}.networks ==) Attributes: + I_pv4_range (str): + Deprecated in favor of subnet mode networks. + The range of internal addresses that are legal + on this network. This range is a CIDR + specification, for example: 192.168.0.0/16. + Provided by the client when the network is + created. auto_create_subnetworks (bool): Must be set to create a VPC network. If not set, a legacy network is created. @@ -14223,13 +15290,6 @@ class Network(proto.Message): gateway_i_pv4 (str): [Output Only] The gateway address for default routing out of the network, selected by GCP. - i_pv4_range (str): - Deprecated in favor of subnet mode networks. - The range of internal addresses that are legal - on this network. This range is a CIDR - specification, for example: 192.168.0.0/16. - Provided by the client when the network is - created. id (str): [Output Only] The unique identifier for the resource. This identifier is defined by the server. @@ -14264,11 +15324,11 @@ class Network(proto.Message): subnetworks in this VPC network. """ + I_pv4_range = proto.Field(proto.STRING, number=59234358, optional=True,) auto_create_subnetworks = proto.Field(proto.BOOL, number=256156690, optional=True,) creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) description = proto.Field(proto.STRING, number=422937596, optional=True,) gateway_i_pv4 = proto.Field(proto.STRING, number=178678877, optional=True,) - i_pv4_range = proto.Field(proto.STRING, number=1978454, optional=True,) id = proto.Field(proto.STRING, number=3355, optional=True,) kind = proto.Field(proto.STRING, number=3292052, optional=True,) mtu = proto.Field(proto.INT32, number=108462, optional=True,) @@ -14472,6 +15532,7 @@ class NetworkEndpointType(proto.Enum): INTERNET_IP_PORT, or SERVERLESS. """ UNDEFINED_NETWORK_ENDPOINT_TYPE = 0 + GCE_VM_IP = 401880793 GCE_VM_IP_PORT = 501838375 INTERNET_FQDN_PORT = 404154477 INTERNET_IP_PORT = 477719963 @@ -14805,6 +15866,57 @@ class NetworksAddPeeringRequest(proto.Message): peer_network = proto.Field(proto.STRING, number=500625489, optional=True,) +class NetworksGetEffectiveFirewallsResponseEffectiveFirewallPolicy(proto.Message): + r""" + Attributes: + display_name (str): + [Output Only] Deprecated, please use short name instead. The + display name of the firewall policy. + name (str): + [Output Only] The name of the firewall policy. + rules (Sequence[google.cloud.compute_v1.types.FirewallPolicyRule]): + The rules that apply to the network. + short_name (str): + [Output Only] The short name of the firewall policy. + type_ (google.cloud.compute_v1.types.NetworksGetEffectiveFirewallsResponseEffectiveFirewallPolicy.Type): + [Output Only] The type of the firewall policy. + """ + + class Type(proto.Enum): + r"""[Output Only] The type of the firewall policy.""" + UNDEFINED_TYPE = 0 + HIERARCHY = 69902869 + NETWORK = 413984270 + UNSPECIFIED = 526786327 + + display_name = proto.Field(proto.STRING, number=4473832, optional=True,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + rules = proto.RepeatedField( + proto.MESSAGE, number=108873975, message="FirewallPolicyRule", + ) + short_name = proto.Field(proto.STRING, number=492051566, optional=True,) + type_ = proto.Field(proto.ENUM, number=3575610, optional=True, enum=Type,) + + +class NetworksGetEffectiveFirewallsResponse(proto.Message): + r""" + Attributes: + firewall_policys (Sequence[google.cloud.compute_v1.types.NetworksGetEffectiveFirewallsResponseEffectiveFirewallPolicy]): + Effective firewalls from firewall policy. + firewalls (Sequence[google.cloud.compute_v1.types.Firewall]): + Effective firewalls on the network. + """ + + firewall_policys = proto.RepeatedField( + proto.MESSAGE, + number=410985794, + message="NetworksGetEffectiveFirewallsResponseEffectiveFirewallPolicy", + ) + firewalls = proto.RepeatedField( + proto.MESSAGE, number=272245619, message="Firewall", + ) + + class NetworksRemovePeeringRequest(proto.Message): r""" Attributes: @@ -14907,6 +16019,12 @@ class NodeGroup(proto.Message): kind (str): [Output Only] The type of the resource. Always compute#nodeGroup for node group. + location_hint (str): + An opaque location hint used to place the Node close to + other resources. This field is for use by internal tools + that use the public API. The location hint here on the + NodeGroup overrides any location_hint present in the + NodeTemplate. maintenance_policy (google.cloud.compute_v1.types.NodeGroup.MaintenancePolicy): Specifies how to handle instances when a node in the group undergoes maintenance. Set to one of: DEFAULT, @@ -14969,6 +16087,7 @@ class Status(proto.Enum): fingerprint = proto.Field(proto.STRING, number=234678500, optional=True,) id = proto.Field(proto.STRING, number=3355, optional=True,) kind = proto.Field(proto.STRING, number=3292052, optional=True,) + location_hint = proto.Field(proto.STRING, number=350519505, optional=True,) maintenance_policy = proto.Field( proto.ENUM, number=528327646, optional=True, enum=MaintenancePolicy, ) @@ -15118,6 +16237,8 @@ class NodeGroupNode(proto.Message): The name of the node. node_type (str): The type of this node. + satisfies_pzs (bool): + [Output Only] Reserved for future use. server_binding (google.cloud.compute_v1.types.ServerBinding): Binding properties for the physical server. server_id (str): @@ -15152,6 +16273,7 @@ class Status(proto.Enum): instances = proto.RepeatedField(proto.STRING, number=29097598,) name = proto.Field(proto.STRING, number=3373707, optional=True,) node_type = proto.Field(proto.STRING, number=465832791, optional=True,) + satisfies_pzs = proto.Field(proto.BOOL, number=480964267, optional=True,) server_binding = proto.Field( proto.MESSAGE, number=208179593, optional=True, message="ServerBinding", ) @@ -15900,6 +17022,10 @@ class Operation(proto.Message): ``compute#operation`` for Operation resources. name (str): [Output Only] Name of the operation. + operation_group_id (str): + [Output Only] An ID that represents a group of operations, + such as when a group of operations results from a + ``bulkInsert`` API request. operation_type (str): [Output Only] The type of operation, such as ``insert``, ``update``, or ``delete``, and so on. @@ -15965,6 +17091,7 @@ class Status(proto.Enum): insert_time = proto.Field(proto.STRING, number=433722515, optional=True,) kind = proto.Field(proto.STRING, number=3292052, optional=True,) name = proto.Field(proto.STRING, number=3373707, optional=True,) + operation_group_id = proto.Field(proto.STRING, number=40171187, optional=True,) operation_type = proto.Field(proto.STRING, number=177650450, optional=True,) progress = proto.Field(proto.INT32, number=72663597, optional=True,) region = proto.Field(proto.STRING, number=138946292, optional=True,) @@ -16098,6 +17225,13 @@ class PacketMirroringForwardingRuleInfo(proto.Message): class PacketMirroringFilter(proto.Message): r""" Attributes: + I_p_protocols (Sequence[str]): + Protocols that apply as filter on mirrored + traffic. If no protocols are specified, all + traffic that matches the specified CIDR ranges + is mirrored. If neither cidrRanges nor + IPProtocols is specified, all traffic is + mirrored. cidr_ranges (Sequence[str]): IP CIDR ranges that apply as filter on the source (ingress) or destination (egress) IP in @@ -16109,13 +17243,6 @@ class PacketMirroringFilter(proto.Message): direction (google.cloud.compute_v1.types.PacketMirroringFilter.Direction): Direction of traffic to mirror, either INGRESS, EGRESS, or BOTH. The default is BOTH. - i_p_protocols (Sequence[str]): - Protocols that apply as filter on mirrored - traffic. If no protocols are specified, all - traffic that matches the specified CIDR ranges - is mirrored. If neither cidrRanges nor - IPProtocols is specified, all traffic is - mirrored. """ class Direction(proto.Enum): @@ -16127,11 +17254,11 @@ class Direction(proto.Enum): EGRESS = 432880501 INGRESS = 516931221 + I_p_protocols = proto.RepeatedField(proto.STRING, number=98544854,) cidr_ranges = proto.RepeatedField(proto.STRING, number=487901697,) direction = proto.Field( proto.ENUM, number=111150975, optional=True, enum=Direction, ) - i_p_protocols = proto.RepeatedField(proto.STRING, number=373325046,) class PacketMirroringMirroredResourceInfo(proto.Message): @@ -16758,14 +17885,18 @@ class Metric(proto.Enum): AUTOSCALERS = 471248988 BACKEND_BUCKETS = 137626846 BACKEND_SERVICES = 269623753 + C2D_CPUS = 508182517 C2_CPUS = 317601211 COMMITMENTS = 456141790 COMMITTED_A2_CPUS = 59330902 + COMMITTED_C2D_CPUS = 282390904 COMMITTED_C2_CPUS = 223725528 COMMITTED_CPUS = 292394702 + COMMITTED_E2_CPUS = 388120154 COMMITTED_LICENSES = 357606869 COMMITTED_LOCAL_SSD_TOTAL_GB = 308393480 COMMITTED_MEMORY_OPTIMIZED_CPUS = 489057886 + COMMITTED_N2A_CPUS = 40064304 COMMITTED_N2D_CPUS = 125951757 COMMITTED_N2_CPUS = 322589603 COMMITTED_NVIDIA_A100_GPUS = 375799445 @@ -16777,6 +17908,7 @@ class Metric(proto.Enum): CPUS = 2075595 CPUS_ALL_REGIONS = 470911149 DISKS_TOTAL_GB = 353520543 + E2_CPUS = 481995837 EXTERNAL_NETWORK_LB_FORWARDING_RULES = 374298265 EXTERNAL_PROTOCOL_FORWARDING_RULES = 63478888 EXTERNAL_VPN_GATEWAYS = 272457134 @@ -16804,6 +17936,7 @@ class Metric(proto.Enum): M1_CPUS = 37203366 M2_CPUS = 65832517 MACHINE_IMAGES = 446986640 + N2A_CPUS = 265855917 N2D_CPUS = 351743370 N2_CPUS = 416465286 NETWORKS = 485481477 @@ -16821,6 +17954,7 @@ class Metric(proto.Enum): NVIDIA_T4_VWS_GPUS = 319813039 NVIDIA_V100_GPUS = 129293095 PACKET_MIRRORINGS = 15578407 + PD_EXTREME_TOTAL_PROVISIONED_IOPS = 69593965 PREEMPTIBLE_CPUS = 251184841 PREEMPTIBLE_LOCAL_SSD_GB = 260819336 PREEMPTIBLE_NVIDIA_A100_GPUS = 68832784 @@ -17103,6 +18237,404 @@ class NetworkTier(proto.Enum): ) +class PublicAdvertisedPrefixPublicDelegatedPrefix(proto.Message): + r"""Represents a CIDR range which can be used to assign + addresses. + + Attributes: + ip_range (str): + The IP address range of the public delegated + prefix + name (str): + The name of the public delegated prefix + project (str): + The project number of the public delegated + prefix + region (str): + The region of the public delegated prefix if + it is regional. If absent, the prefix is global. + status (str): + The status of the public delegated prefix. + Possible values are: INITIALIZING: The public + delegated prefix is being initialized and + addresses cannot be created yet. ANNOUNCED: The + public delegated prefix is active. + """ + + ip_range = proto.Field(proto.STRING, number=145092645, optional=True,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + project = proto.Field(proto.STRING, number=227560217, optional=True,) + region = proto.Field(proto.STRING, number=138946292, optional=True,) + status = proto.Field(proto.STRING, number=181260274, optional=True,) + + +class PublicAdvertisedPrefix(proto.Message): + r"""A public advertised prefix represents an aggregated IP prefix + or netblock which customers bring to cloud. The IP prefix is a + single unit of route advertisement and is announced globally to + the internet. + + Attributes: + creation_timestamp (str): + [Output Only] Creation timestamp in RFC3339 text format. + description (str): + An optional description of this resource. + Provide this property when you create the + resource. + dns_verification_ip (str): + The IPv4 address to be used for reverse DNS + verification. + fingerprint (str): + Fingerprint of this resource. A hash of the + contents stored in this object. This field is + used in optimistic locking. This field will be + ignored when inserting a new + PublicAdvertisedPrefix. An up-to-date + fingerprint must be provided in order to update + the PublicAdvertisedPrefix, otherwise the + request will fail with error 412 + conditionNotMet. To see the latest fingerprint, + make a get() request to retrieve a + PublicAdvertisedPrefix. + id (str): + [Output Only] The unique identifier for the resource type. + The server generates this identifier. + ip_cidr_range (str): + The IPv4 address range, in CIDR format, + represented by this public advertised prefix. + kind (str): + [Output Only] Type of the resource. Always + compute#publicAdvertisedPrefix for public advertised + prefixes. + 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. + public_delegated_prefixs (Sequence[google.cloud.compute_v1.types.PublicAdvertisedPrefixPublicDelegatedPrefix]): + [Output Only] The list of public delegated prefixes that + exist for this public advertised prefix. + self_link (str): + [Output Only] Server-defined URL for the resource. + shared_secret (str): + [Output Only] The shared secret to be used for reverse DNS + verification. + status (google.cloud.compute_v1.types.PublicAdvertisedPrefix.Status): + The status of the public advertised prefix. + """ + + class Status(proto.Enum): + r"""The status of the public advertised prefix.""" + UNDEFINED_STATUS = 0 + INITIAL = 518841124 + PREFIX_CONFIGURATION_COMPLETE = 480889551 + PREFIX_CONFIGURATION_IN_PROGRESS = 378550961 + PREFIX_REMOVAL_IN_PROGRESS = 284375783 + PTR_CONFIGURED = 513497167 + REVERSE_DNS_LOOKUP_FAILED = 295755183 + VALIDATED = 66197998 + + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + dns_verification_ip = proto.Field(proto.STRING, number=241011381, optional=True,) + fingerprint = proto.Field(proto.STRING, number=234678500, optional=True,) + id = proto.Field(proto.STRING, number=3355, optional=True,) + ip_cidr_range = proto.Field(proto.STRING, number=98117322, optional=True,) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + public_delegated_prefixs = proto.RepeatedField( + proto.MESSAGE, + number=425811723, + message="PublicAdvertisedPrefixPublicDelegatedPrefix", + ) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + shared_secret = proto.Field(proto.STRING, number=381932490, optional=True,) + status = proto.Field(proto.ENUM, number=181260274, optional=True, enum=Status,) + + +class PublicAdvertisedPrefixList(proto.Message): + r""" + Attributes: + id (str): + [Output Only] Unique identifier for the resource; defined by + the server. + items (Sequence[google.cloud.compute_v1.types.PublicAdvertisedPrefix]): + A list of PublicAdvertisedPrefix resources. + kind (str): + [Output Only] Type of the resource. Always + compute#publicAdvertisedPrefix for public advertised + prefixes. + 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. + self_link (str): + [Output Only] Server-defined URL for this resource. + warning (google.cloud.compute_v1.types.Warning): + [Output Only] Informational warning message. + """ + + @property + def raw_page(self): + return self + + id = proto.Field(proto.STRING, number=3355, optional=True,) + items = proto.RepeatedField( + proto.MESSAGE, number=100526016, message="PublicAdvertisedPrefix", + ) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) + next_page_token = proto.Field(proto.STRING, number=79797525, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", + ) + + +class PublicDelegatedPrefixPublicDelegatedSubPrefix(proto.Message): + r"""Represents a sub PublicDelegatedPrefix. + Attributes: + delegatee_project (str): + Name of the project scoping this + PublicDelegatedSubPrefix. + description (str): + An optional description of this resource. + Provide this property when you create the + resource. + ip_cidr_range (str): + The IPv4 address range, in CIDR format, + represented by this sub public delegated prefix. + is_address (bool): + Whether the sub prefix is delegated to create + Address resources in the delegatee project. + name (str): + The name of the sub public delegated prefix. + region (str): + [Output Only] The region of the sub public delegated prefix + if it is regional. If absent, the sub prefix is global. + status (google.cloud.compute_v1.types.PublicDelegatedPrefixPublicDelegatedSubPrefix.Status): + [Output Only] The status of the sub public delegated prefix. + """ + + class Status(proto.Enum): + r"""[Output Only] The status of the sub public delegated prefix.""" + UNDEFINED_STATUS = 0 + ACTIVE = 314733318 + INACTIVE = 270421099 + + delegatee_project = proto.Field(proto.STRING, number=414860634, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + ip_cidr_range = proto.Field(proto.STRING, number=98117322, optional=True,) + is_address = proto.Field(proto.BOOL, number=352617951, optional=True,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + region = proto.Field(proto.STRING, number=138946292, optional=True,) + status = proto.Field(proto.ENUM, number=181260274, optional=True, enum=Status,) + + +class PublicDelegatedPrefix(proto.Message): + r"""A PublicDelegatedPrefix resource represents an IP block + within a PublicAdvertisedPrefix that is configured within a + single cloud scope (global or region). IPs in the block can be + allocated to resources within that scope. Public delegated + prefixes may be further broken up into smaller IP blocks in the + same scope as the parent block. + + Attributes: + creation_timestamp (str): + [Output Only] Creation timestamp in RFC3339 text format. + description (str): + An optional description of this resource. + Provide this property when you create the + resource. + fingerprint (str): + Fingerprint of this resource. A hash of the + contents stored in this object. This field is + used in optimistic locking. This field will be + ignored when inserting a new + PublicDelegatedPrefix. An up-to-date fingerprint + must be provided in order to update the + PublicDelegatedPrefix, otherwise the request + will fail with error 412 conditionNotMet. To + see the latest fingerprint, make a get() request + to retrieve a PublicDelegatedPrefix. + id (str): + [Output Only] The unique identifier for the resource type. + The server generates this identifier. + ip_cidr_range (str): + The IPv4 address range, in CIDR format, + represented by this public delegated prefix. + is_live_migration (bool): + If true, the prefix will be live migrated. + kind (str): + [Output Only] Type of the resource. Always + compute#publicDelegatedPrefix for public delegated prefixes. + 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. + parent_prefix (str): + The URL of parent prefix. Either + PublicAdvertisedPrefix or PublicDelegatedPrefix. + public_delegated_sub_prefixs (Sequence[google.cloud.compute_v1.types.PublicDelegatedPrefixPublicDelegatedSubPrefix]): + The list of sub public delegated prefixes + that exist for this public delegated prefix. + region (str): + [Output Only] URL of the region where the public delegated + prefix resides. This field applies only to the region + resource. You must specify this field as part of the HTTP + request URL. It is not settable as a field in the request + body. + self_link (str): + [Output Only] Server-defined URL for the resource. + status (google.cloud.compute_v1.types.PublicDelegatedPrefix.Status): + [Output Only] The status of the public delegated prefix. + """ + + class Status(proto.Enum): + r"""[Output Only] The status of the public delegated prefix.""" + UNDEFINED_STATUS = 0 + ANNOUNCED = 365103355 + DELETING = 528602024 + INITIALIZING = 306588749 + + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + fingerprint = proto.Field(proto.STRING, number=234678500, optional=True,) + id = proto.Field(proto.STRING, number=3355, optional=True,) + ip_cidr_range = proto.Field(proto.STRING, number=98117322, optional=True,) + is_live_migration = proto.Field(proto.BOOL, number=511823856, optional=True,) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + parent_prefix = proto.Field(proto.STRING, number=15233991, optional=True,) + public_delegated_sub_prefixs = proto.RepeatedField( + proto.MESSAGE, + number=188940044, + message="PublicDelegatedPrefixPublicDelegatedSubPrefix", + ) + region = proto.Field(proto.STRING, number=138946292, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + status = proto.Field(proto.ENUM, number=181260274, optional=True, enum=Status,) + + +class PublicDelegatedPrefixesScopedList(proto.Message): + r""" + Attributes: + public_delegated_prefixes (Sequence[google.cloud.compute_v1.types.PublicDelegatedPrefix]): + [Output Only] A list of PublicDelegatedPrefixes contained in + this scope. + warning (google.cloud.compute_v1.types.Warning): + [Output Only] Informational warning which replaces the list + of public delegated prefixes when the list is empty. + """ + + public_delegated_prefixes = proto.RepeatedField( + proto.MESSAGE, number=315261206, message="PublicDelegatedPrefix", + ) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", + ) + + +class PublicDelegatedPrefixAggregatedList(proto.Message): + r""" + Attributes: + id (str): + [Output Only] Unique identifier for the resource; defined by + the server. + items (Sequence[google.cloud.compute_v1.types.PublicDelegatedPrefixAggregatedList.ItemsEntry]): + A list of PublicDelegatedPrefixesScopedList + resources. + kind (str): + [Output Only] Type of the resource. Always + compute#publicDelegatedPrefixAggregatedList for aggregated + lists of public delegated prefixes. + 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. + self_link (str): + [Output Only] Server-defined URL for this resource. + unreachables (Sequence[str]): + [Output Only] Unreachable resources. + warning (google.cloud.compute_v1.types.Warning): + [Output Only] Informational warning message. + """ + + @property + def raw_page(self): + return self + + id = proto.Field(proto.STRING, number=3355, optional=True,) + items = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=100526016, + message="PublicDelegatedPrefixesScopedList", + ) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) + next_page_token = proto.Field(proto.STRING, number=79797525, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + unreachables = proto.RepeatedField(proto.STRING, number=243372063,) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", + ) + + +class PublicDelegatedPrefixList(proto.Message): + r""" + Attributes: + id (str): + [Output Only] Unique identifier for the resource; defined by + the server. + items (Sequence[google.cloud.compute_v1.types.PublicDelegatedPrefix]): + A list of PublicDelegatedPrefix resources. + kind (str): + [Output Only] Type of the resource. Always + compute#publicDelegatedPrefixList for public delegated + prefixes. + 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. + self_link (str): + [Output Only] Server-defined URL for this resource. + warning (google.cloud.compute_v1.types.Warning): + [Output Only] Informational warning message. + """ + + @property + def raw_page(self): + return self + + id = proto.Field(proto.STRING, number=3355, optional=True,) + items = proto.RepeatedField( + proto.MESSAGE, number=100526016, message="PublicDelegatedPrefix", + ) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) + next_page_token = proto.Field(proto.STRING, number=79797525, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", + ) + + class Region(proto.Message): r"""Represents a Region resource. @@ -17132,6 +18664,8 @@ class Region(proto.Message): [Output Only] Server-defined URL for the resource. status (google.cloud.compute_v1.types.Region.Status): [Output Only] Status of the region, either UP or DOWN. + supports_pzs (bool): + [Output Only] Reserved for future use. zones (Sequence[str]): [Output Only] A list of zones available in this region, in the form of resource URLs. @@ -17154,6 +18688,7 @@ class Status(proto.Enum): quotas = proto.RepeatedField(proto.MESSAGE, number=125341947, message="Quota",) self_link = proto.Field(proto.STRING, number=456214797, optional=True,) status = proto.Field(proto.ENUM, number=181260274, optional=True, enum=Status,) + supports_pzs = proto.Field(proto.BOOL, number=83983214, optional=True,) zones = proto.RepeatedField(proto.STRING, number=116085319,) @@ -18087,6 +19622,9 @@ class ResourcePolicy(proto.Message): id (str): [Output Only] The unique identifier for the resource. This identifier is defined by the server. + instance_schedule_policy (google.cloud.compute_v1.types.ResourcePolicyInstanceSchedulePolicy): + Resource policy for scheduling instance + operations. kind (str): [Output Only] Type of the resource. Always compute#resource_policies for resource policies. @@ -18101,6 +19639,8 @@ class ResourcePolicy(proto.Message): digit, except the last character, which cannot be a dash. region (str): + resource_status (google.cloud.compute_v1.types.ResourcePolicyResourceStatus): + [Output Only] The system status of the resource policy. self_link (str): [Output Only] Server-defined fully-qualified URL for this resource. @@ -18116,6 +19656,7 @@ class Status(proto.Enum): UNDEFINED_STATUS = 0 CREATING = 455564985 DELETING = 528602024 + EXPIRED = 482489093 INVALID = 530283991 READY = 77848963 @@ -18128,9 +19669,21 @@ class Status(proto.Enum): message="ResourcePolicyGroupPlacementPolicy", ) id = proto.Field(proto.STRING, number=3355, optional=True,) + instance_schedule_policy = proto.Field( + proto.MESSAGE, + number=344877104, + optional=True, + message="ResourcePolicyInstanceSchedulePolicy", + ) kind = proto.Field(proto.STRING, number=3292052, optional=True,) name = proto.Field(proto.STRING, number=3373707, optional=True,) region = proto.Field(proto.STRING, number=138946292, optional=True,) + resource_status = proto.Field( + proto.MESSAGE, + number=249429315, + optional=True, + message="ResourcePolicyResourceStatus", + ) self_link = proto.Field(proto.STRING, number=456214797, optional=True,) snapshot_schedule_policy = proto.Field( proto.MESSAGE, @@ -18192,6 +19745,68 @@ class Collocation(proto.Enum): vm_count = proto.Field(proto.INT32, number=261463431, optional=True,) +class ResourcePolicyInstanceSchedulePolicy(proto.Message): + r"""An InstanceSchedulePolicy specifies when and how frequent + certain operations are performed on the instance. + + Attributes: + expiration_time (str): + The expiration time of the schedule. The + timestamp is an RFC3339 string. + start_time (str): + The start time of the schedule. The timestamp + is an RFC3339 string. + time_zone (str): + Specifies the time zone to be used in interpreting + Schedule.schedule. The value of this field must be a time + zone name from the tz database: + http://en.wikipedia.org/wiki/Tz_database. + vm_start_schedule (google.cloud.compute_v1.types.ResourcePolicyInstanceSchedulePolicySchedule): + Specifies the schedule for starting + instances. + vm_stop_schedule (google.cloud.compute_v1.types.ResourcePolicyInstanceSchedulePolicySchedule): + Specifies the schedule for stopping + instances. + """ + + expiration_time = proto.Field(proto.STRING, number=230299229, optional=True,) + start_time = proto.Field(proto.STRING, number=37467274, optional=True,) + time_zone = proto.Field(proto.STRING, number=36848094, optional=True,) + vm_start_schedule = proto.Field( + proto.MESSAGE, + number=17762396, + optional=True, + message="ResourcePolicyInstanceSchedulePolicySchedule", + ) + vm_stop_schedule = proto.Field( + proto.MESSAGE, + number=426242732, + optional=True, + message="ResourcePolicyInstanceSchedulePolicySchedule", + ) + + +class ResourcePolicyResourceStatus(proto.Message): + r"""Contains output only fields. Use this sub-message for all + output fields set on ResourcePolicy. The internal structure of + this "status" field should mimic the structure of ResourcePolicy + proto specification. + + Attributes: + instance_schedule_policy (google.cloud.compute_v1.types.ResourcePolicyResourceStatusInstanceSchedulePolicyStatus): + [Output Only] Specifies a set of output values reffering to + the instance_schedule_policy system status. This field + should have the same name as corresponding policy field. + """ + + instance_schedule_policy = proto.Field( + proto.MESSAGE, + number=344877104, + optional=True, + message="ResourcePolicyResourceStatusInstanceSchedulePolicyStatus", + ) + + class ResourcePolicySnapshotSchedulePolicy(proto.Message): r"""A snapshot schedule policy specifies when and how frequently snapshots are to be created for the target disk. Also specifies @@ -18323,6 +19938,17 @@ class ResourcePolicyHourlyCycle(proto.Message): start_time = proto.Field(proto.STRING, number=37467274, optional=True,) +class ResourcePolicyInstanceSchedulePolicySchedule(proto.Message): + r"""Schedule for an instance operation. + Attributes: + schedule (str): + Specifies the frequency for the operation, + using the unix-cron format. + """ + + schedule = proto.Field(proto.STRING, number=375820951, optional=True,) + + class ResourcePolicyList(proto.Message): r""" Attributes: @@ -18366,6 +19992,22 @@ def raw_page(self): ) +class ResourcePolicyResourceStatusInstanceSchedulePolicyStatus(proto.Message): + r""" + Attributes: + last_run_start_time (str): + [Output Only] The last time the schedule successfully ran. + The timestamp is an RFC3339 string. + next_run_start_time (str): + [Output Only] The next time the schedule is planned to run. + The actual time might be slightly different. The timestamp + is an RFC3339 string. + """ + + last_run_start_time = proto.Field(proto.STRING, number=303069063, optional=True,) + next_run_start_time = proto.Field(proto.STRING, number=318642570, optional=True,) + + class ResourcePolicySnapshotSchedulePolicyRetentionPolicy(proto.Message): r"""Policy for retention of scheduled snapshots. Attributes: @@ -18712,13 +20354,11 @@ class RouterBgpPeer(proto.Message): - ALL_SUBNETS: Advertises all available subnets, including peer VPC subnets. - ALL_VPC_SUBNETS: Advertises the router's own VPC subnets. - - ALL_PEER_VPC_SUBNETS: Advertises peer subnets of the - router's VPC network. Note that this field can only be - populated if advertise_mode is CUSTOM and overrides the - list defined for the router (in the "bgp" message). These - groups are advertised in addition to any specified - prefixes. Leave this field blank to advertise no custom - groups. + Note that this field can only be populated if + advertise_mode is CUSTOM and overrides the list defined + for the router (in the "bgp" message). These groups are + advertised in addition to any specified prefixes. Leave + this field blank to advertise no custom groups. advertised_ip_ranges (Sequence[google.cloud.compute_v1.types.RouterAdvertisedIpRange]): User-specified list of individual IP ranges to advertise in custom mode. This field can only be populated if @@ -19050,6 +20690,12 @@ class Router(proto.Message): An optional description of this resource. Provide this property when you create the resource. + encrypted_interconnect_router (bool): + Field to indicate if a router is dedicated to + use with encrypted Interconnect Attachment + (IPsec-encrypted Cloud Interconnect feature). + Not currently available in all Interconnect + locations. id (str): [Output Only] The unique identifier for the resource. This identifier is defined by the server. @@ -19090,6 +20736,9 @@ class Router(proto.Message): ) creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) description = proto.Field(proto.STRING, number=422937596, optional=True,) + encrypted_interconnect_router = proto.Field( + proto.BOOL, number=297996575, optional=True, + ) id = proto.Field(proto.STRING, number=3355, optional=True,) interfaces = proto.RepeatedField( proto.MESSAGE, number=12073562, message="RouterInterface", @@ -19516,7 +21165,7 @@ class SecurityPolicyRule(proto.Message): Attributes: action (str): - The Action to preform when the client + The Action to perform when the client connection triggers the rule. Can currently be either "allow" or "deny()" where valid values for status are 403, 404, and 502. @@ -19883,6 +21532,11 @@ class Snapshot(proto.Message): [Output Only] A list of public visible licenses that apply to this snapshot. This can be because the original image had licenses attached (such as a Windows image). + location_hint (str): + An opaque location hint used to place the + snapshot close to other resources. This field is + for use by internal tools that use the public + API. name (str): Name of the resource; provided by the client when the resource is created. The name must be 1-63 characters long, @@ -19892,6 +21546,8 @@ class Snapshot(proto.Message): 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. + satisfies_pzs (bool): + [Output Only] Reserved for future use. self_link (str): [Output Only] Server-defined URL for the resource. snapshot_encryption_key (google.cloud.compute_v1.types.CustomerEncryptionKey): @@ -19973,7 +21629,9 @@ class StorageBytesStatus(proto.Enum): labels = proto.MapField(proto.STRING, proto.STRING, number=500195327,) license_codes = proto.RepeatedField(proto.STRING, number=45482664,) licenses = proto.RepeatedField(proto.STRING, number=337642578,) + location_hint = proto.Field(proto.STRING, number=350519505, optional=True,) name = proto.Field(proto.STRING, number=3373707, optional=True,) + satisfies_pzs = proto.Field(proto.BOOL, number=480964267, optional=True,) self_link = proto.Field(proto.STRING, number=456214797, optional=True,) snapshot_encryption_key = proto.Field( proto.MESSAGE, number=43334526, optional=True, message="CustomerEncryptionKey", @@ -20035,9 +21693,10 @@ class SslCertificateManagedSslCertificate(proto.Message): [Output only] Detailed statuses of the domains specified for managed certificate resource. domains (Sequence[str]): - The domains for which a managed SSL - certificate will be generated. Currently only - single-domain certs are supported. + The domains for which a managed SSL certificate will be + generated. Each Google-managed SSL certificate supports up + to the `maximum number of domains per Google-managed SSL + certificate `__. status (google.cloud.compute_v1.types.SslCertificateManagedSslCertificate.Status): [Output only] Status of the managed certificate resource. """ @@ -20541,7 +22200,7 @@ class SubnetworkLogConfig(proto.Message): Can only be specified if VPC flow logs for this subnetwork is enabled. Configures whether all, none or a subset of metadata fields should be added to the reported VPC flow - logs. Default is INCLUDE_ALL_METADATA. + logs. Default is EXCLUDE_ALL_METADATA. metadata_fields (Sequence[str]): Can only be specified if VPC flow logs for this subnetwork is enabled and "metadata" was set to CUSTOM_METADATA. @@ -20566,7 +22225,7 @@ class Metadata(proto.Enum): r"""Can only be specified if VPC flow logs for this subnetwork is enabled. Configures whether all, none or a subset of metadata fields should be added to the reported VPC flow logs. Default is - INCLUDE_ALL_METADATA. + EXCLUDE_ALL_METADATA. """ UNDEFINED_METADATA = 0 CUSTOM_METADATA = 62450749 @@ -20592,9 +22251,8 @@ class SubnetworkSecondaryRange(proto.Message): property when you create the subnetwork. Ranges must be unique and non-overlapping with all primary and secondary IP ranges within a - network. Only IPv4 is supported. This may be a - RFC 1918 IP range, or a privately, non-RFC 1918 - IP range, not belonging to Google. + network. Only IPv4 is supported. The range can + be any range listed in the Valid ranges list. range_name (str): The name associated with this subnetwork secondary range, used when adding an alias IP @@ -20652,10 +22310,10 @@ class Subnetwork(proto.Message): 10.0.0.0/8 or 100.64.0.0/10. Ranges must be unique and non-overlapping within a network. Only IPv4 is supported. This field is set at - resource creation time. This may be a RFC 1918 - IP range, or a privately routed, non-RFC 1918 IP - range, not belonging to Google. The range can be - expanded after creation using expandIpCidrRange. + resource creation time. The range can be any + range listed in the Valid ranges list. The range + can be expanded after creation using + expandIpCidrRange. ipv6_cidr_range (str): [Output Only] The range of internal IPv6 addresses that are owned by this subnetwork. @@ -20733,9 +22391,7 @@ class Subnetwork(proto.Message): have the purpose set to INTERNAL_HTTPS_LOAD_BALANCER and indicates that connections to the load balancer are being drained. A subnetwork that is draining cannot be used or - modified until it reaches a status of READY CREATING: - Subnetwork is provisioning DELETING: Subnetwork is being - deleted UPDATING: Subnetwork is being updated + modified until it reaches a status of READY """ class PrivateIpv6GoogleAccess(proto.Enum): @@ -20783,8 +22439,6 @@ class State(proto.Enum): to INTERNAL_HTTPS_LOAD_BALANCER and indicates that connections to the load balancer are being drained. A subnetwork that is draining cannot be used or modified until it reaches a status of READY - CREATING: Subnetwork is provisioning DELETING: Subnetwork is being - deleted UPDATING: Subnetwork is being updated """ UNDEFINED_STATE = 0 DRAINING = 480455402 @@ -20949,10 +22603,11 @@ class TargetGrpcProxy(proto.Message): r"""Represents a Target gRPC Proxy resource. A target gRPC proxy is a component of load balancers intended for - load balancing gRPC traffic. Global forwarding rules reference a - target gRPC proxy. The Target gRPC Proxy references a URL map which - specifies how traffic routes to gRPC backend services. (== - resource_for {$api_version}.targetGrpcProxies ==) + load balancing gRPC traffic. Only global forwarding rules with load + balancing scheme INTERNAL_SELF_MANAGED can reference a target gRPC + proxy. The target gRPC Proxy references a URL map that specifies how + traffic is routed to gRPC backend services. (== resource_for + {$api_version}.targetGrpcProxies ==) Attributes: creation_timestamp (str): @@ -21296,6 +22951,17 @@ class TargetHttpsProxy(proto.Message): An optional description of this resource. Provide this property when you create the resource. + fingerprint (str): + Fingerprint of this resource. A hash of the + contents stored in this object. This field is + used in optimistic locking. This field will be + ignored when inserting a TargetHttpsProxy. An + up-to-date fingerprint must be provided in order + to patch the TargetHttpsProxy; otherwise, the + request will fail with error 412 + conditionNotMet. To see the latest fingerprint, + make a get() request to retrieve the + TargetHttpsProxy. id (str): [Output Only] The unique identifier for the resource. This identifier is defined by the server. @@ -21337,7 +23003,6 @@ class TargetHttpsProxy(proto.Message): quic-override is set to DISABLE, the load balancer doesn't use QUIC. - If the quic- override flag is not specified, NONE is implied. - - region (str): [Output Only] URL of the region where the regional TargetHttpsProxy resides. This field is not applicable to @@ -21383,7 +23048,7 @@ class QuicOverride(proto.Enum): manages whether QUIC is used. - When quic-override is set to ENABLE, the load balancer uses QUIC when possible. - When quic- override is set to DISABLE, the load balancer doesn't use QUIC. - - If the quic-override flag is not specified, NONE is implied. - + - If the quic-override flag is not specified, NONE is implied. """ UNDEFINED_QUIC_OVERRIDE = 0 DISABLE = 241807048 @@ -21393,6 +23058,7 @@ class QuicOverride(proto.Enum): authorization_policy = proto.Field(proto.STRING, number=33945528, optional=True,) creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) description = proto.Field(proto.STRING, number=422937596, optional=True,) + fingerprint = proto.Field(proto.STRING, number=234678500, optional=True,) id = proto.Field(proto.STRING, number=3355, optional=True,) kind = proto.Field(proto.STRING, number=3292052, optional=True,) name = proto.Field(proto.STRING, number=3373707, optional=True,) @@ -21781,10 +23447,8 @@ class TargetPool(proto.Message): The URL of the HttpHealthCheck resource. A member instance in this pool is considered healthy if and only if the health checks pass. - An empty list means all member instances will be - considered healthy at all times. Only legacy - HttpHealthChecks are supported. Only one health - check may be specified. + Only legacy HttpHealthChecks are supported. Only + one health check may be specified. id (str): [Output Only] The unique identifier for the resource. This identifier is defined by the server. @@ -21832,6 +23496,7 @@ class SessionAffinity(proto.Enum): """ UNDEFINED_SESSION_AFFINITY = 0 CLIENT_IP = 345665051 + CLIENT_IP_NO_DESTINATION = 106122516 CLIENT_IP_PORT_PROTO = 221722926 CLIENT_IP_PROTO = 25322148 GENERATED_COOKIE = 370321204 @@ -22267,6 +23932,20 @@ class TargetTcpProxy(proto.Message): 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. + proxy_bind (bool): + This field only applies when the forwarding rule that + references this target proxy has a loadBalancingScheme set + to INTERNAL_SELF_MANAGED. + + When this field is set to true, Envoy proxies set up inbound + traffic interception and bind to the IP address and port + specified in the forwarding rule. This is generally useful + when using Traffic Director to configure Envoy as a gateway + or middle proxy (in other words, not a sidecar proxy). The + Envoy proxy listens for inbound requests and handles + requests when it receives them. + + The default is false. proxy_header (google.cloud.compute_v1.types.TargetTcpProxy.ProxyHeader): Specifies the type of proxy header to append before sending data to the backend, either NONE or PROXY_V1. The default is @@ -22290,6 +23969,7 @@ class ProxyHeader(proto.Enum): id = proto.Field(proto.STRING, number=3355, optional=True,) kind = proto.Field(proto.STRING, number=3292052, optional=True,) name = proto.Field(proto.STRING, number=3373707, optional=True,) + proxy_bind = proto.Field(proto.BOOL, number=286025582, optional=True,) proxy_header = proto.Field( proto.ENUM, number=160374142, optional=True, enum=ProxyHeader, ) @@ -22518,15 +24198,44 @@ def raw_page(self): ) +class UrlMapTestHeader(proto.Message): + r"""HTTP headers used in UrlMapTests. + Attributes: + name (str): + Header name. + value (str): + Header value. + """ + + name = proto.Field(proto.STRING, number=3373707, optional=True,) + value = proto.Field(proto.STRING, number=111972721, optional=True,) + + class TestFailure(proto.Message): r""" Attributes: + actual_output_url (str): + The actual output URL evaluated by load + balancer containing the scheme, host, path and + query parameters. + actual_redirect_response_code (int): + Actual HTTP status code for rule with ``urlRedirect`` + calculated by load balancer actual_service (str): BackendService or BackendBucket returned by load balancer. + expected_output_url (str): + The expected output URL evaluated by load + balancer containing the scheme, host, path and + query parameters. + expected_redirect_response_code (int): + Expected HTTP status code for rule with ``urlRedirect`` + calculated by load balancer expected_service (str): Expected BackendService or BackendBucket resource the given URL should be mapped to. + headers (Sequence[google.cloud.compute_v1.types.UrlMapTestHeader]): + HTTP headers of the request. host (str): Host portion of the URL. path (str): @@ -22534,8 +24243,19 @@ class TestFailure(proto.Message): the URL. """ + actual_output_url = proto.Field(proto.STRING, number=287075458, optional=True,) + actual_redirect_response_code = proto.Field( + proto.INT32, number=42926553, optional=True, + ) actual_service = proto.Field(proto.STRING, number=440379652, optional=True,) + expected_output_url = proto.Field(proto.STRING, number=433967384, optional=True,) + expected_redirect_response_code = proto.Field( + proto.INT32, number=18888047, optional=True, + ) expected_service = proto.Field(proto.STRING, number=133987374, optional=True,) + headers = proto.RepeatedField( + proto.MESSAGE, number=258436998, message="UrlMapTestHeader", + ) host = proto.Field(proto.STRING, number=3208616, optional=True,) path = proto.Field(proto.STRING, number=3433509, optional=True,) @@ -22568,6 +24288,33 @@ class UrlMapTest(proto.Message): Attributes: description (str): Description of this test case. + expected_output_url (str): + The expected output URL evaluated by load balancer + containing the scheme, host, path and query parameters. For + rules that forward requests to backends, the test passes + only when expectedOutputUrl matches the request forwarded by + load balancer to backends. For rules with urlRewrite, the + test verifies that the forwarded request matches hostRewrite + and pathPrefixRewrite in the urlRewrite action. When service + is specified, expectedOutputUrl`s scheme is ignored. For + rules with urlRedirect, the test passes only if + expectedOutputUrl matches the URL in the load balancer's + redirect response. If urlRedirect specifies https_redirect, + the test passes only if the scheme in expectedOutputUrl is + also set to https. If urlRedirect specifies strip_query, the + test passes only if expectedOutputUrl does not contain any + query parameters. expectedOutputUrl is optional when service + is specified. + expected_redirect_response_code (int): + For rules with urlRedirect, the test passes + only if expectedRedirectResponseCode matches the + HTTP status code in load balancer's redirect + response. expectedRedirectResponseCode cannot be + set when service is set. + headers (Sequence[google.cloud.compute_v1.types.UrlMapTestHeader]): + HTTP headers for this request. If headers + contains a host header, then host must also + match the header value. host (str): Host portion of the URL. If headers contains a host header, then host must also match the @@ -22582,6 +24329,13 @@ class UrlMapTest(proto.Message): """ description = proto.Field(proto.STRING, number=422937596, optional=True,) + expected_output_url = proto.Field(proto.STRING, number=433967384, optional=True,) + expected_redirect_response_code = proto.Field( + proto.INT32, number=18888047, optional=True, + ) + headers = proto.RepeatedField( + proto.MESSAGE, number=258436998, message="UrlMapTestHeader", + ) host = proto.Field(proto.STRING, number=3208616, optional=True,) path = proto.Field(proto.STRING, number=3433509, optional=True,) service = proto.Field(proto.STRING, number=373540533, optional=True,) @@ -22935,12 +24689,24 @@ class VpnGatewayVpnGatewayInterface(proto.Message): Attributes: id (int): The numeric ID of this VPN gateway interface. + interconnect_attachment (str): + URL of the interconnect attachment resource. + When the value of this field is present, the VPN + Gateway will be used for IPsec-encrypted Cloud + Interconnect; all Egress or Ingress traffic for + this VPN Gateway interface will go through the + specified interconnect attachment resource. Not + currently available in all Interconnect + locations. ip_address (str): [Output Only] The external IP address for this VPN gateway interface. """ id = proto.Field(proto.UINT32, number=3355, optional=True,) + interconnect_attachment = proto.Field( + proto.STRING, number=308135284, optional=True, + ) ip_address = proto.Field(proto.STRING, number=406272220, optional=True,) @@ -23350,7 +25116,7 @@ class VpnTunnel(proto.Message): ready to be used. - NO_INCOMING_PACKETS: No incoming packets from peer. - REJECTED: Tunnel configuration was rejected, can be - result of being blacklisted. + result of being denied access. - ALLOCATING_RESOURCES: Cloud VPN is in the process of allocating all required resources. - STOPPED: Tunnel is stopped due to its Forwarding Rules @@ -23395,7 +25161,7 @@ class Status(proto.Enum): be used. - NO_INCOMING_PACKETS: No incoming packets from peer. - REJECTED: Tunnel configuration was rejected, can be result of - being blacklisted. + being denied access. - ALLOCATING_RESOURCES: Cloud VPN is in the process of allocating all required resources. - STOPPED: Tunnel is stopped due to its Forwarding Rules being @@ -23636,6 +25402,8 @@ class Zone(proto.Message): [Output Only] Server-defined URL for the resource. status (google.cloud.compute_v1.types.Zone.Status): [Output Only] Status of the zone, either UP or DOWN. + supports_pzs (bool): + [Output Only] Reserved for future use. """ class Status(proto.Enum): @@ -23656,6 +25424,7 @@ class Status(proto.Enum): region = proto.Field(proto.STRING, number=138946292, optional=True,) self_link = proto.Field(proto.STRING, number=456214797, optional=True,) status = proto.Field(proto.ENUM, number=181260274, optional=True, enum=Status,) + supports_pzs = proto.Field(proto.BOOL, number=83983214, optional=True,) class ZoneList(proto.Message): @@ -23813,8 +25582,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -23905,8 +25673,7 @@ 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 and the logic is the same - as today. + default value is false. zone (str): The name of the zone for this request. """ @@ -23992,8 +25759,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -24156,8 +25922,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -24241,8 +26006,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -24405,8 +26169,7 @@ class ListAutoscalersRequest(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 and the logic is the same - as today. + default value is false. zone (str): Name of the zone for this request. """ @@ -24718,8 +26481,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -24915,8 +26677,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -25130,8 +26891,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -25328,8 +27088,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -25420,8 +27179,7 @@ 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 and the logic is the same - as today. + default value is false. zone (str): The name of the zone for this request. """ @@ -25547,8 +27305,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -25708,8 +27465,8 @@ class InsertDiskRequest(proto.Message): exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). source_image (str): - Optional. Source image to restore onto a - disk. + Source image to restore onto a disk. This + field is optional. zone (str): The name of the zone for this request. """ @@ -25782,8 +27539,7 @@ 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 and the logic is the same - as today. + default value is false. zone (str): The name of the zone for this request. """ @@ -26105,8 +27861,7 @@ class ListExternalVpnGatewaysRequest(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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -26157,15 +27912,21 @@ class TestIamPermissionsExternalVpnGatewayRequest(proto.Message): ) -class DeleteFirewallRequest(proto.Message): - r"""A request message for Firewalls.Delete. See the method - description for details. +class AddAssociationFirewallPolicyRequest(proto.Message): + r"""A request message for FirewallPolicies.AddAssociation. See + the method description for details. Attributes: - firewall (str): - Name of the firewall rule to delete. - project (str): - Project ID for this request. + firewall_policy (str): + Name of the firewall policy to update. + firewall_policy_association_resource (google.cloud.compute_v1.types.FirewallPolicyAssociation): + The body resource for this request + replace_existing_association (bool): + Indicates whether or not to replace it if an + association of the attachment already exists. + This is false by default, in which case an error + will be returned if an association already + exists. request_id (str): An optional request ID to identify requests. Specify a unique request ID so that if you must @@ -26184,35 +27945,25 @@ class DeleteFirewallRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - firewall = proto.Field(proto.STRING, number=511016192,) - project = proto.Field(proto.STRING, number=227560217,) + firewall_policy = proto.Field(proto.STRING, number=498173265,) + firewall_policy_association_resource = proto.Field( + proto.MESSAGE, number=259546170, message="FirewallPolicyAssociation", + ) + replace_existing_association = proto.Field( + proto.BOOL, number=209541240, optional=True, + ) request_id = proto.Field(proto.STRING, number=37109963, optional=True,) -class GetFirewallRequest(proto.Message): - r"""A request message for Firewalls.Get. See the method - description for details. - - Attributes: - firewall (str): - Name of the firewall rule to return. - project (str): - Project ID for this request. - """ - - firewall = proto.Field(proto.STRING, number=511016192,) - project = proto.Field(proto.STRING, number=227560217,) - - -class InsertFirewallRequest(proto.Message): - r"""A request message for Firewalls.Insert. See the method - description for details. +class AddRuleFirewallPolicyRequest(proto.Message): + r"""A request message for FirewallPolicies.AddRule. See the + method description for details. Attributes: - firewall_resource (google.cloud.compute_v1.types.Firewall): + firewall_policy (str): + Name of the firewall policy to update. + firewall_policy_rule_resource (google.cloud.compute_v1.types.FirewallPolicyRule): 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 @@ -26231,95 +27982,52 @@ class InsertFirewallRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - firewall_resource = proto.Field(proto.MESSAGE, number=41425005, message="Firewall",) - project = proto.Field(proto.STRING, number=227560217,) + firewall_policy = proto.Field(proto.STRING, number=498173265,) + firewall_policy_rule_resource = proto.Field( + proto.MESSAGE, number=250523523, message="FirewallPolicyRule", + ) request_id = proto.Field(proto.STRING, number=37109963, optional=True,) -class ListFirewallsRequest(proto.Message): - r"""A request message for Firewalls.List. See the method - description for details. +class CloneRulesFirewallPolicyRequest(proto.Message): + r"""A request message for FirewallPolicies.CloneRules. See the + method description for details. Attributes: - filter (str): - A filter expression that filters resources listed in the - response. The expression must specify the field name, a - comparison operator, and the value that you want to use for - filtering. The value must be a string, a number, or a - boolean. The comparison 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``. - - 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)`` - 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``) - 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. - 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. - 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 and the logic is the same - as today. + firewall_policy (str): + Name of the firewall policy to update. + 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). + source_firewall_policy (str): + The firewall policy from which to copy rules. """ - filter = proto.Field(proto.STRING, number=336120696, optional=True,) - max_results = proto.Field(proto.UINT32, number=54715419, optional=True,) - order_by = proto.Field(proto.STRING, number=160562920, optional=True,) - page_token = proto.Field(proto.STRING, number=19994697, optional=True,) - project = proto.Field(proto.STRING, number=227560217,) - return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) + firewall_policy = proto.Field(proto.STRING, number=498173265,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + source_firewall_policy = proto.Field(proto.STRING, number=25013549, optional=True,) -class PatchFirewallRequest(proto.Message): - r"""A request message for Firewalls.Patch. See the method +class DeleteFirewallPolicyRequest(proto.Message): + r"""A request message for FirewallPolicies.Delete. See the method description for details. Attributes: - firewall (str): - Name of the firewall rule to patch. - firewall_resource (google.cloud.compute_v1.types.Firewall): - The body resource for this request - project (str): - Project ID for this request. + firewall_policy (str): + Name of the firewall policy to delete. request_id (str): An optional request ID to identify requests. Specify a unique request ID so that if you must @@ -26338,23 +28046,85 @@ class PatchFirewallRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - firewall = proto.Field(proto.STRING, number=511016192,) - firewall_resource = proto.Field(proto.MESSAGE, number=41425005, message="Firewall",) - project = proto.Field(proto.STRING, number=227560217,) + firewall_policy = proto.Field(proto.STRING, number=498173265,) request_id = proto.Field(proto.STRING, number=37109963, optional=True,) -class UpdateFirewallRequest(proto.Message): - r"""A request message for Firewalls.Update. See the method +class GetFirewallPolicyRequest(proto.Message): + r"""A request message for FirewallPolicies.Get. See the method description for details. Attributes: - firewall (str): - Name of the firewall rule to update. - firewall_resource (google.cloud.compute_v1.types.Firewall): + firewall_policy (str): + Name of the firewall policy to get. + """ + + firewall_policy = proto.Field(proto.STRING, number=498173265,) + + +class GetAssociationFirewallPolicyRequest(proto.Message): + r"""A request message for FirewallPolicies.GetAssociation. See + the method description for details. + + Attributes: + firewall_policy (str): + Name of the firewall policy to which the + queried rule belongs. + name (str): + The name of the association to get from the + firewall policy. + """ + + firewall_policy = proto.Field(proto.STRING, number=498173265,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + + +class GetIamPolicyFirewallPolicyRequest(proto.Message): + r"""A request message for FirewallPolicies.GetIamPolicy. See the + method description for details. + + Attributes: + options_requested_policy_version (int): + Requested IAM Policy version. + resource (str): + Name or id of the resource for this request. + """ + + options_requested_policy_version = proto.Field( + proto.INT32, number=499220029, optional=True, + ) + resource = proto.Field(proto.STRING, number=195806222,) + + +class GetRuleFirewallPolicyRequest(proto.Message): + r"""A request message for FirewallPolicies.GetRule. See the + method description for details. + + Attributes: + firewall_policy (str): + Name of the firewall policy to which the + queried rule belongs. + priority (int): + The priority of the rule to get from the + firewall policy. + """ + + firewall_policy = proto.Field(proto.STRING, number=498173265,) + priority = proto.Field(proto.INT32, number=445151652, optional=True,) + + +class InsertFirewallPolicyRequest(proto.Message): + r"""A request message for FirewallPolicies.Insert. See the method + description for details. + + Attributes: + firewall_policy_resource (google.cloud.compute_v1.types.FirewallPolicy): The body resource for this request - 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. request_id (str): An optional request ID to identify requests. Specify a unique request ID so that if you must @@ -26373,15 +28143,524 @@ class UpdateFirewallRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - firewall = proto.Field(proto.STRING, number=511016192,) - firewall_resource = proto.Field(proto.MESSAGE, number=41425005, message="Firewall",) - project = proto.Field(proto.STRING, number=227560217,) + firewall_policy_resource = proto.Field( + proto.MESSAGE, number=495049532, message="FirewallPolicy", + ) + parent_id = proto.Field(proto.STRING, number=459714768, optional=True,) request_id = proto.Field(proto.STRING, number=37109963, optional=True,) -class AggregatedListForwardingRulesRequest(proto.Message): - r"""A request message for ForwardingRules.AggregatedList. See the - method description for details. +class ListFirewallPoliciesRequest(proto.Message): + r"""A request message for FirewallPolicies.List. See the method + description for details. + + Attributes: + filter (str): + A filter expression that filters resources listed in the + response. The expression must specify the field name, a + comparison operator, and the value that you want to use for + filtering. The value must be a string, a number, or a + boolean. The comparison 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``. + + 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)`` + 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``) + 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. + page_token (str): + Specifies a page token to use. Set ``pageToken`` to the + ``nextPageToken`` returned by a previous list request to get + the next page of results. + parent_id (str): + Parent ID for this request. + return_partial_success (bool): + Opt-in for partial success behavior which + provides partial results in case of failure. The + default value is false. + """ + + filter = proto.Field(proto.STRING, number=336120696, optional=True,) + max_results = proto.Field(proto.UINT32, number=54715419, optional=True,) + order_by = proto.Field(proto.STRING, number=160562920, optional=True,) + page_token = proto.Field(proto.STRING, number=19994697, optional=True,) + parent_id = proto.Field(proto.STRING, number=459714768, optional=True,) + return_partial_success = 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. + + Attributes: + target_resource (str): + The target resource to list associations. It + is an organization, or a folder. + """ + + target_resource = proto.Field(proto.STRING, number=467318524, optional=True,) + + +class MoveFirewallPolicyRequest(proto.Message): + r"""A request message for FirewallPolicies.Move. See the method + description for details. + + Attributes: + firewall_policy (str): + Name of the firewall policy to update. + parent_id (str): + The new parent of the firewall policy. + 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). + """ + + firewall_policy = proto.Field(proto.STRING, number=498173265,) + parent_id = proto.Field(proto.STRING, number=459714768, optional=True,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + + +class PatchFirewallPolicyRequest(proto.Message): + r"""A request message for FirewallPolicies.Patch. See the method + description for details. + + Attributes: + firewall_policy (str): + Name of the firewall policy to update. + firewall_policy_resource (google.cloud.compute_v1.types.FirewallPolicy): + 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). + """ + + firewall_policy = proto.Field(proto.STRING, number=498173265,) + firewall_policy_resource = proto.Field( + proto.MESSAGE, number=495049532, message="FirewallPolicy", + ) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + + +class PatchRuleFirewallPolicyRequest(proto.Message): + r"""A request message for FirewallPolicies.PatchRule. See the + method description for details. + + Attributes: + firewall_policy (str): + Name of the firewall policy to update. + firewall_policy_rule_resource (google.cloud.compute_v1.types.FirewallPolicyRule): + The body resource for this request + priority (int): + The priority of the rule to patch. + 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). + """ + + firewall_policy = proto.Field(proto.STRING, number=498173265,) + firewall_policy_rule_resource = proto.Field( + proto.MESSAGE, number=250523523, message="FirewallPolicyRule", + ) + priority = proto.Field(proto.INT32, number=445151652, optional=True,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + + +class RemoveAssociationFirewallPolicyRequest(proto.Message): + r"""A request message for FirewallPolicies.RemoveAssociation. See + the method description for details. + + Attributes: + firewall_policy (str): + Name of the firewall policy to update. + name (str): + Name for the attachment that will be removed. + 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). + """ + + firewall_policy = proto.Field(proto.STRING, number=498173265,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + + +class RemoveRuleFirewallPolicyRequest(proto.Message): + r"""A request message for FirewallPolicies.RemoveRule. See the + method description for details. + + Attributes: + firewall_policy (str): + Name of the firewall policy to update. + priority (int): + The priority of the rule to remove from the + firewall policy. + 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). + """ + + firewall_policy = proto.Field(proto.STRING, number=498173265,) + priority = proto.Field(proto.INT32, number=445151652, optional=True,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + + +class SetIamPolicyFirewallPolicyRequest(proto.Message): + r"""A request message for FirewallPolicies.SetIamPolicy. See the + method description for details. + + Attributes: + global_organization_set_policy_request_resource (google.cloud.compute_v1.types.GlobalOrganizationSetPolicyRequest): + The body resource for this request + resource (str): + Name or id of the resource for this request. + """ + + global_organization_set_policy_request_resource = proto.Field( + proto.MESSAGE, number=177408606, message="GlobalOrganizationSetPolicyRequest", + ) + resource = proto.Field(proto.STRING, number=195806222,) + + +class TestIamPermissionsFirewallPolicyRequest(proto.Message): + r"""A request message for FirewallPolicies.TestIamPermissions. + See the method description for details. + + Attributes: + 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 + """ + + resource = proto.Field(proto.STRING, number=195806222,) + test_permissions_request_resource = proto.Field( + proto.MESSAGE, number=439214758, message="TestPermissionsRequest", + ) + + +class DeleteFirewallRequest(proto.Message): + r"""A request message for Firewalls.Delete. See the method + description for details. + + Attributes: + firewall (str): + Name of the firewall rule 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). + """ + + firewall = proto.Field(proto.STRING, number=511016192,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + + +class GetFirewallRequest(proto.Message): + r"""A request message for Firewalls.Get. See the method + description for details. + + Attributes: + firewall (str): + Name of the firewall rule to return. + project (str): + Project ID for this request. + """ + + firewall = proto.Field(proto.STRING, number=511016192,) + project = proto.Field(proto.STRING, number=227560217,) + + +class InsertFirewallRequest(proto.Message): + r"""A request message for Firewalls.Insert. See the method + description for details. + + Attributes: + firewall_resource (google.cloud.compute_v1.types.Firewall): + 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). + """ + + firewall_resource = proto.Field(proto.MESSAGE, number=41425005, message="Firewall",) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + + +class ListFirewallsRequest(proto.Message): + r"""A request message for Firewalls.List. See the method + description for details. + + Attributes: + filter (str): + A filter expression that filters resources listed in the + response. The expression must specify the field name, a + comparison operator, and the value that you want to use for + filtering. The value must be a string, a number, or a + boolean. The comparison 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``. + + 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)`` + 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``) + 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. + 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. + 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. + """ + + filter = proto.Field(proto.STRING, number=336120696, optional=True,) + max_results = proto.Field(proto.UINT32, number=54715419, optional=True,) + order_by = proto.Field(proto.STRING, number=160562920, optional=True,) + page_token = proto.Field(proto.STRING, number=19994697, optional=True,) + project = proto.Field(proto.STRING, number=227560217,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) + + +class PatchFirewallRequest(proto.Message): + r"""A request message for Firewalls.Patch. See the method + description for details. + + Attributes: + firewall (str): + Name of the firewall rule to patch. + firewall_resource (google.cloud.compute_v1.types.Firewall): + 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). + """ + + firewall = proto.Field(proto.STRING, number=511016192,) + firewall_resource = proto.Field(proto.MESSAGE, number=41425005, message="Firewall",) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + + +class UpdateFirewallRequest(proto.Message): + r"""A request message for Firewalls.Update. See the method + description for details. + + Attributes: + firewall (str): + Name of the firewall rule to update. + firewall_resource (google.cloud.compute_v1.types.Firewall): + 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). + """ + + firewall = proto.Field(proto.STRING, number=511016192,) + firewall_resource = proto.Field(proto.MESSAGE, number=41425005, message="Firewall",) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + + +class AggregatedListForwardingRulesRequest(proto.Message): + r"""A request message for ForwardingRules.AggregatedList. See the + method description for details. Attributes: filter (str): @@ -26451,8 +28730,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -26619,8 +28897,7 @@ class ListForwardingRulesRequest(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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -26672,6 +28949,46 @@ class PatchForwardingRuleRequest(proto.Message): request_id = proto.Field(proto.STRING, number=37109963, optional=True,) +class SetLabelsForwardingRuleRequest(proto.Message): + r"""A request message for ForwardingRules.SetLabels. See the + method description for details. + + 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). + resource (str): + Name or id of the resource for this request. + """ + + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + region_set_labels_request_resource = proto.Field( + proto.MESSAGE, number=259357782, message="RegionSetLabelsRequest", + ) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + resource = proto.Field(proto.STRING, number=195806222,) + + class SetTargetForwardingRuleRequest(proto.Message): r"""A request message for ForwardingRules.SetTarget. See the method description for details. @@ -26853,8 +29170,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -26948,114 +29264,133 @@ class InsertGlobalForwardingRuleRequest(proto.Message): request_id = proto.Field(proto.STRING, number=37109963, optional=True,) -class ListGlobalForwardingRulesRequest(proto.Message): - r"""A request message for GlobalForwardingRules.List. See the - method description for details. - - Attributes: - filter (str): - A filter expression that filters resources listed in the - response. The expression must specify the field name, a - comparison operator, and the value that you want to use for - filtering. The value must be a string, a number, or a - boolean. The comparison 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``. - - 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)`` - 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``) - 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. - 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. - 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 and the logic is the same - as today. - """ - - filter = proto.Field(proto.STRING, number=336120696, optional=True,) - max_results = proto.Field(proto.UINT32, number=54715419, optional=True,) - order_by = proto.Field(proto.STRING, number=160562920, optional=True,) - page_token = proto.Field(proto.STRING, number=19994697, optional=True,) - project = proto.Field(proto.STRING, number=227560217,) - return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) - - -class PatchGlobalForwardingRuleRequest(proto.Message): - r"""A request message for GlobalForwardingRules.Patch. See the - method description for details. +class ListGlobalForwardingRulesRequest(proto.Message): + r"""A request message for GlobalForwardingRules.List. See the + method description for details. + + Attributes: + filter (str): + A filter expression that filters resources listed in the + response. The expression must specify the field name, a + comparison operator, and the value that you want to use for + filtering. The value must be a string, a number, or a + boolean. The comparison 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``. + + 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)`` + 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``) + 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. + 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. + 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. + """ + + filter = proto.Field(proto.STRING, number=336120696, optional=True,) + max_results = proto.Field(proto.UINT32, number=54715419, optional=True,) + order_by = proto.Field(proto.STRING, number=160562920, optional=True,) + page_token = proto.Field(proto.STRING, number=19994697, optional=True,) + project = proto.Field(proto.STRING, number=227560217,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) + + +class PatchGlobalForwardingRuleRequest(proto.Message): + r"""A request message for GlobalForwardingRules.Patch. See the + method description for details. + + Attributes: + forwarding_rule (str): + Name of the ForwardingRule resource to patch. + forwarding_rule_resource (google.cloud.compute_v1.types.ForwardingRule): + 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). + """ + + forwarding_rule = proto.Field(proto.STRING, number=269964030,) + forwarding_rule_resource = proto.Field( + proto.MESSAGE, number=301211695, message="ForwardingRule", + ) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + + +class SetLabelsGlobalForwardingRuleRequest(proto.Message): + r"""A request message for GlobalForwardingRules.SetLabels. See + the method description for details. Attributes: - forwarding_rule (str): - Name of the ForwardingRule resource to patch. - forwarding_rule_resource (google.cloud.compute_v1.types.ForwardingRule): + global_set_labels_request_resource (google.cloud.compute_v1.types.GlobalSetLabelsRequest): 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). + resource (str): + Name or id of the resource for this request. """ - forwarding_rule = proto.Field(proto.STRING, number=269964030,) - forwarding_rule_resource = proto.Field( - proto.MESSAGE, number=301211695, message="ForwardingRule", + global_set_labels_request_resource = proto.Field( + proto.MESSAGE, number=319917189, message="GlobalSetLabelsRequest", ) project = proto.Field(proto.STRING, number=227560217,) - request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + resource = proto.Field(proto.STRING, number=195806222,) class SetTargetGlobalForwardingRuleRequest(proto.Message): @@ -27324,8 +29659,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -27403,8 +29737,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -27488,8 +29821,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -27598,8 +29930,7 @@ class ListGlobalOperationsRequest(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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -27722,8 +30053,7 @@ class ListGlobalOrganizationOperationsRequest(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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -27734,6 +30064,199 @@ class ListGlobalOrganizationOperationsRequest(proto.Message): return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) +class DeleteGlobalPublicDelegatedPrefixeRequest(proto.Message): + r"""A request message for GlobalPublicDelegatedPrefixes.Delete. + See the method description for details. + + Attributes: + project (str): + Project ID for this request. + public_delegated_prefix (str): + Name of the PublicDelegatedPrefix resource to + delete. + 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). + """ + + project = proto.Field(proto.STRING, number=227560217,) + public_delegated_prefix = proto.Field(proto.STRING, number=204238440,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + + +class GetGlobalPublicDelegatedPrefixeRequest(proto.Message): + r"""A request message for GlobalPublicDelegatedPrefixes.Get. See + the method description for details. + + Attributes: + project (str): + Project ID for this request. + public_delegated_prefix (str): + Name of the PublicDelegatedPrefix resource to + return. + """ + + project = proto.Field(proto.STRING, number=227560217,) + public_delegated_prefix = proto.Field(proto.STRING, number=204238440,) + + +class InsertGlobalPublicDelegatedPrefixeRequest(proto.Message): + r"""A request message for GlobalPublicDelegatedPrefixes.Insert. + See the method description for details. + + Attributes: + project (str): + Project ID for this request. + public_delegated_prefix_resource (google.cloud.compute_v1.types.PublicDelegatedPrefix): + 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). + """ + + project = proto.Field(proto.STRING, number=227560217,) + public_delegated_prefix_resource = proto.Field( + proto.MESSAGE, number=47594501, message="PublicDelegatedPrefix", + ) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + + +class ListGlobalPublicDelegatedPrefixesRequest(proto.Message): + r"""A request message for GlobalPublicDelegatedPrefixes.List. See + the method description for details. + + Attributes: + filter (str): + A filter expression that filters resources listed in the + response. The expression must specify the field name, a + comparison operator, and the value that you want to use for + filtering. The value must be a string, a number, or a + boolean. The comparison 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``. + + 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)`` + 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``) + 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. + 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. + 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. + """ + + filter = proto.Field(proto.STRING, number=336120696, optional=True,) + max_results = proto.Field(proto.UINT32, number=54715419, optional=True,) + order_by = proto.Field(proto.STRING, number=160562920, optional=True,) + page_token = proto.Field(proto.STRING, number=19994697, optional=True,) + project = proto.Field(proto.STRING, number=227560217,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) + + +class PatchGlobalPublicDelegatedPrefixeRequest(proto.Message): + r"""A request message for GlobalPublicDelegatedPrefixes.Patch. + See the method description for details. + + Attributes: + project (str): + Project ID for this request. + public_delegated_prefix (str): + Name of the PublicDelegatedPrefix resource to + patch. + public_delegated_prefix_resource (google.cloud.compute_v1.types.PublicDelegatedPrefix): + 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). + """ + + project = proto.Field(proto.STRING, number=227560217,) + public_delegated_prefix = proto.Field(proto.STRING, number=204238440,) + public_delegated_prefix_resource = proto.Field( + proto.MESSAGE, number=47594501, message="PublicDelegatedPrefix", + ) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + + class AggregatedListHealthChecksRequest(proto.Message): r"""A request message for HealthChecks.AggregatedList. See the method description for details. @@ -27806,8 +30329,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -27961,8 +30483,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -28262,8 +30783,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -28484,8 +31004,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -28797,8 +31316,7 @@ 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 and the logic is the same - as today. + default value is false. zone (str): The name of the zone where the managed instance group is located. @@ -28879,8 +31397,7 @@ class ListErrorsInstanceGroupManagersRequest(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 and the logic is the same - as today. + default value is false. zone (str): The name of the zone where the managed instance group is located. It should conform to @@ -28961,8 +31478,7 @@ 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 and the logic is the same - as today. + default value is false. zone (str): The name of the zone where the managed instance group is located. @@ -29043,8 +31559,7 @@ 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 and the logic is the same - as today. + default value is false. zone (str): The name of the zone where the managed instance group is located. It should conform to @@ -29482,8 +31997,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -29649,8 +32163,7 @@ 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 and the logic is the same - as today. + default value is false. zone (str): The name of the zone where the instance group is located. @@ -29731,8 +32244,7 @@ class ListInstancesInstanceGroupsRequest(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 and the logic is the same - as today. + default value is false. zone (str): The name of the zone where the instance group is located. @@ -29997,8 +32509,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -30083,9 +32594,292 @@ class AddAccessConfigInstanceRequest(proto.Message): The name of the zone for this request. """ - access_config_resource = proto.Field( - proto.MESSAGE, number=387825552, message="AccessConfig", - ) + access_config_resource = proto.Field( + proto.MESSAGE, number=387825552, message="AccessConfig", + ) + instance = proto.Field(proto.STRING, number=18257045,) + network_interface = proto.Field(proto.STRING, number=365387880,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + zone = proto.Field(proto.STRING, number=3744684,) + + +class AddResourcePoliciesInstanceRequest(proto.Message): + r"""A request message for Instances.AddResourcePolicies. See the + method description for details. + + Attributes: + instance (str): + The instance name for this request. + instances_add_resource_policies_request_resource (google.cloud.compute_v1.types.InstancesAddResourcePoliciesRequest): + 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). + zone (str): + The name of the zone for this request. + """ + + instance = proto.Field(proto.STRING, number=18257045,) + instances_add_resource_policies_request_resource = proto.Field( + proto.MESSAGE, number=489351963, message="InstancesAddResourcePoliciesRequest", + ) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + zone = proto.Field(proto.STRING, number=3744684,) + + +class AggregatedListInstancesRequest(proto.Message): + r"""A request message for Instances.AggregatedList. See the + method description for details. + + Attributes: + filter (str): + A filter expression that filters resources listed in the + response. The expression must specify the field name, a + comparison operator, and the value that you want to use for + filtering. The value must be a string, a number, or a + boolean. The comparison 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``. + + 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)`` + 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. + 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``) + 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. + 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. + 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. + """ + + filter = proto.Field(proto.STRING, number=336120696, optional=True,) + include_all_scopes = proto.Field(proto.BOOL, number=391327988, optional=True,) + max_results = proto.Field(proto.UINT32, number=54715419, optional=True,) + order_by = proto.Field(proto.STRING, number=160562920, optional=True,) + page_token = proto.Field(proto.STRING, number=19994697, optional=True,) + project = proto.Field(proto.STRING, number=227560217,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) + + +class AttachDiskInstanceRequest(proto.Message): + r"""A request message for Instances.AttachDisk. See the method + description for details. + + Attributes: + attached_disk_resource (google.cloud.compute_v1.types.AttachedDisk): + The body resource for this request + force_attach (bool): + Whether to force attach the regional disk + even if it's currently attached to another + instance. If you try to force attach a zonal + disk to an instance, you will receive an error. + instance (str): + The instance name 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). + zone (str): + The name of the zone for this request. + """ + + attached_disk_resource = proto.Field( + proto.MESSAGE, number=90605845, message="AttachedDisk", + ) + force_attach = proto.Field(proto.BOOL, number=142758425, optional=True,) + instance = proto.Field(proto.STRING, number=18257045,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + zone = proto.Field(proto.STRING, number=3744684,) + + +class BulkInsertInstanceRequest(proto.Message): + r"""A request message for Instances.BulkInsert. See the method + description for details. + + Attributes: + bulk_insert_instance_resource_resource (google.cloud.compute_v1.types.BulkInsertInstanceResource): + 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). + zone (str): + The name of the zone for this request. + """ + + bulk_insert_instance_resource_resource = proto.Field( + proto.MESSAGE, number=41427278, message="BulkInsertInstanceResource", + ) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + zone = proto.Field(proto.STRING, number=3744684,) + + +class DeleteInstanceRequest(proto.Message): + r"""A request message for Instances.Delete. See the method + description for details. + + Attributes: + instance (str): + Name of the instance 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). + zone (str): + The name of the zone for this request. + """ + + instance = proto.Field(proto.STRING, number=18257045,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + zone = proto.Field(proto.STRING, number=3744684,) + + +class DeleteAccessConfigInstanceRequest(proto.Message): + r"""A request message for Instances.DeleteAccessConfig. See the + method description for details. + + Attributes: + access_config (str): + The name of the access config to delete. + instance (str): + The instance name for this request. + network_interface (str): + The name of the network interface. + 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). + zone (str): + The name of the zone for this request. + """ + + access_config = proto.Field(proto.STRING, number=72856189,) instance = proto.Field(proto.STRING, number=18257045,) network_interface = proto.Field(proto.STRING, number=365387880,) project = proto.Field(proto.STRING, number=227560217,) @@ -30093,145 +32887,17 @@ class AddAccessConfigInstanceRequest(proto.Message): zone = proto.Field(proto.STRING, number=3744684,) -class AddResourcePoliciesInstanceRequest(proto.Message): - r"""A request message for Instances.AddResourcePolicies. See the - method description for details. - - Attributes: - instance (str): - The instance name for this request. - instances_add_resource_policies_request_resource (google.cloud.compute_v1.types.InstancesAddResourcePoliciesRequest): - 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). - zone (str): - The name of the zone for this request. - """ - - instance = proto.Field(proto.STRING, number=18257045,) - instances_add_resource_policies_request_resource = proto.Field( - proto.MESSAGE, number=489351963, message="InstancesAddResourcePoliciesRequest", - ) - project = proto.Field(proto.STRING, number=227560217,) - request_id = proto.Field(proto.STRING, number=37109963, optional=True,) - zone = proto.Field(proto.STRING, number=3744684,) - - -class AggregatedListInstancesRequest(proto.Message): - r"""A request message for Instances.AggregatedList. See the - method description for details. - - Attributes: - filter (str): - A filter expression that filters resources listed in the - response. The expression must specify the field name, a - comparison operator, and the value that you want to use for - filtering. The value must be a string, a number, or a - boolean. The comparison 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``. - - 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)`` - 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. - 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``) - 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. - 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. - 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 and the logic is the same - as today. - """ - - filter = proto.Field(proto.STRING, number=336120696, optional=True,) - include_all_scopes = proto.Field(proto.BOOL, number=391327988, optional=True,) - max_results = proto.Field(proto.UINT32, number=54715419, optional=True,) - order_by = proto.Field(proto.STRING, number=160562920, optional=True,) - page_token = proto.Field(proto.STRING, number=19994697, optional=True,) - project = proto.Field(proto.STRING, number=227560217,) - return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) - - -class AttachDiskInstanceRequest(proto.Message): - r"""A request message for Instances.AttachDisk. See the method +class DetachDiskInstanceRequest(proto.Message): + r"""A request message for Instances.DetachDisk. See the method description for details. Attributes: - attached_disk_resource (google.cloud.compute_v1.types.AttachedDisk): - The body resource for this request - force_attach (bool): - Whether to force attach the regional disk - even if it's currently attached to another - instance. If you try to force attach a zonal - disk to an instance, you will receive an error. + device_name (str): + The device name of the disk to detach. Make a + get() request on the instance to view currently + attached disks and device names. instance (str): - The instance name for this request. + Instance name for this request. project (str): Project ID for this request. request_id (str): @@ -30254,147 +32920,50 @@ class AttachDiskInstanceRequest(proto.Message): The name of the zone for this request. """ - attached_disk_resource = proto.Field( - proto.MESSAGE, number=90605845, message="AttachedDisk", - ) - force_attach = proto.Field(proto.BOOL, number=142758425, optional=True,) + device_name = proto.Field(proto.STRING, number=67541716,) instance = proto.Field(proto.STRING, number=18257045,) project = proto.Field(proto.STRING, number=227560217,) request_id = proto.Field(proto.STRING, number=37109963, optional=True,) zone = proto.Field(proto.STRING, number=3744684,) -class DeleteInstanceRequest(proto.Message): - r"""A request message for Instances.Delete. See the method +class GetInstanceRequest(proto.Message): + r"""A request message for Instances.Get. See the method description for details. Attributes: instance (str): - Name of the instance resource to delete. + Name of the instance resource to return. 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). zone (str): The name of the zone for this request. """ instance = proto.Field(proto.STRING, number=18257045,) project = proto.Field(proto.STRING, number=227560217,) - request_id = proto.Field(proto.STRING, number=37109963, optional=True,) zone = proto.Field(proto.STRING, number=3744684,) -class DeleteAccessConfigInstanceRequest(proto.Message): - r"""A request message for Instances.DeleteAccessConfig. See the - method description for details. +class GetEffectiveFirewallsInstanceRequest(proto.Message): + r"""A request message for Instances.GetEffectiveFirewalls. See + the method description for details. Attributes: - access_config (str): - The name of the access config to delete. instance (str): - The instance name for this request. + Name of the instance scoping this request. network_interface (str): - The name of the network interface. + The name of the network interface to get the + effective firewalls. 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). zone (str): The name of the zone for this request. """ - access_config = proto.Field(proto.STRING, number=72856189,) instance = proto.Field(proto.STRING, number=18257045,) network_interface = proto.Field(proto.STRING, number=365387880,) project = proto.Field(proto.STRING, number=227560217,) - request_id = proto.Field(proto.STRING, number=37109963, optional=True,) - zone = proto.Field(proto.STRING, number=3744684,) - - -class DetachDiskInstanceRequest(proto.Message): - r"""A request message for Instances.DetachDisk. See the method - description for details. - - Attributes: - device_name (str): - The device name of the disk to detach. Make a - get() request on the instance to view currently - attached disks and device names. - instance (str): - Instance name 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). - zone (str): - The name of the zone for this request. - """ - - device_name = proto.Field(proto.STRING, number=67541716,) - instance = proto.Field(proto.STRING, number=18257045,) - project = proto.Field(proto.STRING, number=227560217,) - request_id = proto.Field(proto.STRING, number=37109963, optional=True,) - zone = proto.Field(proto.STRING, number=3744684,) - - -class GetInstanceRequest(proto.Message): - r"""A request message for Instances.Get. See the method - description for details. - - Attributes: - instance (str): - Name of the instance resource to return. - project (str): - Project ID for this request. - zone (str): - The name of the zone for this request. - """ - - instance = proto.Field(proto.STRING, number=18257045,) - project = proto.Field(proto.STRING, number=227560217,) zone = proto.Field(proto.STRING, number=3744684,) @@ -30636,8 +33205,7 @@ 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 and the logic is the same - as today. + default value is false. zone (str): The name of the zone for this request. """ @@ -30716,8 +33284,7 @@ class ListReferrersInstancesRequest(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 and the logic is the same - as today. + default value is false. zone (str): The name of the zone for this request. """ @@ -31725,8 +34292,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -31896,8 +34462,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -32025,8 +34590,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -32194,8 +34758,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -32439,8 +35002,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -32563,8 +35125,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -32655,8 +35216,7 @@ 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 and the logic is the same - as today. + default value is false. zone (str): The name of the zone for this request. """ @@ -32742,8 +35302,7 @@ class AggregatedListNetworkEndpointGroupsRequest(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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -33008,8 +35567,7 @@ 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 and the logic is the same - as today. + default value is false. zone (str): The name of the zone where the network endpoint group is located. It should comply with @@ -33094,8 +35652,7 @@ 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 and the logic is the same - as today. + default value is false. zone (str): The name of the zone where the network endpoint group is located. It should comply with @@ -33226,6 +35783,21 @@ class GetNetworkRequest(proto.Message): project = proto.Field(proto.STRING, number=227560217,) +class GetEffectiveFirewallsNetworkRequest(proto.Message): + r"""A request message for Networks.GetEffectiveFirewalls. See the + method description for details. + + Attributes: + network (str): + Name of the network for this request. + project (str): + Project ID for this request. + """ + + network = proto.Field(proto.STRING, number=232872494,) + project = proto.Field(proto.STRING, number=227560217,) + + class InsertNetworkRequest(proto.Message): r"""A request message for Networks.Insert. See the method description for details. @@ -33319,8 +35891,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -33403,8 +35974,7 @@ 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 and the logic is the same - as today. + default value is false. """ class Direction(proto.Enum): @@ -33682,8 +36252,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -33913,8 +36482,7 @@ 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 and the logic is the same - as today. + default value is false. zone (str): The name of the zone for this request. """ @@ -33992,8 +36560,7 @@ 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 and the logic is the same - as today. + default value is false. zone (str): The name of the zone for this request. """ @@ -34206,8 +36773,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -34395,8 +36961,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -34526,8 +37091,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -34618,8 +37182,7 @@ 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 and the logic is the same - as today. + default value is false. zone (str): The name of the zone for this request. """ @@ -34705,8 +37268,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -34873,8 +37435,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -35161,8 +37722,409 @@ 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 and the logic is the same - as today. + default value is false. + """ + + filter = proto.Field(proto.STRING, number=336120696, optional=True,) + max_results = proto.Field(proto.UINT32, number=54715419, optional=True,) + order_by = proto.Field(proto.STRING, number=160562920, optional=True,) + page_token = proto.Field(proto.STRING, number=19994697, optional=True,) + project = proto.Field(proto.STRING, number=227560217,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) + + +class ListXpnHostsProjectsRequest(proto.Message): + r"""A request message for Projects.ListXpnHosts. See the method + description for details. + + Attributes: + filter (str): + A filter expression that filters resources listed in the + response. The expression must specify the field name, a + comparison operator, and the value that you want to use for + filtering. The value must be a string, a number, or a + boolean. The comparison 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``. + + 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)`` + 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``) + 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. + 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. + project (str): + Project ID for this request. + projects_list_xpn_hosts_request_resource (google.cloud.compute_v1.types.ProjectsListXpnHostsRequest): + The body resource for this request + return_partial_success (bool): + Opt-in for partial success behavior which + provides partial results in case of failure. The + default value is false. + """ + + filter = proto.Field(proto.STRING, number=336120696, optional=True,) + max_results = proto.Field(proto.UINT32, number=54715419, optional=True,) + order_by = proto.Field(proto.STRING, number=160562920, optional=True,) + page_token = proto.Field(proto.STRING, number=19994697, optional=True,) + project = proto.Field(proto.STRING, number=227560217,) + projects_list_xpn_hosts_request_resource = proto.Field( + proto.MESSAGE, number=238266391, message="ProjectsListXpnHostsRequest", + ) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) + + +class MoveDiskProjectRequest(proto.Message): + r"""A request message for Projects.MoveDisk. See the method + description for details. + + Attributes: + disk_move_request_resource (google.cloud.compute_v1.types.DiskMoveRequest): + 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). + """ + + disk_move_request_resource = proto.Field( + proto.MESSAGE, number=313008458, message="DiskMoveRequest", + ) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + + +class MoveInstanceProjectRequest(proto.Message): + r"""A request message for Projects.MoveInstance. See the method + description for details. + + Attributes: + instance_move_request_resource (google.cloud.compute_v1.types.InstanceMoveRequest): + 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). + """ + + instance_move_request_resource = proto.Field( + proto.MESSAGE, number=311664194, message="InstanceMoveRequest", + ) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + + +class SetCommonInstanceMetadataProjectRequest(proto.Message): + r"""A request message for Projects.SetCommonInstanceMetadata. See + the method description for details. + + Attributes: + metadata_resource (google.cloud.compute_v1.types.Metadata): + 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). + """ + + metadata_resource = proto.Field( + proto.MESSAGE, number=291086110, message="Metadata", + ) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + + +class SetDefaultNetworkTierProjectRequest(proto.Message): + r"""A request message for Projects.SetDefaultNetworkTier. See the + method description for details. + + Attributes: + project (str): + Project ID for this request. + projects_set_default_network_tier_request_resource (google.cloud.compute_v1.types.ProjectsSetDefaultNetworkTierRequest): + 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). + """ + + project = proto.Field(proto.STRING, number=227560217,) + projects_set_default_network_tier_request_resource = proto.Field( + proto.MESSAGE, number=126410762, message="ProjectsSetDefaultNetworkTierRequest", + ) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + + +class SetUsageExportBucketProjectRequest(proto.Message): + r"""A request message for Projects.SetUsageExportBucket. See the + method description for details. + + 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). + usage_export_location_resource (google.cloud.compute_v1.types.UsageExportLocation): + The body resource for this request + """ + + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + usage_export_location_resource = proto.Field( + proto.MESSAGE, number=20260459, message="UsageExportLocation", + ) + + +class DeletePublicAdvertisedPrefixeRequest(proto.Message): + r"""A request message for PublicAdvertisedPrefixes.Delete. See + the method description for details. + + Attributes: + project (str): + Project ID for this request. + public_advertised_prefix (str): + Name of the PublicAdvertisedPrefix resource + to delete. + 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). + """ + + project = proto.Field(proto.STRING, number=227560217,) + public_advertised_prefix = proto.Field(proto.STRING, number=101874590,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + + +class GetPublicAdvertisedPrefixeRequest(proto.Message): + r"""A request message for PublicAdvertisedPrefixes.Get. See the + method description for details. + + Attributes: + project (str): + Project ID for this request. + public_advertised_prefix (str): + Name of the PublicAdvertisedPrefix resource + to return. + """ + + project = proto.Field(proto.STRING, number=227560217,) + public_advertised_prefix = proto.Field(proto.STRING, number=101874590,) + + +class InsertPublicAdvertisedPrefixeRequest(proto.Message): + r"""A request message for PublicAdvertisedPrefixes.Insert. See + the method description for details. + + Attributes: + project (str): + Project ID for this request. + public_advertised_prefix_resource (google.cloud.compute_v1.types.PublicAdvertisedPrefix): + 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). + """ + + project = proto.Field(proto.STRING, number=227560217,) + public_advertised_prefix_resource = proto.Field( + proto.MESSAGE, number=233614223, message="PublicAdvertisedPrefix", + ) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + + +class ListPublicAdvertisedPrefixesRequest(proto.Message): + r"""A request message for PublicAdvertisedPrefixes.List. See the + method description for details. + + Attributes: + filter (str): + A filter expression that filters resources listed in the + response. The expression must specify the field name, a + comparison operator, and the value that you want to use for + filtering. The value must be a string, a number, or a + boolean. The comparison 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``. + + 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)`` + 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``) + 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. + 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. + 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. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -35173,9 +38135,47 @@ class GetXpnResourcesProjectsRequest(proto.Message): return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) -class ListXpnHostsProjectsRequest(proto.Message): - r"""A request message for Projects.ListXpnHosts. See the method - description for details. +class PatchPublicAdvertisedPrefixeRequest(proto.Message): + r"""A request message for PublicAdvertisedPrefixes.Patch. See the + method description for details. + + Attributes: + project (str): + Project ID for this request. + public_advertised_prefix (str): + Name of the PublicAdvertisedPrefix resource + to patch. + public_advertised_prefix_resource (google.cloud.compute_v1.types.PublicAdvertisedPrefix): + 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). + """ + + project = proto.Field(proto.STRING, number=227560217,) + public_advertised_prefix = proto.Field(proto.STRING, number=101874590,) + public_advertised_prefix_resource = proto.Field( + proto.MESSAGE, number=233614223, message="PublicAdvertisedPrefix", + ) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + + +class AggregatedListPublicDelegatedPrefixesRequest(proto.Message): + r"""A request message for PublicDelegatedPrefixes.AggregatedList. + See the method description for details. Attributes: filter (str): @@ -35203,6 +38203,17 @@ class ListXpnHostsProjectsRequest(proto.Message): However, you can include ``AND`` and ``OR`` expressions explicitly. For example: ``(cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true)`` + 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. max_results (int): The maximum number of results per page that should be returned. If the number of available results is larger than @@ -35230,36 +38241,34 @@ class ListXpnHostsProjectsRequest(proto.Message): ``nextPageToken`` returned by a previous list request to get the next page of results. project (str): - Project ID for this request. - projects_list_xpn_hosts_request_resource (google.cloud.compute_v1.types.ProjectsListXpnHostsRequest): - The body resource for this request + 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) + include_all_scopes = proto.Field(proto.BOOL, number=391327988, optional=True,) max_results = proto.Field(proto.UINT32, number=54715419, optional=True,) order_by = proto.Field(proto.STRING, number=160562920, optional=True,) page_token = proto.Field(proto.STRING, number=19994697, optional=True,) project = proto.Field(proto.STRING, number=227560217,) - projects_list_xpn_hosts_request_resource = proto.Field( - proto.MESSAGE, number=238266391, message="ProjectsListXpnHostsRequest", - ) return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) -class MoveDiskProjectRequest(proto.Message): - r"""A request message for Projects.MoveDisk. See the method - description for details. +class DeletePublicDelegatedPrefixeRequest(proto.Message): + r"""A request message for PublicDelegatedPrefixes.Delete. See the + method description for details. Attributes: - disk_move_request_resource (google.cloud.compute_v1.types.DiskMoveRequest): - The body resource for this request project (str): Project ID for this request. + public_delegated_prefix (str): + Name of the PublicDelegatedPrefix resource to + delete. + region (str): + Name of the region of this request. request_id (str): An optional request ID to identify requests. Specify a unique request ID so that if you must @@ -35278,56 +38287,42 @@ class MoveDiskProjectRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - disk_move_request_resource = proto.Field( - proto.MESSAGE, number=313008458, message="DiskMoveRequest", - ) project = proto.Field(proto.STRING, number=227560217,) + public_delegated_prefix = proto.Field(proto.STRING, number=204238440,) + region = proto.Field(proto.STRING, number=138946292,) request_id = proto.Field(proto.STRING, number=37109963, optional=True,) -class MoveInstanceProjectRequest(proto.Message): - r"""A request message for Projects.MoveInstance. See the method - description for details. +class GetPublicDelegatedPrefixeRequest(proto.Message): + r"""A request message for PublicDelegatedPrefixes.Get. See the + method description for details. Attributes: - instance_move_request_resource (google.cloud.compute_v1.types.InstanceMoveRequest): - 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). + public_delegated_prefix (str): + Name of the PublicDelegatedPrefix resource to + return. + region (str): + Name of the region of this request. """ - instance_move_request_resource = proto.Field( - proto.MESSAGE, number=311664194, message="InstanceMoveRequest", - ) project = proto.Field(proto.STRING, number=227560217,) - request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + public_delegated_prefix = proto.Field(proto.STRING, number=204238440,) + region = proto.Field(proto.STRING, number=138946292,) -class SetCommonInstanceMetadataProjectRequest(proto.Message): - r"""A request message for Projects.SetCommonInstanceMetadata. See - the method description for details. +class InsertPublicDelegatedPrefixeRequest(proto.Message): + r"""A request message for PublicDelegatedPrefixes.Insert. See the + method description for details. Attributes: - metadata_resource (google.cloud.compute_v1.types.Metadata): - The body resource for this request project (str): Project ID for this request. + public_delegated_prefix_resource (google.cloud.compute_v1.types.PublicDelegatedPrefix): + The body resource for this request + region (str): + Name of the region of this request. request_id (str): An optional request ID to identify requests. Specify a unique request ID so that if you must @@ -35346,54 +38341,103 @@ class SetCommonInstanceMetadataProjectRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - metadata_resource = proto.Field( - proto.MESSAGE, number=291086110, message="Metadata", - ) project = proto.Field(proto.STRING, number=227560217,) + public_delegated_prefix_resource = proto.Field( + proto.MESSAGE, number=47594501, message="PublicDelegatedPrefix", + ) + region = proto.Field(proto.STRING, number=138946292,) request_id = proto.Field(proto.STRING, number=37109963, optional=True,) -class SetDefaultNetworkTierProjectRequest(proto.Message): - r"""A request message for Projects.SetDefaultNetworkTier. See the +class ListPublicDelegatedPrefixesRequest(proto.Message): + r"""A request message for PublicDelegatedPrefixes.List. See the method description for details. Attributes: + filter (str): + A filter expression that filters resources listed in the + response. The expression must specify the field name, a + comparison operator, and the value that you want to use for + filtering. The value must be a string, a number, or a + boolean. The comparison 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``. + + 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)`` + 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``) + 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. + 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. project (str): Project ID for this request. - projects_set_default_network_tier_request_resource (google.cloud.compute_v1.types.ProjectsSetDefaultNetworkTierRequest): - 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). + 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. """ + filter = proto.Field(proto.STRING, number=336120696, optional=True,) + max_results = proto.Field(proto.UINT32, number=54715419, optional=True,) + order_by = proto.Field(proto.STRING, number=160562920, optional=True,) + page_token = proto.Field(proto.STRING, number=19994697, optional=True,) project = proto.Field(proto.STRING, number=227560217,) - projects_set_default_network_tier_request_resource = proto.Field( - proto.MESSAGE, number=126410762, message="ProjectsSetDefaultNetworkTierRequest", - ) - request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) -class SetUsageExportBucketProjectRequest(proto.Message): - r"""A request message for Projects.SetUsageExportBucket. See the +class PatchPublicDelegatedPrefixeRequest(proto.Message): + r"""A request message for PublicDelegatedPrefixes.Patch. See the method description for details. Attributes: project (str): Project ID for this request. + public_delegated_prefix (str): + Name of the PublicDelegatedPrefix resource to + patch. + public_delegated_prefix_resource (google.cloud.compute_v1.types.PublicDelegatedPrefix): + The body resource 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 @@ -35410,15 +38454,15 @@ class SetUsageExportBucketProjectRequest(proto.Message): The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). - usage_export_location_resource (google.cloud.compute_v1.types.UsageExportLocation): - The body resource for this request """ project = proto.Field(proto.STRING, number=227560217,) - request_id = proto.Field(proto.STRING, number=37109963, optional=True,) - usage_export_location_resource = proto.Field( - proto.MESSAGE, number=20260459, message="UsageExportLocation", + public_delegated_prefix = proto.Field(proto.STRING, number=204238440,) + public_delegated_prefix_resource = proto.Field( + proto.MESSAGE, number=47594501, message="PublicDelegatedPrefix", ) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class DeleteRegionAutoscalerRequest(proto.Message): @@ -35574,8 +38618,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -35846,8 +38889,7 @@ class ListRegionBackendServicesRequest(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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -36012,8 +39054,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -36143,8 +39184,7 @@ class ListRegionCommitmentsRequest(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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -36237,8 +39277,7 @@ class ListRegionDiskTypesRequest(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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -36439,8 +39478,8 @@ class InsertRegionDiskRequest(proto.Message): exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). source_image (str): - Optional. Source image to restore onto a - disk. + Source image to restore onto a disk. This + field is optional. """ disk_resource = proto.Field(proto.MESSAGE, number=25880688, message="Disk",) @@ -36513,8 +39552,7 @@ class ListRegionDisksRequest(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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -36851,8 +39889,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -37059,8 +40096,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -37492,8 +40528,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -37574,8 +40609,7 @@ class ListErrorsRegionInstanceGroupManagersRequest(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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -37654,8 +40688,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -37736,8 +40769,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -38130,8 +41162,7 @@ class ListRegionInstanceGroupsRequest(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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -38211,8 +41242,7 @@ class ListInstancesRegionInstanceGroupsRequest(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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -38273,6 +41303,43 @@ class SetNamedPortsRegionInstanceGroupRequest(proto.Message): request_id = proto.Field(proto.STRING, number=37109963, optional=True,) +class BulkInsertRegionInstanceRequest(proto.Message): + r"""A request message for RegionInstances.BulkInsert. See the + method description for details. + + Attributes: + bulk_insert_instance_resource_resource (google.cloud.compute_v1.types.BulkInsertInstanceResource): + The body resource for this request + 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). + """ + + bulk_insert_instance_resource_resource = proto.Field( + proto.MESSAGE, number=41427278, message="BulkInsertInstanceResource", + ) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = 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. @@ -38436,8 +41503,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -38604,8 +41670,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -38722,8 +41787,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -38908,8 +41972,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -39076,8 +42139,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -39285,8 +42347,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -39508,8 +42569,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -39671,8 +42731,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -39755,8 +42814,7 @@ class AggregatedListReservationsRequest(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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -39942,8 +43000,7 @@ 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 and the logic is the same - as today. + default value is false. zone (str): Name of the zone for this request. """ @@ -40115,8 +43172,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -40304,8 +43360,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -40435,8 +43490,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -40564,8 +43618,7 @@ 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 and the logic is the same - as today. + default value is false. router (str): Name of the Router resource to query for Nat Mapping information of VM endpoints. @@ -40697,8 +43750,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -40947,8 +43999,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -41141,8 +44192,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -41215,8 +44265,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -41434,8 +44483,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -41578,8 +44626,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -41735,8 +44782,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -41893,8 +44939,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -41966,8 +45011,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -42089,8 +45133,7 @@ class AggregatedListSubnetworksRequest(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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -42318,8 +45361,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -42392,8 +45434,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -42688,8 +45729,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -42810,8 +45850,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -42967,8 +46006,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -43127,8 +46165,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -43284,8 +46321,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -43296,6 +46332,44 @@ class ListTargetHttpsProxiesRequest(proto.Message): return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) +class PatchTargetHttpsProxyRequest(proto.Message): + r"""A request message for TargetHttpsProxies.Patch. See the + method description for details. + + 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). + target_https_proxy (str): + Name of the TargetHttpsProxy resource to + patch. + target_https_proxy_resource (google.cloud.compute_v1.types.TargetHttpsProxy): + The body resource for this request + """ + + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + target_https_proxy = proto.Field(proto.STRING, number=52336748,) + target_https_proxy_resource = proto.Field( + proto.MESSAGE, number=433657473, message="TargetHttpsProxy", + ) + + class SetQuicOverrideTargetHttpsProxyRequest(proto.Message): r"""A request message for TargetHttpsProxies.SetQuicOverride. See the method description for details. @@ -43526,8 +46600,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -43692,8 +46765,7 @@ 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 and the logic is the same - as today. + default value is false. zone (str): Name of the zone scoping this request. """ @@ -43861,8 +46933,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -44051,8 +47122,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -44334,8 +47404,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -44649,8 +47718,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -44813,8 +47881,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -44979,8 +48046,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -45064,8 +48130,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -45254,8 +48319,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -45429,8 +48493,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -45613,8 +48676,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -45761,8 +48823,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -45927,8 +48988,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) @@ -46043,8 +49103,7 @@ 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 and the logic is the same - as today. + default value is false. zone (str): Name of the zone for request. """ @@ -46152,8 +49211,7 @@ 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 and the logic is the same - as today. + default value is false. """ filter = proto.Field(proto.STRING, number=336120696, optional=True,) diff --git a/packages/google-cloud-compute/noxfile.py b/packages/google-cloud-compute/noxfile.py index ae624edf327b..178f3a9930d7 100644 --- a/packages/google-cloud-compute/noxfile.py +++ b/packages/google-cloud-compute/noxfile.py @@ -169,7 +169,7 @@ def cover(session): test runs (not system test runs), and then erases coverage data. """ session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=97") + session.run("coverage", "report", "--show-missing", "--fail-under=96") session.run("coverage", "erase") @@ -179,7 +179,7 @@ def docs(session): """Build the docs for this library.""" session.install("-e", ".") - session.install("sphinx", "alabaster", "recommonmark") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) session.run( @@ -200,7 +200,9 @@ def docfx(session): """Build the docfx yaml files for this library.""" session.install("-e", ".") - session.install("sphinx", "alabaster", "recommonmark", "gcp-sphinx-docfx-yaml") + session.install( + "sphinx==4.0.1", "alabaster", "recommonmark", "gcp-sphinx-docfx-yaml" + ) shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) session.run( diff --git a/packages/google-cloud-compute/setup.py b/packages/google-cloud-compute/setup.py index 42e657386623..d0d3ba10c952 100644 --- a/packages/google-cloud-compute/setup.py +++ b/packages/google-cloud-compute/setup.py @@ -40,8 +40,9 @@ platforms="Posix; MacOS X; Windows", include_package_data=True, install_requires=( - "google-api-core[grpc] >= 1.22.2, < 2.0.0dev", + "google-api-core[grpc] >= 1.28.0, < 2.0.0dev", "proto-plus >= 1.13.0", + "packaging >= 14.3", ), python_requires=">=3.6", classifiers=[ diff --git a/packages/google-cloud-compute/synth.metadata b/packages/google-cloud-compute/synth.metadata index e056526307a1..8798701cee81 100644 --- a/packages/google-cloud-compute/synth.metadata +++ b/packages/google-cloud-compute/synth.metadata @@ -4,14 +4,14 @@ "git": { "name": ".", "remote": "https://github.com/googleapis/python-compute.git", - "sha": "4c139541aefe65545f278795470d02c3fcd0e673" + "sha": "ce057e7b80baca7ef577ee1495ba034cdb3a491a" } }, { "git": { "name": "googleapis-discovery", "remote": "https://github.com/googleapis/googleapis-discovery.git", - "sha": "8f48e81408f5582f8bf17d0b959711d955988bb9" + "sha": "6b01eb5607e6ba0b3b931905bd779b28dc89b933" } } ], @@ -93,6 +93,7 @@ "docs/compute_v1/disk_types.rst", "docs/compute_v1/disks.rst", "docs/compute_v1/external_vpn_gateways.rst", + "docs/compute_v1/firewall_policies.rst", "docs/compute_v1/firewalls.rst", "docs/compute_v1/forwarding_rules.rst", "docs/compute_v1/global_addresses.rst", @@ -100,6 +101,7 @@ "docs/compute_v1/global_network_endpoint_groups.rst", "docs/compute_v1/global_operations.rst", "docs/compute_v1/global_organization_operations.rst", + "docs/compute_v1/global_public_delegated_prefixes.rst", "docs/compute_v1/health_checks.rst", "docs/compute_v1/images.rst", "docs/compute_v1/instance_group_managers.rst", @@ -119,6 +121,8 @@ "docs/compute_v1/node_types.rst", "docs/compute_v1/packet_mirrorings.rst", "docs/compute_v1/projects.rst", + "docs/compute_v1/public_advertised_prefixes.rst", + "docs/compute_v1/public_delegated_prefixes.rst", "docs/compute_v1/region_autoscalers.rst", "docs/compute_v1/region_backend_services.rst", "docs/compute_v1/region_commitments.rst", @@ -128,6 +132,7 @@ "docs/compute_v1/region_health_checks.rst", "docs/compute_v1/region_instance_group_managers.rst", "docs/compute_v1/region_instance_groups.rst", + "docs/compute_v1/region_instances.rst", "docs/compute_v1/region_network_endpoint_groups.rst", "docs/compute_v1/region_notification_endpoints.rst", "docs/compute_v1/region_operations.rst", @@ -216,6 +221,12 @@ "google/cloud/compute_v1/services/external_vpn_gateways/transports/__init__.py", "google/cloud/compute_v1/services/external_vpn_gateways/transports/base.py", "google/cloud/compute_v1/services/external_vpn_gateways/transports/rest.py", + "google/cloud/compute_v1/services/firewall_policies/__init__.py", + "google/cloud/compute_v1/services/firewall_policies/client.py", + "google/cloud/compute_v1/services/firewall_policies/pagers.py", + "google/cloud/compute_v1/services/firewall_policies/transports/__init__.py", + "google/cloud/compute_v1/services/firewall_policies/transports/base.py", + "google/cloud/compute_v1/services/firewall_policies/transports/rest.py", "google/cloud/compute_v1/services/firewalls/__init__.py", "google/cloud/compute_v1/services/firewalls/client.py", "google/cloud/compute_v1/services/firewalls/pagers.py", @@ -258,6 +269,12 @@ "google/cloud/compute_v1/services/global_organization_operations/transports/__init__.py", "google/cloud/compute_v1/services/global_organization_operations/transports/base.py", "google/cloud/compute_v1/services/global_organization_operations/transports/rest.py", + "google/cloud/compute_v1/services/global_public_delegated_prefixes/__init__.py", + "google/cloud/compute_v1/services/global_public_delegated_prefixes/client.py", + "google/cloud/compute_v1/services/global_public_delegated_prefixes/pagers.py", + "google/cloud/compute_v1/services/global_public_delegated_prefixes/transports/__init__.py", + "google/cloud/compute_v1/services/global_public_delegated_prefixes/transports/base.py", + "google/cloud/compute_v1/services/global_public_delegated_prefixes/transports/rest.py", "google/cloud/compute_v1/services/health_checks/__init__.py", "google/cloud/compute_v1/services/health_checks/client.py", "google/cloud/compute_v1/services/health_checks/pagers.py", @@ -371,6 +388,18 @@ "google/cloud/compute_v1/services/projects/transports/__init__.py", "google/cloud/compute_v1/services/projects/transports/base.py", "google/cloud/compute_v1/services/projects/transports/rest.py", + "google/cloud/compute_v1/services/public_advertised_prefixes/__init__.py", + "google/cloud/compute_v1/services/public_advertised_prefixes/client.py", + "google/cloud/compute_v1/services/public_advertised_prefixes/pagers.py", + "google/cloud/compute_v1/services/public_advertised_prefixes/transports/__init__.py", + "google/cloud/compute_v1/services/public_advertised_prefixes/transports/base.py", + "google/cloud/compute_v1/services/public_advertised_prefixes/transports/rest.py", + "google/cloud/compute_v1/services/public_delegated_prefixes/__init__.py", + "google/cloud/compute_v1/services/public_delegated_prefixes/client.py", + "google/cloud/compute_v1/services/public_delegated_prefixes/pagers.py", + "google/cloud/compute_v1/services/public_delegated_prefixes/transports/__init__.py", + "google/cloud/compute_v1/services/public_delegated_prefixes/transports/base.py", + "google/cloud/compute_v1/services/public_delegated_prefixes/transports/rest.py", "google/cloud/compute_v1/services/region_autoscalers/__init__.py", "google/cloud/compute_v1/services/region_autoscalers/client.py", "google/cloud/compute_v1/services/region_autoscalers/pagers.py", @@ -425,6 +454,11 @@ "google/cloud/compute_v1/services/region_instance_groups/transports/__init__.py", "google/cloud/compute_v1/services/region_instance_groups/transports/base.py", "google/cloud/compute_v1/services/region_instance_groups/transports/rest.py", + "google/cloud/compute_v1/services/region_instances/__init__.py", + "google/cloud/compute_v1/services/region_instances/client.py", + "google/cloud/compute_v1/services/region_instances/transports/__init__.py", + "google/cloud/compute_v1/services/region_instances/transports/base.py", + "google/cloud/compute_v1/services/region_instances/transports/rest.py", "google/cloud/compute_v1/services/region_network_endpoint_groups/__init__.py", "google/cloud/compute_v1/services/region_network_endpoint_groups/client.py", "google/cloud/compute_v1/services/region_network_endpoint_groups/pagers.py", @@ -631,6 +665,7 @@ "tests/unit/gapic/compute_v1/test_disk_types.py", "tests/unit/gapic/compute_v1/test_disks.py", "tests/unit/gapic/compute_v1/test_external_vpn_gateways.py", + "tests/unit/gapic/compute_v1/test_firewall_policies.py", "tests/unit/gapic/compute_v1/test_firewalls.py", "tests/unit/gapic/compute_v1/test_forwarding_rules.py", "tests/unit/gapic/compute_v1/test_global_addresses.py", @@ -638,6 +673,7 @@ "tests/unit/gapic/compute_v1/test_global_network_endpoint_groups.py", "tests/unit/gapic/compute_v1/test_global_operations.py", "tests/unit/gapic/compute_v1/test_global_organization_operations.py", + "tests/unit/gapic/compute_v1/test_global_public_delegated_prefixes.py", "tests/unit/gapic/compute_v1/test_health_checks.py", "tests/unit/gapic/compute_v1/test_images.py", "tests/unit/gapic/compute_v1/test_instance_group_managers.py", @@ -657,6 +693,8 @@ "tests/unit/gapic/compute_v1/test_node_types.py", "tests/unit/gapic/compute_v1/test_packet_mirrorings.py", "tests/unit/gapic/compute_v1/test_projects.py", + "tests/unit/gapic/compute_v1/test_public_advertised_prefixes.py", + "tests/unit/gapic/compute_v1/test_public_delegated_prefixes.py", "tests/unit/gapic/compute_v1/test_region_autoscalers.py", "tests/unit/gapic/compute_v1/test_region_backend_services.py", "tests/unit/gapic/compute_v1/test_region_commitments.py", @@ -666,6 +704,7 @@ "tests/unit/gapic/compute_v1/test_region_health_checks.py", "tests/unit/gapic/compute_v1/test_region_instance_group_managers.py", "tests/unit/gapic/compute_v1/test_region_instance_groups.py", + "tests/unit/gapic/compute_v1/test_region_instances.py", "tests/unit/gapic/compute_v1/test_region_network_endpoint_groups.py", "tests/unit/gapic/compute_v1/test_region_notification_endpoints.py", "tests/unit/gapic/compute_v1/test_region_operations.py", diff --git a/packages/google-cloud-compute/synth.py b/packages/google-cloud-compute/synth.py index 5fa5546df2c4..a6eb56c07a34 100644 --- a/packages/google-cloud-compute/synth.py +++ b/packages/google-cloud-compute/synth.py @@ -40,7 +40,7 @@ # Add templated files # ---------------------------------------------------------------------------- -templated_files = common.py_library(cov_level=99, microgenerator=True) +templated_files = common.py_library(cov_level=96, microgenerator=True) s.move( templated_files, excludes=[".coveragerc"] # the microgenerator has a good coveragerc file ) diff --git a/packages/google-cloud-compute/testing/constraints-3.6.txt b/packages/google-cloud-compute/testing/constraints-3.6.txt index 9d481b987ebe..e93042f1ab41 100644 --- a/packages/google-cloud-compute/testing/constraints-3.6.txt +++ b/packages/google-cloud-compute/testing/constraints-3.6.txt @@ -5,5 +5,6 @@ # 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.22.2 +google-api-core==1.28.0 proto-plus==1.13.0 +packaging==14.3 diff --git a/packages/google-cloud-compute/tests/system/test_smoke.py b/packages/google-cloud-compute/tests/system/test_smoke.py index 67d4560539bd..926937c7da9d 100644 --- a/packages/google-cloud-compute/tests/system/test_smoke.py +++ b/packages/google-cloud-compute/tests/system/test_smoke.py @@ -13,9 +13,8 @@ # limitations under the License. -import requests import time - +import google.api_core.exceptions from google.cloud.compute_v1.services.instances.client import InstancesClient from google.cloud.compute_v1.types import ( @@ -84,18 +83,18 @@ def test_aggregated_list(self): self.assertTrue(presented) def test_client_error(self): - with self.assertRaises(expected_exception=requests.exceptions.HTTPError) as ex: + with self.assertRaises( + expected_exception=google.api_core.exceptions.BadRequest + ): self.client.get(instance=self.name, zone=self.DEFAULT_ZONE) - self.assertIn("Bad Request", str(ex.exception.args)) def test_api_error(self): - with self.assertRaises(expected_exception=requests.exceptions.HTTPError) as ex: + with self.assertRaises(expected_exception=google.api_core.exceptions.NotFound): self.client.get( project=self.DEFAULT_PROJECT, zone=self.DEFAULT_ZONE, instance="nonexistent9999123412314", ) - self.assertIn("Not Found", str(ex.exception.args)) def test_zero_values(self): with self.assertRaises(expected_exception=TypeError) as ex: diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_accelerator_types.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_accelerator_types.py index f017384fb3d9..ac74df7e8e29 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_accelerator_types.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_accelerator_types.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.accelerator_types import AcceleratorTypesClient from google.cloud.compute_v1.services.accelerator_types import pagers from google.cloud.compute_v1.services.accelerator_types import transports -from google.cloud.compute_v1.services.accelerator_types.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.accelerator_types.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_addresses.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_addresses.py index 952efccff274..cefe5c688cac 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_addresses.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_addresses.py @@ -36,7 +36,6 @@ from google.cloud.compute_v1.services.addresses import AddressesClient from google.cloud.compute_v1.services.addresses import pagers from google.cloud.compute_v1.services.addresses import transports -from google.cloud.compute_v1.services.addresses.transports.base import _API_CORE_VERSION from google.cloud.compute_v1.services.addresses.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -45,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -57,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -572,6 +562,7 @@ def test_delete_rest( 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", @@ -607,6 +598,7 @@ def test_delete_rest( 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" @@ -808,6 +800,7 @@ def test_insert_rest( 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", @@ -843,6 +836,7 @@ def test_insert_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_autoscalers.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_autoscalers.py index 17c97bcc7553..736d95d15119 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_autoscalers.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_autoscalers.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.autoscalers import AutoscalersClient from google.cloud.compute_v1.services.autoscalers import pagers from google.cloud.compute_v1.services.autoscalers import transports -from google.cloud.compute_v1.services.autoscalers.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.autoscalers.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -593,6 +581,7 @@ def test_delete_rest( 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", @@ -628,6 +617,7 @@ def test_delete_rest( 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" @@ -714,6 +704,11 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetAutoscalerReq name="name_value", recommended_size=1693, region="region_value", + scaling_schedule_status={ + "key_value": compute.ScalingScheduleStatus( + last_start_time="last_start_time_value" + ) + }, self_link="self_link_value", status=compute.Autoscaler.Status.ACTIVE, status_details=[compute.AutoscalerStatusDetails(message="message_value")], @@ -741,6 +736,11 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetAutoscalerReq assert response.name == "name_value" assert response.recommended_size == 1693 assert response.region == "region_value" + assert response.scaling_schedule_status == { + "key_value": compute.ScalingScheduleStatus( + last_start_time="last_start_time_value" + ) + } assert response.self_link == "self_link_value" assert response.status == compute.Autoscaler.Status.ACTIVE assert response.status_details == [ @@ -825,6 +825,7 @@ def test_insert_rest( 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", @@ -860,6 +861,7 @@ def test_insert_rest( 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" @@ -1108,6 +1110,7 @@ def test_patch_rest( 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", @@ -1143,6 +1146,7 @@ def test_patch_rest( 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" @@ -1245,6 +1249,7 @@ def test_update_rest( 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", @@ -1280,6 +1285,7 @@ def test_update_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_backend_buckets.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_backend_buckets.py index efa7e1032bf2..986f8da5b716 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_backend_buckets.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_backend_buckets.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.backend_buckets import BackendBucketsClient from google.cloud.compute_v1.services.backend_buckets import pagers from google.cloud.compute_v1.services.backend_buckets import transports -from google.cloud.compute_v1.services.backend_buckets.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.backend_buckets.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -432,6 +420,7 @@ def test_add_signed_url_key_rest( 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", @@ -467,6 +456,7 @@ def test_add_signed_url_key_rest( 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" @@ -565,6 +555,7 @@ def test_delete_rest( 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", @@ -600,6 +591,7 @@ def test_delete_rest( 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" @@ -689,6 +681,7 @@ def test_delete_signed_url_key_rest( 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", @@ -724,6 +717,7 @@ def test_delete_signed_url_key_rest( 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" @@ -808,7 +802,11 @@ def test_get_rest( return_value = compute.BackendBucket( bucket_name="bucket_name_value", cdn_policy=compute.BackendBucketCdnPolicy( - cache_mode=compute.BackendBucketCdnPolicy.CacheMode.CACHE_ALL_STATIC + bypass_cache_on_request_headers=[ + compute.BackendBucketCdnPolicyBypassCacheOnRequestHeader( + header_name="header_name_value" + ) + ] ), creation_timestamp="creation_timestamp_value", custom_response_headers=["custom_response_headers_value"], @@ -832,7 +830,11 @@ def test_get_rest( assert isinstance(response, compute.BackendBucket) assert response.bucket_name == "bucket_name_value" assert response.cdn_policy == compute.BackendBucketCdnPolicy( - cache_mode=compute.BackendBucketCdnPolicy.CacheMode.CACHE_ALL_STATIC + bypass_cache_on_request_headers=[ + compute.BackendBucketCdnPolicyBypassCacheOnRequestHeader( + header_name="header_name_value" + ) + ] ) assert response.creation_timestamp == "creation_timestamp_value" assert response.custom_response_headers == ["custom_response_headers_value"] @@ -917,6 +919,7 @@ def test_insert_rest( 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", @@ -952,6 +955,7 @@ def test_insert_rest( 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" @@ -1179,6 +1183,7 @@ def test_patch_rest( 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", @@ -1214,6 +1219,7 @@ def test_patch_rest( 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" @@ -1314,6 +1320,7 @@ def test_update_rest( 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", @@ -1349,6 +1356,7 @@ def test_update_rest( 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" 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 228775ab2c4e..991770dd5c40 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 @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.backend_services import BackendServicesClient from google.cloud.compute_v1.services.backend_services import pagers from google.cloud.compute_v1.services.backend_services import transports -from google.cloud.compute_v1.services.backend_services.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.backend_services.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -442,6 +430,7 @@ def test_add_signed_url_key_rest( 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", @@ -477,6 +466,7 @@ def test_add_signed_url_key_rest( 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" @@ -736,6 +726,7 @@ def test_delete_rest( 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", @@ -771,6 +762,7 @@ def test_delete_rest( 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" @@ -861,6 +853,7 @@ def test_delete_signed_url_key_rest( 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", @@ -896,6 +889,7 @@ def test_delete_signed_url_key_rest( 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" @@ -983,7 +977,11 @@ def test_get_rest( compute.Backend(balancing_mode=compute.Backend.BalancingMode.CONNECTION) ], cdn_policy=compute.BackendServiceCdnPolicy( - cache_key_policy=compute.CacheKeyPolicy(include_host=True) + bypass_cache_on_request_headers=[ + compute.BackendServiceCdnPolicyBypassCacheOnRequestHeader( + header_name="header_name_value" + ) + ] ), circuit_breakers=compute.CircuitBreakers(max_connections=1608), connection_draining=compute.ConnectionDraining(draining_timeout_sec=2124), @@ -1008,6 +1006,7 @@ def test_get_rest( load_balancing_scheme=compute.BackendService.LoadBalancingScheme.EXTERNAL, locality_lb_policy=compute.BackendService.LocalityLbPolicy.INVALID_LB_POLICY, log_config=compute.BackendServiceLogConfig(enable=True), + max_stream_duration=compute.Duration(nanos=543), name="name_value", network="network_value", outlier_detection=compute.OutlierDetection( @@ -1041,7 +1040,11 @@ def test_get_rest( compute.Backend(balancing_mode=compute.Backend.BalancingMode.CONNECTION) ] assert response.cdn_policy == compute.BackendServiceCdnPolicy( - cache_key_policy=compute.CacheKeyPolicy(include_host=True) + bypass_cache_on_request_headers=[ + compute.BackendServiceCdnPolicyBypassCacheOnRequestHeader( + header_name="header_name_value" + ) + ] ) assert response.circuit_breakers == compute.CircuitBreakers(max_connections=1608) assert response.connection_draining == compute.ConnectionDraining( @@ -1074,6 +1077,7 @@ def test_get_rest( == compute.BackendService.LocalityLbPolicy.INVALID_LB_POLICY ) assert response.log_config == compute.BackendServiceLogConfig(enable=True) + assert response.max_stream_duration == compute.Duration(nanos=543) assert response.name == "name_value" assert response.network == "network_value" assert response.outlier_detection == compute.OutlierDetection( @@ -1264,6 +1268,7 @@ def test_insert_rest( 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", @@ -1299,6 +1304,7 @@ def test_insert_rest( 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" @@ -1526,6 +1532,7 @@ def test_patch_rest( 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", @@ -1561,6 +1568,7 @@ def test_patch_rest( 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" @@ -1661,6 +1669,7 @@ def test_set_security_policy_rest( 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", @@ -1696,6 +1705,7 @@ def test_set_security_policy_rest( 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" @@ -1798,6 +1808,7 @@ def test_update_rest( 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", @@ -1833,6 +1844,7 @@ def test_update_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_disk_types.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_disk_types.py index 04a81be73960..47bf9fdd7973 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_disk_types.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_disk_types.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.disk_types import DiskTypesClient from google.cloud.compute_v1.services.disk_types import pagers from google.cloud.compute_v1.services.disk_types import transports -from google.cloud.compute_v1.services.disk_types.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.disk_types.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" 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 9c92cd913349..e55b37af8d67 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 @@ -36,15 +36,15 @@ from google.cloud.compute_v1.services.disks import DisksClient from google.cloud.compute_v1.services.disks import pagers from google.cloud.compute_v1.services.disks import transports -from google.cloud.compute_v1.services.disks.transports.base import _API_CORE_VERSION from google.cloud.compute_v1.services.disks.transports.base import _GOOGLE_AUTH_VERSION from google.cloud.compute_v1.types import compute from google.oauth2 import service_account import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -55,16 +55,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -416,6 +406,7 @@ def test_add_resource_policies_rest( 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", @@ -451,6 +442,7 @@ def test_add_resource_policies_rest( 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" @@ -706,6 +698,7 @@ def test_create_snapshot_rest( 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", @@ -741,6 +734,7 @@ def test_create_snapshot_rest( 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" @@ -840,6 +834,7 @@ def test_delete_rest(transport: str = "rest", request_type=compute.DeleteDiskReq 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", @@ -875,6 +870,7 @@ def test_delete_rest(transport: str = "rest", request_type=compute.DeleteDiskReq 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" @@ -971,12 +967,15 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetDiskRequest): last_detach_timestamp="last_detach_timestamp_value", license_codes=["license_codes_value"], licenses=["licenses_value"], + location_hint="location_hint_value", name="name_value", options="options_value", physical_block_size_bytes="physical_block_size_bytes_value", + provisioned_iops="provisioned_iops_value", region="region_value", replica_zones=["replica_zones_value"], resource_policies=["resource_policies_value"], + satisfies_pzs=True, self_link="self_link_value", size_gb="size_gb_value", source_disk="source_disk_value", @@ -991,6 +990,7 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetDiskRequest): kms_key_name="kms_key_name_value" ), source_snapshot_id="source_snapshot_id_value", + source_storage_object="source_storage_object_value", status=compute.Disk.Status.CREATING, type_="type__value", users=["users_value"], @@ -1025,12 +1025,15 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetDiskRequest): assert response.last_detach_timestamp == "last_detach_timestamp_value" assert response.license_codes == ["license_codes_value"] assert response.licenses == ["licenses_value"] + assert response.location_hint == "location_hint_value" assert response.name == "name_value" assert response.options == "options_value" assert response.physical_block_size_bytes == "physical_block_size_bytes_value" + assert response.provisioned_iops == "provisioned_iops_value" assert response.region == "region_value" assert response.replica_zones == ["replica_zones_value"] assert response.resource_policies == ["resource_policies_value"] + assert response.satisfies_pzs is True assert response.self_link == "self_link_value" assert response.size_gb == "size_gb_value" assert response.source_disk == "source_disk_value" @@ -1045,6 +1048,7 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetDiskRequest): kms_key_name="kms_key_name_value" ) assert response.source_snapshot_id == "source_snapshot_id_value" + assert response.source_storage_object == "source_storage_object_value" assert response.status == compute.Disk.Status.CREATING assert response.type_ == "type__value" assert response.users == ["users_value"] @@ -1228,6 +1232,7 @@ def test_insert_rest(transport: str = "rest", request_type=compute.InsertDiskReq 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", @@ -1263,6 +1268,7 @@ def test_insert_rest(transport: str = "rest", request_type=compute.InsertDiskReq 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" @@ -1485,6 +1491,7 @@ def test_remove_resource_policies_rest( 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", @@ -1520,6 +1527,7 @@ def test_remove_resource_policies_rest( 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" @@ -1623,6 +1631,7 @@ def test_resize_rest(transport: str = "rest", request_type=compute.ResizeDiskReq 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", @@ -1658,6 +1667,7 @@ def test_resize_rest(transport: str = "rest", request_type=compute.ResizeDiskReq 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" @@ -1881,6 +1891,7 @@ def test_set_labels_rest( 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", @@ -1916,6 +1927,7 @@ def test_set_labels_rest( 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" 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 694c39b0b06e..e3fcde065f0b 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 @@ -38,9 +38,6 @@ ) from google.cloud.compute_v1.services.external_vpn_gateways import pagers from google.cloud.compute_v1.services.external_vpn_gateways import transports -from google.cloud.compute_v1.services.external_vpn_gateways.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.external_vpn_gateways.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -49,8 +46,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -61,16 +59,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -445,6 +433,7 @@ def test_delete_rest( 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", @@ -480,6 +469,7 @@ def test_delete_rest( 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" @@ -676,6 +666,7 @@ def test_insert_rest( 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", @@ -711,6 +702,7 @@ def test_insert_rest( 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" @@ -959,6 +951,7 @@ def test_set_labels_rest( 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", @@ -994,6 +987,7 @@ def test_set_labels_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_firewall_policies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_firewall_policies.py new file mode 100644 index 000000000000..9edef8eda46d --- /dev/null +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_firewall_policies.py @@ -0,0 +1,2844 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from requests import Response +from requests.sessions import Session + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.compute_v1.services.firewall_policies import FirewallPoliciesClient +from google.cloud.compute_v1.services.firewall_policies import pagers +from google.cloud.compute_v1.services.firewall_policies import transports +from google.cloud.compute_v1.services.firewall_policies.transports.base import ( + _GOOGLE_AUTH_VERSION, +) +from google.cloud.compute_v1.types import compute +from google.oauth2 import service_account +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + + +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 + ) + + +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 FirewallPoliciesClient._get_default_mtls_endpoint(None) is None + assert ( + FirewallPoliciesClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + FirewallPoliciesClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + FirewallPoliciesClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + FirewallPoliciesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + FirewallPoliciesClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +@pytest.mark.parametrize("client_class", [FirewallPoliciesClient,]) +def test_firewall_policies_client_from_service_account_info(client_class): + 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) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == "compute.googleapis.com:443" + + +@pytest.mark.parametrize("client_class", [FirewallPoliciesClient,]) +def test_firewall_policies_client_from_service_account_file(client_class): + 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") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == "compute.googleapis.com:443" + + +def test_firewall_policies_client_get_transport_class(): + transport = FirewallPoliciesClient.get_transport_class() + available_transports = [ + transports.FirewallPoliciesRestTransport, + ] + assert transport in available_transports + + transport = FirewallPoliciesClient.get_transport_class("rest") + assert transport == transports.FirewallPoliciesRestTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [(FirewallPoliciesClient, transports.FirewallPoliciesRestTransport, "rest"),], +) +@mock.patch.object( + FirewallPoliciesClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(FirewallPoliciesClient), +) +def test_firewall_policies_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(FirewallPoliciesClient, "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(FirewallPoliciesClient, "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(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, + ) + + # 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() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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() + 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, + ) + + # 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): + client = client_class() + + # 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): + client = client_class() + + # 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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + FirewallPoliciesClient, + transports.FirewallPoliciesRestTransport, + "rest", + "true", + ), + ( + FirewallPoliciesClient, + transports.FirewallPoliciesRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + FirewallPoliciesClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(FirewallPoliciesClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_firewall_policies_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + 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, + ) + + # 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 + 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() + 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, + ) + + # 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() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [(FirewallPoliciesClient, transports.FirewallPoliciesRestTransport, "rest"),], +) +def test_firewall_policies_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [(FirewallPoliciesClient, transports.FirewallPoliciesRestTransport, "rest"),], +) +def test_firewall_policies_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # 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) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_add_association_rest( + transport: str = "rest", request_type=compute.AddAssociationFirewallPolicyRequest +): + client = FirewallPoliciesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + error=compute.Error(errors=[compute.Errors(code="code_value")]), + http_error_message="http_error_message_value", + http_error_status_code=2374, + id="id_value", + 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="target_id_value", + target_link="target_link_value", + user="user_value", + warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)], + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.add_association(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Operation) + 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.error == compute.Error(errors=[compute.Errors(code="code_value")]) + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == "id_value" + 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 == "target_id_value" + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.warnings == [ + compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED) + ] + assert response.zone == "zone_value" + + +def test_add_association_rest_from_dict(): + test_add_association_rest(request_type=dict) + + +def test_add_association_rest_flattened(): + client = FirewallPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + firewall_policy_association_resource = compute.FirewallPolicyAssociation( + attachment_target="attachment_target_value" + ) + client.add_association( + firewall_policy="firewall_policy_value", + firewall_policy_association_resource=firewall_policy_association_resource, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "firewall_policy_value" in http_call[1] + str(body) + assert compute.FirewallPolicyAssociation.to_json( + firewall_policy_association_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) in http_call[1] + str(body) + + +def test_add_association_rest_flattened_error(): + client = FirewallPoliciesClient(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.add_association( + compute.AddAssociationFirewallPolicyRequest(), + firewall_policy="firewall_policy_value", + firewall_policy_association_resource=compute.FirewallPolicyAssociation( + attachment_target="attachment_target_value" + ), + ) + + +def test_add_rule_rest( + transport: str = "rest", request_type=compute.AddRuleFirewallPolicyRequest +): + client = FirewallPoliciesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + error=compute.Error(errors=[compute.Errors(code="code_value")]), + http_error_message="http_error_message_value", + http_error_status_code=2374, + id="id_value", + 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="target_id_value", + target_link="target_link_value", + user="user_value", + warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)], + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.add_rule(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Operation) + 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.error == compute.Error(errors=[compute.Errors(code="code_value")]) + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == "id_value" + 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 == "target_id_value" + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.warnings == [ + compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED) + ] + assert response.zone == "zone_value" + + +def test_add_rule_rest_from_dict(): + test_add_rule_rest(request_type=dict) + + +def test_add_rule_rest_flattened(): + client = FirewallPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + firewall_policy_rule_resource = compute.FirewallPolicyRule( + action="action_value" + ) + client.add_rule( + firewall_policy="firewall_policy_value", + firewall_policy_rule_resource=firewall_policy_rule_resource, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "firewall_policy_value" in http_call[1] + str(body) + assert compute.FirewallPolicyRule.to_json( + firewall_policy_rule_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) in http_call[1] + str(body) + + +def test_add_rule_rest_flattened_error(): + client = FirewallPoliciesClient(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.add_rule( + compute.AddRuleFirewallPolicyRequest(), + firewall_policy="firewall_policy_value", + firewall_policy_rule_resource=compute.FirewallPolicyRule( + action="action_value" + ), + ) + + +def test_clone_rules_rest( + transport: str = "rest", request_type=compute.CloneRulesFirewallPolicyRequest +): + client = FirewallPoliciesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + error=compute.Error(errors=[compute.Errors(code="code_value")]), + http_error_message="http_error_message_value", + http_error_status_code=2374, + id="id_value", + 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="target_id_value", + target_link="target_link_value", + user="user_value", + warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)], + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.clone_rules(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Operation) + 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.error == compute.Error(errors=[compute.Errors(code="code_value")]) + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == "id_value" + 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 == "target_id_value" + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.warnings == [ + compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED) + ] + assert response.zone == "zone_value" + + +def test_clone_rules_rest_from_dict(): + test_clone_rules_rest(request_type=dict) + + +def test_clone_rules_rest_flattened(): + client = FirewallPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.clone_rules(firewall_policy="firewall_policy_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "firewall_policy_value" in http_call[1] + str(body) + + +def test_clone_rules_rest_flattened_error(): + client = FirewallPoliciesClient(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.clone_rules( + compute.CloneRulesFirewallPolicyRequest(), + firewall_policy="firewall_policy_value", + ) + + +def test_delete_rest( + transport: str = "rest", request_type=compute.DeleteFirewallPolicyRequest +): + client = FirewallPoliciesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + error=compute.Error(errors=[compute.Errors(code="code_value")]), + http_error_message="http_error_message_value", + http_error_status_code=2374, + id="id_value", + 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="target_id_value", + target_link="target_link_value", + user="user_value", + warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)], + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + 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, compute.Operation) + 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.error == compute.Error(errors=[compute.Errors(code="code_value")]) + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == "id_value" + 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 == "target_id_value" + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.warnings == [ + compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED) + ] + assert response.zone == "zone_value" + + +def test_delete_rest_from_dict(): + test_delete_rest(request_type=dict) + + +def test_delete_rest_flattened(): + client = FirewallPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete(firewall_policy="firewall_policy_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "firewall_policy_value" in http_call[1] + str(body) + + +def test_delete_rest_flattened_error(): + client = FirewallPoliciesClient(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( + compute.DeleteFirewallPolicyRequest(), + firewall_policy="firewall_policy_value", + ) + + +def test_get_rest( + transport: str = "rest", request_type=compute.GetFirewallPolicyRequest +): + client = FirewallPoliciesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.FirewallPolicy( + associations=[ + compute.FirewallPolicyAssociation( + attachment_target="attachment_target_value" + ) + ], + creation_timestamp="creation_timestamp_value", + description="description_value", + display_name="display_name_value", + fingerprint="fingerprint_value", + id="id_value", + kind="kind_value", + name="name_value", + parent="parent_value", + rule_tuple_count=1737, + rules=[compute.FirewallPolicyRule(action="action_value")], + self_link="self_link_value", + self_link_with_id="self_link_with_id_value", + short_name="short_name_value", + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.FirewallPolicy.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + 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.FirewallPolicy) + assert response.associations == [ + compute.FirewallPolicyAssociation(attachment_target="attachment_target_value") + ] + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.display_name == "display_name_value" + assert response.fingerprint == "fingerprint_value" + assert response.id == "id_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.parent == "parent_value" + assert response.rule_tuple_count == 1737 + assert response.rules == [compute.FirewallPolicyRule(action="action_value")] + assert response.self_link == "self_link_value" + assert response.self_link_with_id == "self_link_with_id_value" + assert response.short_name == "short_name_value" + + +def test_get_rest_from_dict(): + test_get_rest(request_type=dict) + + +def test_get_rest_flattened(): + client = FirewallPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.FirewallPolicy() + + # Wrap the value into a proper Response obj + json_return_value = compute.FirewallPolicy.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get(firewall_policy="firewall_policy_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "firewall_policy_value" in http_call[1] + str(body) + + +def test_get_rest_flattened_error(): + client = FirewallPoliciesClient(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( + compute.GetFirewallPolicyRequest(), firewall_policy="firewall_policy_value", + ) + + +def test_get_association_rest( + transport: str = "rest", request_type=compute.GetAssociationFirewallPolicyRequest +): + client = FirewallPoliciesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.FirewallPolicyAssociation( + attachment_target="attachment_target_value", + display_name="display_name_value", + firewall_policy_id="firewall_policy_id_value", + name="name_value", + short_name="short_name_value", + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.FirewallPolicyAssociation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_association(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.FirewallPolicyAssociation) + assert response.attachment_target == "attachment_target_value" + assert response.display_name == "display_name_value" + assert response.firewall_policy_id == "firewall_policy_id_value" + assert response.name == "name_value" + assert response.short_name == "short_name_value" + + +def test_get_association_rest_from_dict(): + test_get_association_rest(request_type=dict) + + +def test_get_association_rest_flattened(): + client = FirewallPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.FirewallPolicyAssociation() + + # Wrap the value into a proper Response obj + json_return_value = compute.FirewallPolicyAssociation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_association(firewall_policy="firewall_policy_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "firewall_policy_value" in http_call[1] + str(body) + + +def test_get_association_rest_flattened_error(): + client = FirewallPoliciesClient(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_association( + compute.GetAssociationFirewallPolicyRequest(), + firewall_policy="firewall_policy_value", + ) + + +def test_get_iam_policy_rest( + transport: str = "rest", request_type=compute.GetIamPolicyFirewallPolicyRequest +): + client = FirewallPoliciesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Policy( + audit_configs=[ + compute.AuditConfig( + audit_log_configs=[ + compute.AuditLogConfig( + exempted_members=["exempted_members_value"] + ) + ] + ) + ], + bindings=[compute.Binding(binding_id="binding_id_value")], + etag="etag_value", + iam_owned=True, + rules=[compute.Rule(action=compute.Rule.Action.ALLOW)], + version=774, + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.Policy.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + 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.audit_configs == [ + compute.AuditConfig( + audit_log_configs=[ + compute.AuditLogConfig(exempted_members=["exempted_members_value"]) + ] + ) + ] + assert response.bindings == [compute.Binding(binding_id="binding_id_value")] + assert response.etag == "etag_value" + assert response.iam_owned is True + assert response.rules == [compute.Rule(action=compute.Rule.Action.ALLOW)] + assert response.version == 774 + + +def test_get_iam_policy_rest_from_dict(): + test_get_iam_policy_rest(request_type=dict) + + +def test_get_iam_policy_rest_flattened(): + client = FirewallPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Policy() + + # Wrap the value into a proper Response obj + json_return_value = compute.Policy.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # 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(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "resource_value" in http_call[1] + str(body) + + +def test_get_iam_policy_rest_flattened_error(): + client = FirewallPoliciesClient(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( + compute.GetIamPolicyFirewallPolicyRequest(), resource="resource_value", + ) + + +def test_get_rule_rest( + transport: str = "rest", request_type=compute.GetRuleFirewallPolicyRequest +): + client = FirewallPoliciesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.FirewallPolicyRule( + action="action_value", + description="description_value", + direction=compute.FirewallPolicyRule.Direction.EGRESS, + disabled=True, + enable_logging=True, + kind="kind_value", + match=compute.FirewallPolicyRuleMatcher( + dest_ip_ranges=["dest_ip_ranges_value"] + ), + priority=898, + rule_tuple_count=1737, + target_resources=["target_resources_value"], + target_service_accounts=["target_service_accounts_value"], + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.FirewallPolicyRule.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_rule(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.FirewallPolicyRule) + assert response.action == "action_value" + assert response.description == "description_value" + assert response.direction == compute.FirewallPolicyRule.Direction.EGRESS + assert response.disabled is True + assert response.enable_logging is True + assert response.kind == "kind_value" + assert response.match == compute.FirewallPolicyRuleMatcher( + dest_ip_ranges=["dest_ip_ranges_value"] + ) + assert response.priority == 898 + assert response.rule_tuple_count == 1737 + assert response.target_resources == ["target_resources_value"] + assert response.target_service_accounts == ["target_service_accounts_value"] + + +def test_get_rule_rest_from_dict(): + test_get_rule_rest(request_type=dict) + + +def test_get_rule_rest_flattened(): + client = FirewallPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.FirewallPolicyRule() + + # Wrap the value into a proper Response obj + json_return_value = compute.FirewallPolicyRule.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_rule(firewall_policy="firewall_policy_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "firewall_policy_value" in http_call[1] + str(body) + + +def test_get_rule_rest_flattened_error(): + client = FirewallPoliciesClient(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_rule( + compute.GetRuleFirewallPolicyRequest(), + firewall_policy="firewall_policy_value", + ) + + +def test_insert_rest( + transport: str = "rest", request_type=compute.InsertFirewallPolicyRequest +): + client = FirewallPoliciesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + error=compute.Error(errors=[compute.Errors(code="code_value")]), + http_error_message="http_error_message_value", + http_error_status_code=2374, + id="id_value", + 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="target_id_value", + target_link="target_link_value", + user="user_value", + warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)], + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + 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, compute.Operation) + 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.error == compute.Error(errors=[compute.Errors(code="code_value")]) + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == "id_value" + 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 == "target_id_value" + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.warnings == [ + compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED) + ] + assert response.zone == "zone_value" + + +def test_insert_rest_from_dict(): + test_insert_rest(request_type=dict) + + +def test_insert_rest_flattened(): + client = FirewallPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + firewall_policy_resource = compute.FirewallPolicy( + associations=[ + compute.FirewallPolicyAssociation( + attachment_target="attachment_target_value" + ) + ] + ) + client.insert(firewall_policy_resource=firewall_policy_resource,) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert compute.FirewallPolicy.to_json( + firewall_policy_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) in http_call[1] + str(body) + + +def test_insert_rest_flattened_error(): + client = FirewallPoliciesClient(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.insert( + compute.InsertFirewallPolicyRequest(), + firewall_policy_resource=compute.FirewallPolicy( + associations=[ + compute.FirewallPolicyAssociation( + attachment_target="attachment_target_value" + ) + ] + ), + ) + + +def test_list_rest( + transport: str = "rest", request_type=compute.ListFirewallPoliciesRequest +): + client = FirewallPoliciesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.FirewallPolicyList( + id="id_value", + items=[ + compute.FirewallPolicy( + associations=[ + compute.FirewallPolicyAssociation( + attachment_target="attachment_target_value" + ) + ] + ) + ], + kind="kind_value", + next_page_token="next_page_token_value", + warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.FirewallPolicyList.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + 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.items == [ + compute.FirewallPolicy( + associations=[ + compute.FirewallPolicyAssociation( + attachment_target="attachment_target_value" + ) + ] + ) + ] + assert response.kind == "kind_value" + assert response.next_page_token == "next_page_token_value" + assert response.warning == compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED) + + +def test_list_rest_from_dict(): + test_list_rest(request_type=dict) + + +def test_list_rest_flattened(): + client = FirewallPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.FirewallPolicyList() + + # Wrap the value into a proper Response obj + json_return_value = compute.FirewallPolicyList.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list() + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + + +def test_list_rest_flattened_error(): + client = FirewallPoliciesClient(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(compute.ListFirewallPoliciesRequest(),) + + +def test_list_pager(): + client = FirewallPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Set the response as a series of pages + response = ( + compute.FirewallPolicyList( + items=[ + compute.FirewallPolicy(), + compute.FirewallPolicy(), + compute.FirewallPolicy(), + ], + next_page_token="abc", + ), + compute.FirewallPolicyList(items=[], next_page_token="def",), + compute.FirewallPolicyList( + items=[compute.FirewallPolicy(),], next_page_token="ghi", + ), + compute.FirewallPolicyList( + items=[compute.FirewallPolicy(), compute.FirewallPolicy(),], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(compute.FirewallPolicyList.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 + + metadata = () + pager = client.list(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, compute.FirewallPolicy) for i in results) + + pages = list(client.list(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_list_associations_rest( + transport: str = "rest", request_type=compute.ListAssociationsFirewallPolicyRequest +): + client = FirewallPoliciesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.FirewallPoliciesListAssociationsResponse( + associations=[ + compute.FirewallPolicyAssociation( + attachment_target="attachment_target_value" + ) + ], + kind="kind_value", + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.FirewallPoliciesListAssociationsResponse.to_json( + return_value + ) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_associations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.FirewallPoliciesListAssociationsResponse) + assert response.associations == [ + compute.FirewallPolicyAssociation(attachment_target="attachment_target_value") + ] + assert response.kind == "kind_value" + + +def test_list_associations_rest_from_dict(): + test_list_associations_rest(request_type=dict) + + +def test_list_associations_rest_flattened(): + client = FirewallPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.FirewallPoliciesListAssociationsResponse() + + # Wrap the value into a proper Response obj + json_return_value = compute.FirewallPoliciesListAssociationsResponse.to_json( + return_value + ) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_associations() + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + + +def test_list_associations_rest_flattened_error(): + client = FirewallPoliciesClient(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_associations(compute.ListAssociationsFirewallPolicyRequest(),) + + +def test_move_rest( + transport: str = "rest", request_type=compute.MoveFirewallPolicyRequest +): + client = FirewallPoliciesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + error=compute.Error(errors=[compute.Errors(code="code_value")]), + http_error_message="http_error_message_value", + http_error_status_code=2374, + id="id_value", + 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="target_id_value", + target_link="target_link_value", + user="user_value", + warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)], + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.move(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Operation) + 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.error == compute.Error(errors=[compute.Errors(code="code_value")]) + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == "id_value" + 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 == "target_id_value" + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.warnings == [ + compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED) + ] + assert response.zone == "zone_value" + + +def test_move_rest_from_dict(): + test_move_rest(request_type=dict) + + +def test_move_rest_flattened(): + client = FirewallPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.move(firewall_policy="firewall_policy_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "firewall_policy_value" in http_call[1] + str(body) + + +def test_move_rest_flattened_error(): + client = FirewallPoliciesClient(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.move( + compute.MoveFirewallPolicyRequest(), + firewall_policy="firewall_policy_value", + ) + + +def test_patch_rest( + transport: str = "rest", request_type=compute.PatchFirewallPolicyRequest +): + client = FirewallPoliciesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + error=compute.Error(errors=[compute.Errors(code="code_value")]), + http_error_message="http_error_message_value", + http_error_status_code=2374, + id="id_value", + 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="target_id_value", + target_link="target_link_value", + user="user_value", + warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)], + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.patch(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Operation) + 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.error == compute.Error(errors=[compute.Errors(code="code_value")]) + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == "id_value" + 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 == "target_id_value" + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.warnings == [ + compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED) + ] + assert response.zone == "zone_value" + + +def test_patch_rest_from_dict(): + test_patch_rest(request_type=dict) + + +def test_patch_rest_flattened(): + client = FirewallPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + firewall_policy_resource = compute.FirewallPolicy( + associations=[ + compute.FirewallPolicyAssociation( + attachment_target="attachment_target_value" + ) + ] + ) + client.patch( + firewall_policy="firewall_policy_value", + firewall_policy_resource=firewall_policy_resource, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "firewall_policy_value" in http_call[1] + str(body) + assert compute.FirewallPolicy.to_json( + firewall_policy_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) in http_call[1] + str(body) + + +def test_patch_rest_flattened_error(): + client = FirewallPoliciesClient(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.patch( + compute.PatchFirewallPolicyRequest(), + firewall_policy="firewall_policy_value", + firewall_policy_resource=compute.FirewallPolicy( + associations=[ + compute.FirewallPolicyAssociation( + attachment_target="attachment_target_value" + ) + ] + ), + ) + + +def test_patch_rule_rest( + transport: str = "rest", request_type=compute.PatchRuleFirewallPolicyRequest +): + client = FirewallPoliciesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + error=compute.Error(errors=[compute.Errors(code="code_value")]), + http_error_message="http_error_message_value", + http_error_status_code=2374, + id="id_value", + 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="target_id_value", + target_link="target_link_value", + user="user_value", + warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)], + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.patch_rule(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Operation) + 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.error == compute.Error(errors=[compute.Errors(code="code_value")]) + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == "id_value" + 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 == "target_id_value" + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.warnings == [ + compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED) + ] + assert response.zone == "zone_value" + + +def test_patch_rule_rest_from_dict(): + test_patch_rule_rest(request_type=dict) + + +def test_patch_rule_rest_flattened(): + client = FirewallPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + firewall_policy_rule_resource = compute.FirewallPolicyRule( + action="action_value" + ) + client.patch_rule( + firewall_policy="firewall_policy_value", + firewall_policy_rule_resource=firewall_policy_rule_resource, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "firewall_policy_value" in http_call[1] + str(body) + assert compute.FirewallPolicyRule.to_json( + firewall_policy_rule_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) in http_call[1] + str(body) + + +def test_patch_rule_rest_flattened_error(): + client = FirewallPoliciesClient(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.patch_rule( + compute.PatchRuleFirewallPolicyRequest(), + firewall_policy="firewall_policy_value", + firewall_policy_rule_resource=compute.FirewallPolicyRule( + action="action_value" + ), + ) + + +def test_remove_association_rest( + transport: str = "rest", request_type=compute.RemoveAssociationFirewallPolicyRequest +): + client = FirewallPoliciesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + error=compute.Error(errors=[compute.Errors(code="code_value")]), + http_error_message="http_error_message_value", + http_error_status_code=2374, + id="id_value", + 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="target_id_value", + target_link="target_link_value", + user="user_value", + warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)], + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.remove_association(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Operation) + 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.error == compute.Error(errors=[compute.Errors(code="code_value")]) + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == "id_value" + 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 == "target_id_value" + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.warnings == [ + compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED) + ] + assert response.zone == "zone_value" + + +def test_remove_association_rest_from_dict(): + test_remove_association_rest(request_type=dict) + + +def test_remove_association_rest_flattened(): + client = FirewallPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.remove_association(firewall_policy="firewall_policy_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "firewall_policy_value" in http_call[1] + str(body) + + +def test_remove_association_rest_flattened_error(): + client = FirewallPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_association( + compute.RemoveAssociationFirewallPolicyRequest(), + firewall_policy="firewall_policy_value", + ) + + +def test_remove_rule_rest( + transport: str = "rest", request_type=compute.RemoveRuleFirewallPolicyRequest +): + client = FirewallPoliciesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + error=compute.Error(errors=[compute.Errors(code="code_value")]), + http_error_message="http_error_message_value", + http_error_status_code=2374, + id="id_value", + 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="target_id_value", + target_link="target_link_value", + user="user_value", + warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)], + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.remove_rule(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Operation) + 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.error == compute.Error(errors=[compute.Errors(code="code_value")]) + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == "id_value" + 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 == "target_id_value" + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.warnings == [ + compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED) + ] + assert response.zone == "zone_value" + + +def test_remove_rule_rest_from_dict(): + test_remove_rule_rest(request_type=dict) + + +def test_remove_rule_rest_flattened(): + client = FirewallPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.remove_rule(firewall_policy="firewall_policy_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "firewall_policy_value" in http_call[1] + str(body) + + +def test_remove_rule_rest_flattened_error(): + client = FirewallPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_rule( + compute.RemoveRuleFirewallPolicyRequest(), + firewall_policy="firewall_policy_value", + ) + + +def test_set_iam_policy_rest( + transport: str = "rest", request_type=compute.SetIamPolicyFirewallPolicyRequest +): + client = FirewallPoliciesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Policy( + audit_configs=[ + compute.AuditConfig( + audit_log_configs=[ + compute.AuditLogConfig( + exempted_members=["exempted_members_value"] + ) + ] + ) + ], + bindings=[compute.Binding(binding_id="binding_id_value")], + etag="etag_value", + iam_owned=True, + rules=[compute.Rule(action=compute.Rule.Action.ALLOW)], + version=774, + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.Policy.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + 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.audit_configs == [ + compute.AuditConfig( + audit_log_configs=[ + compute.AuditLogConfig(exempted_members=["exempted_members_value"]) + ] + ) + ] + assert response.bindings == [compute.Binding(binding_id="binding_id_value")] + assert response.etag == "etag_value" + assert response.iam_owned is True + assert response.rules == [compute.Rule(action=compute.Rule.Action.ALLOW)] + assert response.version == 774 + + +def test_set_iam_policy_rest_from_dict(): + test_set_iam_policy_rest(request_type=dict) + + +def test_set_iam_policy_rest_flattened(): + client = FirewallPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Policy() + + # Wrap the value into a proper Response obj + json_return_value = compute.Policy.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + global_organization_set_policy_request_resource = compute.GlobalOrganizationSetPolicyRequest( + bindings=[compute.Binding(binding_id="binding_id_value")] + ) + client.set_iam_policy( + resource="resource_value", + global_organization_set_policy_request_resource=global_organization_set_policy_request_resource, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "resource_value" in http_call[1] + str(body) + assert compute.GlobalOrganizationSetPolicyRequest.to_json( + global_organization_set_policy_request_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) in http_call[1] + str(body) + + +def test_set_iam_policy_rest_flattened_error(): + client = FirewallPoliciesClient(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( + compute.SetIamPolicyFirewallPolicyRequest(), + resource="resource_value", + global_organization_set_policy_request_resource=compute.GlobalOrganizationSetPolicyRequest( + bindings=[compute.Binding(binding_id="binding_id_value")] + ), + ) + + +def test_test_iam_permissions_rest( + transport: str = "rest", + request_type=compute.TestIamPermissionsFirewallPolicyRequest, +): + client = FirewallPoliciesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.TestPermissionsResponse( + permissions=["permissions_value"], + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.TestPermissionsResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + 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_from_dict(): + test_test_iam_permissions_rest(request_type=dict) + + +def test_test_iam_permissions_rest_flattened(): + client = FirewallPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.TestPermissionsResponse() + + # Wrap the value into a proper Response obj + json_return_value = compute.TestPermissionsResponse.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + test_permissions_request_resource = compute.TestPermissionsRequest( + permissions=["permissions_value"] + ) + client.test_iam_permissions( + resource="resource_value", + test_permissions_request_resource=test_permissions_request_resource, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "resource_value" in http_call[1] + str(body) + assert compute.TestPermissionsRequest.to_json( + test_permissions_request_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) in http_call[1] + str(body) + + +def test_test_iam_permissions_rest_flattened_error(): + client = FirewallPoliciesClient(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( + compute.TestIamPermissionsFirewallPolicyRequest(), + resource="resource_value", + test_permissions_request_resource=compute.TestPermissionsRequest( + permissions=["permissions_value"] + ), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.FirewallPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FirewallPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.FirewallPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FirewallPoliciesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.FirewallPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FirewallPoliciesClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.FirewallPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = FirewallPoliciesClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize("transport_class", [transports.FirewallPoliciesRestTransport,]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_firewall_policies_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.FirewallPoliciesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_firewall_policies_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.compute_v1.services.firewall_policies.transports.FirewallPoliciesTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.FirewallPoliciesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "add_association", + "add_rule", + "clone_rules", + "delete", + "get", + "get_association", + "get_iam_policy", + "get_rule", + "insert", + "list", + "list_associations", + "move", + "patch", + "patch_rule", + "remove_association", + "remove_rule", + "set_iam_policy", + "test_iam_permissions", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_firewall_policies_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.firewall_policies.transports.FirewallPoliciesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FirewallPoliciesTransport( + 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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_firewall_policies_base_transport_with_credentials_file_old_google_auth(): + # 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.firewall_policies.transports.FirewallPoliciesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FirewallPoliciesTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +def test_firewall_policies_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.compute_v1.services.firewall_policies.transports.FirewallPoliciesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FirewallPoliciesTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_firewall_policies_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + FirewallPoliciesClient() + 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, + ) + + +@requires_google_auth_lt_1_25_0 +def test_firewall_policies_auth_adc_old_google_auth(): + # 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) + FirewallPoliciesClient() + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +def test_firewall_policies_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.FirewallPoliciesRestTransport( + 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_firewall_policies_host_no_port(): + client = FirewallPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="compute.googleapis.com" + ), + ) + assert client.transport._host == "compute.googleapis.com:443" + + +def test_firewall_policies_host_with_port(): + client = FirewallPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="compute.googleapis.com:8000" + ), + ) + assert client.transport._host == "compute.googleapis.com:8000" + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = FirewallPoliciesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = FirewallPoliciesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = FirewallPoliciesClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder,) + actual = FirewallPoliciesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = FirewallPoliciesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = FirewallPoliciesClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization,) + actual = FirewallPoliciesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = FirewallPoliciesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = FirewallPoliciesClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project,) + actual = FirewallPoliciesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = FirewallPoliciesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = FirewallPoliciesClient.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 = FirewallPoliciesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = FirewallPoliciesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = FirewallPoliciesClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.FirewallPoliciesTransport, "_prep_wrapped_messages" + ) as prep: + client = FirewallPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.FirewallPoliciesTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = FirewallPoliciesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_firewalls.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_firewalls.py index e5973a5fa745..de0fde737582 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_firewalls.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_firewalls.py @@ -36,7 +36,6 @@ from google.cloud.compute_v1.services.firewalls import FirewallsClient from google.cloud.compute_v1.services.firewalls import pagers from google.cloud.compute_v1.services.firewalls import transports -from google.cloud.compute_v1.services.firewalls.transports.base import _API_CORE_VERSION from google.cloud.compute_v1.services.firewalls.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -45,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -57,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -419,6 +409,7 @@ def test_delete_rest( 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", @@ -454,6 +445,7 @@ def test_delete_rest( 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" @@ -530,9 +522,9 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetFirewallReque with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. return_value = compute.Firewall( - allowed=[compute.Allowed(i_p_protocol="i_p_protocol_value")], + allowed=[compute.Allowed(I_p_protocol="I_p_protocol_value")], creation_timestamp="creation_timestamp_value", - denied=[compute.Denied(i_p_protocol="i_p_protocol_value")], + denied=[compute.Denied(I_p_protocol="I_p_protocol_value")], description="description_value", destination_ranges=["destination_ranges_value"], direction=compute.Firewall.Direction.EGRESS, @@ -561,9 +553,9 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetFirewallReque # Establish that the response is the type that we expect. assert isinstance(response, compute.Firewall) - assert response.allowed == [compute.Allowed(i_p_protocol="i_p_protocol_value")] + assert response.allowed == [compute.Allowed(I_p_protocol="I_p_protocol_value")] assert response.creation_timestamp == "creation_timestamp_value" - assert response.denied == [compute.Denied(i_p_protocol="i_p_protocol_value")] + assert response.denied == [compute.Denied(I_p_protocol="I_p_protocol_value")] assert response.description == "description_value" assert response.destination_ranges == ["destination_ranges_value"] assert response.direction == compute.Firewall.Direction.EGRESS @@ -655,6 +647,7 @@ def test_insert_rest( 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", @@ -690,6 +683,7 @@ def test_insert_rest( 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" @@ -728,7 +722,7 @@ def test_insert_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. firewall_resource = compute.Firewall( - allowed=[compute.Allowed(i_p_protocol="i_p_protocol_value")] + allowed=[compute.Allowed(I_p_protocol="I_p_protocol_value")] ) client.insert( project="project_value", firewall_resource=firewall_resource, @@ -757,7 +751,7 @@ def test_insert_rest_flattened_error(): compute.InsertFirewallRequest(), project="project_value", firewall_resource=compute.Firewall( - allowed=[compute.Allowed(i_p_protocol="i_p_protocol_value")] + allowed=[compute.Allowed(I_p_protocol="I_p_protocol_value")] ), ) @@ -778,7 +772,7 @@ def test_list_rest(transport: str = "rest", request_type=compute.ListFirewallsRe id="id_value", items=[ compute.Firewall( - allowed=[compute.Allowed(i_p_protocol="i_p_protocol_value")] + allowed=[compute.Allowed(I_p_protocol="I_p_protocol_value")] ) ], kind="kind_value", @@ -799,7 +793,7 @@ def test_list_rest(transport: str = "rest", request_type=compute.ListFirewallsRe assert isinstance(response, pagers.ListPager) assert response.id == "id_value" assert response.items == [ - compute.Firewall(allowed=[compute.Allowed(i_p_protocol="i_p_protocol_value")]) + compute.Firewall(allowed=[compute.Allowed(I_p_protocol="I_p_protocol_value")]) ] assert response.kind == "kind_value" assert response.next_page_token == "next_page_token_value" @@ -913,6 +907,7 @@ def test_patch_rest(transport: str = "rest", request_type=compute.PatchFirewallR 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", @@ -948,6 +943,7 @@ def test_patch_rest(transport: str = "rest", request_type=compute.PatchFirewallR 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" @@ -986,7 +982,7 @@ def test_patch_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. firewall_resource = compute.Firewall( - allowed=[compute.Allowed(i_p_protocol="i_p_protocol_value")] + allowed=[compute.Allowed(I_p_protocol="I_p_protocol_value")] ) client.patch( project="project_value", @@ -1019,7 +1015,7 @@ def test_patch_rest_flattened_error(): project="project_value", firewall="firewall_value", firewall_resource=compute.Firewall( - allowed=[compute.Allowed(i_p_protocol="i_p_protocol_value")] + allowed=[compute.Allowed(I_p_protocol="I_p_protocol_value")] ), ) @@ -1050,6 +1046,7 @@ def test_update_rest( 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", @@ -1085,6 +1082,7 @@ def test_update_rest( 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" @@ -1123,7 +1121,7 @@ def test_update_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. firewall_resource = compute.Firewall( - allowed=[compute.Allowed(i_p_protocol="i_p_protocol_value")] + allowed=[compute.Allowed(I_p_protocol="I_p_protocol_value")] ) client.update( project="project_value", @@ -1156,7 +1154,7 @@ def test_update_rest_flattened_error(): project="project_value", firewall="firewall_value", firewall_resource=compute.Firewall( - allowed=[compute.Allowed(i_p_protocol="i_p_protocol_value")] + allowed=[compute.Allowed(I_p_protocol="I_p_protocol_value")] ), ) diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_forwarding_rules.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_forwarding_rules.py index 845c9270ef41..2995c60a6868 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_forwarding_rules.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_forwarding_rules.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.forwarding_rules import ForwardingRulesClient from google.cloud.compute_v1.services.forwarding_rules import pagers from google.cloud.compute_v1.services.forwarding_rules import transports -from google.cloud.compute_v1.services.forwarding_rules.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.forwarding_rules.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -434,7 +422,9 @@ def test_aggregated_list_rest( id="id_value", items={ "key_value": compute.ForwardingRulesScopedList( - forwarding_rules=[compute.ForwardingRule(all_ports=True)] + forwarding_rules=[ + compute.ForwardingRule(I_p_address="I_p_address_value") + ] ) }, kind="kind_value", @@ -457,7 +447,7 @@ def test_aggregated_list_rest( assert response.id == "id_value" assert response.items == { "key_value": compute.ForwardingRulesScopedList( - forwarding_rules=[compute.ForwardingRule(all_ports=True)] + forwarding_rules=[compute.ForwardingRule(I_p_address="I_p_address_value")] ) } assert response.kind == "kind_value" @@ -601,6 +591,7 @@ def test_delete_rest( 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", @@ -636,6 +627,7 @@ def test_delete_rest( 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" @@ -718,18 +710,20 @@ def test_get_rest( with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. return_value = compute.ForwardingRule( + I_p_address="I_p_address_value", + I_p_protocol=compute.ForwardingRule.IPProtocol.AH, all_ports=True, allow_global_access=True, backend_service="backend_service_value", creation_timestamp="creation_timestamp_value", description="description_value", fingerprint="fingerprint_value", - i_p_address="i_p_address_value", - i_p_protocol=compute.ForwardingRule.IPProtocol.AH, id="id_value", ip_version=compute.ForwardingRule.IpVersion.IPV4, is_mirroring_collector=True, kind="kind_value", + label_fingerprint="label_fingerprint_value", + labels={"key_value": "value_value"}, load_balancing_scheme=compute.ForwardingRule.LoadBalancingScheme.EXTERNAL, metadata_filters=[ compute.MetadataFilter( @@ -741,8 +735,14 @@ def test_get_rest( network_tier=compute.ForwardingRule.NetworkTier.PREMIUM, port_range="port_range_value", ports=["ports_value"], + psc_connection_id="psc_connection_id_value", region="region_value", self_link="self_link_value", + service_directory_registrations=[ + compute.ForwardingRuleServiceDirectoryRegistration( + namespace="namespace_value" + ) + ], service_label="service_label_value", service_name="service_name_value", subnetwork="subnetwork_value", @@ -759,18 +759,20 @@ def test_get_rest( # Establish that the response is the type that we expect. assert isinstance(response, compute.ForwardingRule) + assert response.I_p_address == "I_p_address_value" + assert response.I_p_protocol == compute.ForwardingRule.IPProtocol.AH assert response.all_ports is True assert response.allow_global_access is True assert response.backend_service == "backend_service_value" assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" assert response.fingerprint == "fingerprint_value" - assert response.i_p_address == "i_p_address_value" - assert response.i_p_protocol == compute.ForwardingRule.IPProtocol.AH assert response.id == "id_value" assert response.ip_version == compute.ForwardingRule.IpVersion.IPV4 assert response.is_mirroring_collector is True assert response.kind == "kind_value" + assert response.label_fingerprint == "label_fingerprint_value" + assert response.labels == {"key_value": "value_value"} assert ( response.load_balancing_scheme == compute.ForwardingRule.LoadBalancingScheme.EXTERNAL @@ -785,8 +787,12 @@ def test_get_rest( assert response.network_tier == compute.ForwardingRule.NetworkTier.PREMIUM assert response.port_range == "port_range_value" assert response.ports == ["ports_value"] + assert response.psc_connection_id == "psc_connection_id_value" assert response.region == "region_value" assert response.self_link == "self_link_value" + assert response.service_directory_registrations == [ + compute.ForwardingRuleServiceDirectoryRegistration(namespace="namespace_value") + ] assert response.service_label == "service_label_value" assert response.service_name == "service_name_value" assert response.subnetwork == "subnetwork_value" @@ -870,6 +876,7 @@ def test_insert_rest( 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", @@ -905,6 +912,7 @@ def test_insert_rest( 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" @@ -942,7 +950,9 @@ def test_insert_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - forwarding_rule_resource = compute.ForwardingRule(all_ports=True) + forwarding_rule_resource = compute.ForwardingRule( + I_p_address="I_p_address_value" + ) client.insert( project="project_value", region="region_value", @@ -973,7 +983,9 @@ def test_insert_rest_flattened_error(): compute.InsertForwardingRuleRequest(), project="project_value", region="region_value", - forwarding_rule_resource=compute.ForwardingRule(all_ports=True), + forwarding_rule_resource=compute.ForwardingRule( + I_p_address="I_p_address_value" + ), ) @@ -993,7 +1005,7 @@ def test_list_rest( # Designate an appropriate value for the returned response. return_value = compute.ForwardingRuleList( id="id_value", - items=[compute.ForwardingRule(all_ports=True)], + items=[compute.ForwardingRule(I_p_address="I_p_address_value")], kind="kind_value", next_page_token="next_page_token_value", self_link="self_link_value", @@ -1011,7 +1023,7 @@ def test_list_rest( # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListPager) assert response.id == "id_value" - assert response.items == [compute.ForwardingRule(all_ports=True)] + assert response.items == [compute.ForwardingRule(I_p_address="I_p_address_value")] assert response.kind == "kind_value" assert response.next_page_token == "next_page_token_value" assert response.self_link == "self_link_value" @@ -1139,6 +1151,7 @@ def test_patch_rest( 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", @@ -1174,6 +1187,7 @@ def test_patch_rest( 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" @@ -1211,7 +1225,9 @@ def test_patch_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - forwarding_rule_resource = compute.ForwardingRule(all_ports=True) + forwarding_rule_resource = compute.ForwardingRule( + I_p_address="I_p_address_value" + ) client.patch( project="project_value", region="region_value", @@ -1245,7 +1261,151 @@ def test_patch_rest_flattened_error(): project="project_value", region="region_value", forwarding_rule="forwarding_rule_value", - forwarding_rule_resource=compute.ForwardingRule(all_ports=True), + forwarding_rule_resource=compute.ForwardingRule( + I_p_address="I_p_address_value" + ), + ) + + +def test_set_labels_rest( + transport: str = "rest", request_type=compute.SetLabelsForwardingRuleRequest +): + client = ForwardingRulesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + error=compute.Error(errors=[compute.Errors(code="code_value")]), + http_error_message="http_error_message_value", + http_error_status_code=2374, + id="id_value", + 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="target_id_value", + target_link="target_link_value", + user="user_value", + warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)], + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + 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, compute.Operation) + 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.error == compute.Error(errors=[compute.Errors(code="code_value")]) + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == "id_value" + 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 == "target_id_value" + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.warnings == [ + compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED) + ] + assert response.zone == "zone_value" + + +def test_set_labels_rest_from_dict(): + test_set_labels_rest(request_type=dict) + + +def test_set_labels_rest_flattened(): + client = ForwardingRulesClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + region_set_labels_request_resource = compute.RegionSetLabelsRequest( + label_fingerprint="label_fingerprint_value" + ) + client.set_labels( + project="project_value", + region="region_value", + resource="resource_value", + region_set_labels_request_resource=region_set_labels_request_resource, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "project_value" in http_call[1] + str(body) + assert "region_value" in http_call[1] + str(body) + assert "resource_value" in http_call[1] + str(body) + assert compute.RegionSetLabelsRequest.to_json( + region_set_labels_request_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) in http_call[1] + str(body) + + +def test_set_labels_rest_flattened_error(): + client = ForwardingRulesClient(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_labels( + compute.SetLabelsForwardingRuleRequest(), + project="project_value", + region="region_value", + resource="resource_value", + region_set_labels_request_resource=compute.RegionSetLabelsRequest( + label_fingerprint="label_fingerprint_value" + ), ) @@ -1275,6 +1435,7 @@ def test_set_target_rest( 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", @@ -1310,6 +1471,7 @@ def test_set_target_rest( 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" @@ -1461,6 +1623,7 @@ def test_forwarding_rules_base_transport(): "insert", "list", "patch", + "set_labels", "set_target", ) for method in methods: diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_addresses.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_addresses.py index 528b20ca19f5..fdbe7fd06a7e 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_addresses.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_addresses.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.global_addresses import GlobalAddressesClient from google.cloud.compute_v1.services.global_addresses import pagers from google.cloud.compute_v1.services.global_addresses import transports -from google.cloud.compute_v1.services.global_addresses.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.global_addresses.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -442,6 +430,7 @@ def test_delete_rest( 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", @@ -477,6 +466,7 @@ def test_delete_rest( 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" @@ -676,6 +666,7 @@ def test_insert_rest( 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", @@ -711,6 +702,7 @@ def test_insert_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_forwarding_rules.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_forwarding_rules.py index a519ef8cf32f..333ea1017146 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_forwarding_rules.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_forwarding_rules.py @@ -38,9 +38,6 @@ ) from google.cloud.compute_v1.services.global_forwarding_rules import pagers from google.cloud.compute_v1.services.global_forwarding_rules import transports -from google.cloud.compute_v1.services.global_forwarding_rules.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.global_forwarding_rules.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -49,8 +46,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -61,16 +59,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -463,6 +451,7 @@ def test_delete_rest( 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", @@ -498,6 +487,7 @@ def test_delete_rest( 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" @@ -580,18 +570,20 @@ def test_get_rest( with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. return_value = compute.ForwardingRule( + I_p_address="I_p_address_value", + I_p_protocol=compute.ForwardingRule.IPProtocol.AH, all_ports=True, allow_global_access=True, backend_service="backend_service_value", creation_timestamp="creation_timestamp_value", description="description_value", fingerprint="fingerprint_value", - i_p_address="i_p_address_value", - i_p_protocol=compute.ForwardingRule.IPProtocol.AH, id="id_value", ip_version=compute.ForwardingRule.IpVersion.IPV4, is_mirroring_collector=True, kind="kind_value", + label_fingerprint="label_fingerprint_value", + labels={"key_value": "value_value"}, load_balancing_scheme=compute.ForwardingRule.LoadBalancingScheme.EXTERNAL, metadata_filters=[ compute.MetadataFilter( @@ -603,8 +595,14 @@ def test_get_rest( network_tier=compute.ForwardingRule.NetworkTier.PREMIUM, port_range="port_range_value", ports=["ports_value"], + psc_connection_id="psc_connection_id_value", region="region_value", self_link="self_link_value", + service_directory_registrations=[ + compute.ForwardingRuleServiceDirectoryRegistration( + namespace="namespace_value" + ) + ], service_label="service_label_value", service_name="service_name_value", subnetwork="subnetwork_value", @@ -621,18 +619,20 @@ def test_get_rest( # Establish that the response is the type that we expect. assert isinstance(response, compute.ForwardingRule) + assert response.I_p_address == "I_p_address_value" + assert response.I_p_protocol == compute.ForwardingRule.IPProtocol.AH assert response.all_ports is True assert response.allow_global_access is True assert response.backend_service == "backend_service_value" assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" assert response.fingerprint == "fingerprint_value" - assert response.i_p_address == "i_p_address_value" - assert response.i_p_protocol == compute.ForwardingRule.IPProtocol.AH assert response.id == "id_value" assert response.ip_version == compute.ForwardingRule.IpVersion.IPV4 assert response.is_mirroring_collector is True assert response.kind == "kind_value" + assert response.label_fingerprint == "label_fingerprint_value" + assert response.labels == {"key_value": "value_value"} assert ( response.load_balancing_scheme == compute.ForwardingRule.LoadBalancingScheme.EXTERNAL @@ -647,8 +647,12 @@ def test_get_rest( assert response.network_tier == compute.ForwardingRule.NetworkTier.PREMIUM assert response.port_range == "port_range_value" assert response.ports == ["ports_value"] + assert response.psc_connection_id == "psc_connection_id_value" assert response.region == "region_value" assert response.self_link == "self_link_value" + assert response.service_directory_registrations == [ + compute.ForwardingRuleServiceDirectoryRegistration(namespace="namespace_value") + ] assert response.service_label == "service_label_value" assert response.service_name == "service_name_value" assert response.subnetwork == "subnetwork_value" @@ -732,6 +736,7 @@ def test_insert_rest( 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", @@ -767,6 +772,7 @@ def test_insert_rest( 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" @@ -806,7 +812,9 @@ def test_insert_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - forwarding_rule_resource = compute.ForwardingRule(all_ports=True) + forwarding_rule_resource = compute.ForwardingRule( + I_p_address="I_p_address_value" + ) client.insert( project="project_value", forwarding_rule_resource=forwarding_rule_resource, ) @@ -835,7 +843,9 @@ def test_insert_rest_flattened_error(): client.insert( compute.InsertGlobalForwardingRuleRequest(), project="project_value", - forwarding_rule_resource=compute.ForwardingRule(all_ports=True), + forwarding_rule_resource=compute.ForwardingRule( + I_p_address="I_p_address_value" + ), ) @@ -855,7 +865,7 @@ def test_list_rest( # Designate an appropriate value for the returned response. return_value = compute.ForwardingRuleList( id="id_value", - items=[compute.ForwardingRule(all_ports=True)], + items=[compute.ForwardingRule(I_p_address="I_p_address_value")], kind="kind_value", next_page_token="next_page_token_value", self_link="self_link_value", @@ -873,7 +883,7 @@ def test_list_rest( # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListPager) assert response.id == "id_value" - assert response.items == [compute.ForwardingRule(all_ports=True)] + assert response.items == [compute.ForwardingRule(I_p_address="I_p_address_value")] assert response.kind == "kind_value" assert response.next_page_token == "next_page_token_value" assert response.self_link == "self_link_value" @@ -1002,6 +1012,7 @@ def test_patch_rest( 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", @@ -1037,6 +1048,7 @@ def test_patch_rest( 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" @@ -1076,7 +1088,9 @@ def test_patch_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - forwarding_rule_resource = compute.ForwardingRule(all_ports=True) + forwarding_rule_resource = compute.ForwardingRule( + I_p_address="I_p_address_value" + ) client.patch( project="project_value", forwarding_rule="forwarding_rule_value", @@ -1109,7 +1123,152 @@ def test_patch_rest_flattened_error(): compute.PatchGlobalForwardingRuleRequest(), project="project_value", forwarding_rule="forwarding_rule_value", - forwarding_rule_resource=compute.ForwardingRule(all_ports=True), + forwarding_rule_resource=compute.ForwardingRule( + I_p_address="I_p_address_value" + ), + ) + + +def test_set_labels_rest( + transport: str = "rest", request_type=compute.SetLabelsGlobalForwardingRuleRequest +): + client = GlobalForwardingRulesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + error=compute.Error(errors=[compute.Errors(code="code_value")]), + http_error_message="http_error_message_value", + http_error_status_code=2374, + id="id_value", + 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="target_id_value", + target_link="target_link_value", + user="user_value", + warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)], + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + 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, compute.Operation) + 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.error == compute.Error(errors=[compute.Errors(code="code_value")]) + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == "id_value" + 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 == "target_id_value" + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.warnings == [ + compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED) + ] + assert response.zone == "zone_value" + + +def test_set_labels_rest_from_dict(): + test_set_labels_rest(request_type=dict) + + +def test_set_labels_rest_flattened(): + client = GlobalForwardingRulesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + global_set_labels_request_resource = compute.GlobalSetLabelsRequest( + label_fingerprint="label_fingerprint_value" + ) + client.set_labels( + project="project_value", + resource="resource_value", + global_set_labels_request_resource=global_set_labels_request_resource, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "project_value" in http_call[1] + str(body) + assert "resource_value" in http_call[1] + str(body) + assert compute.GlobalSetLabelsRequest.to_json( + global_set_labels_request_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) in http_call[1] + str(body) + + +def test_set_labels_rest_flattened_error(): + client = GlobalForwardingRulesClient( + 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_labels( + compute.SetLabelsGlobalForwardingRuleRequest(), + project="project_value", + resource="resource_value", + global_set_labels_request_resource=compute.GlobalSetLabelsRequest( + label_fingerprint="label_fingerprint_value" + ), ) @@ -1139,6 +1298,7 @@ def test_set_target_rest( 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", @@ -1174,6 +1334,7 @@ def test_set_target_rest( 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" @@ -1327,6 +1488,7 @@ def test_global_forwarding_rules_base_transport(): "insert", "list", "patch", + "set_labels", "set_target", ) for method in methods: diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_network_endpoint_groups.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_network_endpoint_groups.py index 09ee43b1bc0e..5694a714b8e9 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_network_endpoint_groups.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_network_endpoint_groups.py @@ -38,9 +38,6 @@ ) from google.cloud.compute_v1.services.global_network_endpoint_groups import pagers from google.cloud.compute_v1.services.global_network_endpoint_groups import transports -from google.cloud.compute_v1.services.global_network_endpoint_groups.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.global_network_endpoint_groups.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -49,8 +46,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -61,16 +59,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -470,6 +458,7 @@ def test_attach_network_endpoints_rest( 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", @@ -505,6 +494,7 @@ def test_attach_network_endpoints_rest( 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" @@ -616,6 +606,7 @@ def test_delete_rest( 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", @@ -651,6 +642,7 @@ def test_delete_rest( 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" @@ -746,6 +738,7 @@ def test_detach_network_endpoints_rest( 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", @@ -781,6 +774,7 @@ def test_detach_network_endpoints_rest( 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" @@ -893,7 +887,7 @@ def test_get_rest( kind="kind_value", name="name_value", network="network_value", - network_endpoint_type=compute.NetworkEndpointGroup.NetworkEndpointType.GCE_VM_IP_PORT, + network_endpoint_type=compute.NetworkEndpointGroup.NetworkEndpointType.GCE_VM_IP, region="region_value", self_link="self_link_value", size=443, @@ -930,7 +924,7 @@ def test_get_rest( assert response.network == "network_value" assert ( response.network_endpoint_type - == compute.NetworkEndpointGroup.NetworkEndpointType.GCE_VM_IP_PORT + == compute.NetworkEndpointGroup.NetworkEndpointType.GCE_VM_IP ) assert response.region == "region_value" assert response.self_link == "self_link_value" @@ -1018,6 +1012,7 @@ def test_insert_rest( 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", @@ -1053,6 +1048,7 @@ def test_insert_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_operations.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_operations.py index 6461a92edc00..c08bc4fac384 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_operations.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_operations.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.global_operations import GlobalOperationsClient from google.cloud.compute_v1.services.global_operations import pagers from google.cloud.compute_v1.services.global_operations import transports -from google.cloud.compute_v1.services.global_operations.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.global_operations.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -677,6 +665,7 @@ def test_get_rest( 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", @@ -712,6 +701,7 @@ def test_get_rest( 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" @@ -926,6 +916,7 @@ def test_wait_rest( 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", @@ -961,6 +952,7 @@ def test_wait_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_organization_operations.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_organization_operations.py index 0573d6b72822..4be3bd2e88ea 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_organization_operations.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_organization_operations.py @@ -38,9 +38,6 @@ ) from google.cloud.compute_v1.services.global_organization_operations import pagers from google.cloud.compute_v1.services.global_organization_operations import transports -from google.cloud.compute_v1.services.global_organization_operations.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.global_organization_operations.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -49,8 +46,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -61,16 +59,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -549,6 +537,7 @@ def test_get_rest( 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", @@ -584,6 +573,7 @@ def test_get_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_public_delegated_prefixes.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_public_delegated_prefixes.py new file mode 100644 index 000000000000..40f05db55fc9 --- /dev/null +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_public_delegated_prefixes.py @@ -0,0 +1,1438 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from requests import Response +from requests.sessions import Session + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.compute_v1.services.global_public_delegated_prefixes import ( + GlobalPublicDelegatedPrefixesClient, +) +from google.cloud.compute_v1.services.global_public_delegated_prefixes import pagers +from google.cloud.compute_v1.services.global_public_delegated_prefixes import transports +from google.cloud.compute_v1.services.global_public_delegated_prefixes.transports.base import ( + _GOOGLE_AUTH_VERSION, +) +from google.cloud.compute_v1.types import compute +from google.oauth2 import service_account +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + + +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 + ) + + +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 GlobalPublicDelegatedPrefixesClient._get_default_mtls_endpoint(None) is None + assert ( + GlobalPublicDelegatedPrefixesClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + GlobalPublicDelegatedPrefixesClient._get_default_mtls_endpoint( + api_mtls_endpoint + ) + == api_mtls_endpoint + ) + assert ( + GlobalPublicDelegatedPrefixesClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + GlobalPublicDelegatedPrefixesClient._get_default_mtls_endpoint( + sandbox_mtls_endpoint + ) + == sandbox_mtls_endpoint + ) + assert ( + GlobalPublicDelegatedPrefixesClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +@pytest.mark.parametrize("client_class", [GlobalPublicDelegatedPrefixesClient,]) +def test_global_public_delegated_prefixes_client_from_service_account_info( + client_class, +): + 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) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == "compute.googleapis.com:443" + + +@pytest.mark.parametrize("client_class", [GlobalPublicDelegatedPrefixesClient,]) +def test_global_public_delegated_prefixes_client_from_service_account_file( + client_class, +): + 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") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == "compute.googleapis.com:443" + + +def test_global_public_delegated_prefixes_client_get_transport_class(): + transport = GlobalPublicDelegatedPrefixesClient.get_transport_class() + available_transports = [ + transports.GlobalPublicDelegatedPrefixesRestTransport, + ] + assert transport in available_transports + + transport = GlobalPublicDelegatedPrefixesClient.get_transport_class("rest") + assert transport == transports.GlobalPublicDelegatedPrefixesRestTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + GlobalPublicDelegatedPrefixesClient, + transports.GlobalPublicDelegatedPrefixesRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + GlobalPublicDelegatedPrefixesClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(GlobalPublicDelegatedPrefixesClient), +) +def test_global_public_delegated_prefixes_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( + GlobalPublicDelegatedPrefixesClient, "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( + GlobalPublicDelegatedPrefixesClient, "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(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, + ) + + # 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() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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() + 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, + ) + + # 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): + client = client_class() + + # 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): + client = client_class() + + # 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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + GlobalPublicDelegatedPrefixesClient, + transports.GlobalPublicDelegatedPrefixesRestTransport, + "rest", + "true", + ), + ( + GlobalPublicDelegatedPrefixesClient, + transports.GlobalPublicDelegatedPrefixesRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + GlobalPublicDelegatedPrefixesClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(GlobalPublicDelegatedPrefixesClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_global_public_delegated_prefixes_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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + 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, + ) + + # 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 + 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() + 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, + ) + + # 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() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + GlobalPublicDelegatedPrefixesClient, + transports.GlobalPublicDelegatedPrefixesRestTransport, + "rest", + ), + ], +) +def test_global_public_delegated_prefixes_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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + GlobalPublicDelegatedPrefixesClient, + transports.GlobalPublicDelegatedPrefixesRestTransport, + "rest", + ), + ], +) +def test_global_public_delegated_prefixes_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # 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) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_delete_rest( + transport: str = "rest", + request_type=compute.DeleteGlobalPublicDelegatedPrefixeRequest, +): + client = GlobalPublicDelegatedPrefixesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + error=compute.Error(errors=[compute.Errors(code="code_value")]), + http_error_message="http_error_message_value", + http_error_status_code=2374, + id="id_value", + 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="target_id_value", + target_link="target_link_value", + user="user_value", + warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)], + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + 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, compute.Operation) + 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.error == compute.Error(errors=[compute.Errors(code="code_value")]) + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == "id_value" + 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 == "target_id_value" + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.warnings == [ + compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED) + ] + assert response.zone == "zone_value" + + +def test_delete_rest_from_dict(): + test_delete_rest(request_type=dict) + + +def test_delete_rest_flattened(): + client = GlobalPublicDelegatedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete( + project="project_value", + public_delegated_prefix="public_delegated_prefix_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "project_value" in http_call[1] + str(body) + assert "public_delegated_prefix_value" in http_call[1] + str(body) + + +def test_delete_rest_flattened_error(): + client = GlobalPublicDelegatedPrefixesClient( + 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( + compute.DeleteGlobalPublicDelegatedPrefixeRequest(), + project="project_value", + public_delegated_prefix="public_delegated_prefix_value", + ) + + +def test_get_rest( + transport: str = "rest", request_type=compute.GetGlobalPublicDelegatedPrefixeRequest +): + client = GlobalPublicDelegatedPrefixesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.PublicDelegatedPrefix( + creation_timestamp="creation_timestamp_value", + description="description_value", + fingerprint="fingerprint_value", + id="id_value", + ip_cidr_range="ip_cidr_range_value", + is_live_migration=True, + kind="kind_value", + name="name_value", + parent_prefix="parent_prefix_value", + public_delegated_sub_prefixs=[ + compute.PublicDelegatedPrefixPublicDelegatedSubPrefix( + delegatee_project="delegatee_project_value" + ) + ], + region="region_value", + self_link="self_link_value", + status=compute.PublicDelegatedPrefix.Status.ANNOUNCED, + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.PublicDelegatedPrefix.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + 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.PublicDelegatedPrefix) + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.fingerprint == "fingerprint_value" + assert response.id == "id_value" + assert response.ip_cidr_range == "ip_cidr_range_value" + assert response.is_live_migration is True + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.parent_prefix == "parent_prefix_value" + assert response.public_delegated_sub_prefixs == [ + compute.PublicDelegatedPrefixPublicDelegatedSubPrefix( + delegatee_project="delegatee_project_value" + ) + ] + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.status == compute.PublicDelegatedPrefix.Status.ANNOUNCED + + +def test_get_rest_from_dict(): + test_get_rest(request_type=dict) + + +def test_get_rest_flattened(): + client = GlobalPublicDelegatedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.PublicDelegatedPrefix() + + # Wrap the value into a proper Response obj + json_return_value = compute.PublicDelegatedPrefix.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get( + project="project_value", + public_delegated_prefix="public_delegated_prefix_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "project_value" in http_call[1] + str(body) + assert "public_delegated_prefix_value" in http_call[1] + str(body) + + +def test_get_rest_flattened_error(): + client = GlobalPublicDelegatedPrefixesClient( + 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( + compute.GetGlobalPublicDelegatedPrefixeRequest(), + project="project_value", + public_delegated_prefix="public_delegated_prefix_value", + ) + + +def test_insert_rest( + transport: str = "rest", + request_type=compute.InsertGlobalPublicDelegatedPrefixeRequest, +): + client = GlobalPublicDelegatedPrefixesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + error=compute.Error(errors=[compute.Errors(code="code_value")]), + http_error_message="http_error_message_value", + http_error_status_code=2374, + id="id_value", + 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="target_id_value", + target_link="target_link_value", + user="user_value", + warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)], + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + 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, compute.Operation) + 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.error == compute.Error(errors=[compute.Errors(code="code_value")]) + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == "id_value" + 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 == "target_id_value" + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.warnings == [ + compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED) + ] + assert response.zone == "zone_value" + + +def test_insert_rest_from_dict(): + test_insert_rest(request_type=dict) + + +def test_insert_rest_flattened(): + client = GlobalPublicDelegatedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + public_delegated_prefix_resource = compute.PublicDelegatedPrefix( + creation_timestamp="creation_timestamp_value" + ) + client.insert( + project="project_value", + public_delegated_prefix_resource=public_delegated_prefix_resource, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "project_value" in http_call[1] + str(body) + assert compute.PublicDelegatedPrefix.to_json( + public_delegated_prefix_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) in http_call[1] + str(body) + + +def test_insert_rest_flattened_error(): + client = GlobalPublicDelegatedPrefixesClient( + 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.insert( + compute.InsertGlobalPublicDelegatedPrefixeRequest(), + project="project_value", + public_delegated_prefix_resource=compute.PublicDelegatedPrefix( + creation_timestamp="creation_timestamp_value" + ), + ) + + +def test_list_rest( + transport: str = "rest", + request_type=compute.ListGlobalPublicDelegatedPrefixesRequest, +): + client = GlobalPublicDelegatedPrefixesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.PublicDelegatedPrefixList( + id="id_value", + items=[ + compute.PublicDelegatedPrefix( + creation_timestamp="creation_timestamp_value" + ) + ], + kind="kind_value", + next_page_token="next_page_token_value", + self_link="self_link_value", + warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.PublicDelegatedPrefixList.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + 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.items == [ + compute.PublicDelegatedPrefix(creation_timestamp="creation_timestamp_value") + ] + assert response.kind == "kind_value" + assert response.next_page_token == "next_page_token_value" + assert response.self_link == "self_link_value" + assert response.warning == compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED) + + +def test_list_rest_from_dict(): + test_list_rest(request_type=dict) + + +def test_list_rest_flattened(): + client = GlobalPublicDelegatedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.PublicDelegatedPrefixList() + + # Wrap the value into a proper Response obj + json_return_value = compute.PublicDelegatedPrefixList.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list(project="project_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "project_value" in http_call[1] + str(body) + + +def test_list_rest_flattened_error(): + client = GlobalPublicDelegatedPrefixesClient( + 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( + compute.ListGlobalPublicDelegatedPrefixesRequest(), project="project_value", + ) + + +def test_list_pager(): + client = GlobalPublicDelegatedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Set the response as a series of pages + response = ( + compute.PublicDelegatedPrefixList( + items=[ + compute.PublicDelegatedPrefix(), + compute.PublicDelegatedPrefix(), + compute.PublicDelegatedPrefix(), + ], + next_page_token="abc", + ), + compute.PublicDelegatedPrefixList(items=[], next_page_token="def",), + compute.PublicDelegatedPrefixList( + items=[compute.PublicDelegatedPrefix(),], next_page_token="ghi", + ), + compute.PublicDelegatedPrefixList( + items=[ + compute.PublicDelegatedPrefix(), + compute.PublicDelegatedPrefix(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(compute.PublicDelegatedPrefixList.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 + + metadata = () + pager = client.list(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, compute.PublicDelegatedPrefix) for i in results) + + pages = list(client.list(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_patch_rest( + transport: str = "rest", + request_type=compute.PatchGlobalPublicDelegatedPrefixeRequest, +): + client = GlobalPublicDelegatedPrefixesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + error=compute.Error(errors=[compute.Errors(code="code_value")]), + http_error_message="http_error_message_value", + http_error_status_code=2374, + id="id_value", + 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="target_id_value", + target_link="target_link_value", + user="user_value", + warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)], + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.patch(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Operation) + 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.error == compute.Error(errors=[compute.Errors(code="code_value")]) + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == "id_value" + 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 == "target_id_value" + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.warnings == [ + compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED) + ] + assert response.zone == "zone_value" + + +def test_patch_rest_from_dict(): + test_patch_rest(request_type=dict) + + +def test_patch_rest_flattened(): + client = GlobalPublicDelegatedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + public_delegated_prefix_resource = compute.PublicDelegatedPrefix( + creation_timestamp="creation_timestamp_value" + ) + client.patch( + project="project_value", + public_delegated_prefix="public_delegated_prefix_value", + public_delegated_prefix_resource=public_delegated_prefix_resource, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "project_value" in http_call[1] + str(body) + assert "public_delegated_prefix_value" in http_call[1] + str(body) + assert compute.PublicDelegatedPrefix.to_json( + public_delegated_prefix_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) in http_call[1] + str(body) + + +def test_patch_rest_flattened_error(): + client = GlobalPublicDelegatedPrefixesClient( + 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.patch( + compute.PatchGlobalPublicDelegatedPrefixeRequest(), + project="project_value", + public_delegated_prefix="public_delegated_prefix_value", + public_delegated_prefix_resource=compute.PublicDelegatedPrefix( + creation_timestamp="creation_timestamp_value" + ), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.GlobalPublicDelegatedPrefixesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GlobalPublicDelegatedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.GlobalPublicDelegatedPrefixesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GlobalPublicDelegatedPrefixesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.GlobalPublicDelegatedPrefixesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GlobalPublicDelegatedPrefixesClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.GlobalPublicDelegatedPrefixesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = GlobalPublicDelegatedPrefixesClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", [transports.GlobalPublicDelegatedPrefixesRestTransport,] +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_global_public_delegated_prefixes_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.GlobalPublicDelegatedPrefixesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_global_public_delegated_prefixes_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.compute_v1.services.global_public_delegated_prefixes.transports.GlobalPublicDelegatedPrefixesTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.GlobalPublicDelegatedPrefixesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "delete", + "get", + "insert", + "list", + "patch", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_global_public_delegated_prefixes_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.global_public_delegated_prefixes.transports.GlobalPublicDelegatedPrefixesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GlobalPublicDelegatedPrefixesTransport( + 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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_global_public_delegated_prefixes_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.global_public_delegated_prefixes.transports.GlobalPublicDelegatedPrefixesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GlobalPublicDelegatedPrefixesTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +def test_global_public_delegated_prefixes_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.compute_v1.services.global_public_delegated_prefixes.transports.GlobalPublicDelegatedPrefixesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GlobalPublicDelegatedPrefixesTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_global_public_delegated_prefixes_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) + GlobalPublicDelegatedPrefixesClient() + 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, + ) + + +@requires_google_auth_lt_1_25_0 +def test_global_public_delegated_prefixes_auth_adc_old_google_auth(): + # 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) + GlobalPublicDelegatedPrefixesClient() + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +def test_global_public_delegated_prefixes_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.GlobalPublicDelegatedPrefixesRestTransport( + 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_global_public_delegated_prefixes_host_no_port(): + client = GlobalPublicDelegatedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="compute.googleapis.com" + ), + ) + assert client.transport._host == "compute.googleapis.com:443" + + +def test_global_public_delegated_prefixes_host_with_port(): + client = GlobalPublicDelegatedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="compute.googleapis.com:8000" + ), + ) + assert client.transport._host == "compute.googleapis.com:8000" + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = GlobalPublicDelegatedPrefixesClient.common_billing_account_path( + billing_account + ) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = GlobalPublicDelegatedPrefixesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = GlobalPublicDelegatedPrefixesClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder,) + actual = GlobalPublicDelegatedPrefixesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = GlobalPublicDelegatedPrefixesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = GlobalPublicDelegatedPrefixesClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization,) + actual = GlobalPublicDelegatedPrefixesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = GlobalPublicDelegatedPrefixesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = GlobalPublicDelegatedPrefixesClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project,) + actual = GlobalPublicDelegatedPrefixesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = GlobalPublicDelegatedPrefixesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = GlobalPublicDelegatedPrefixesClient.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 = GlobalPublicDelegatedPrefixesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = GlobalPublicDelegatedPrefixesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = GlobalPublicDelegatedPrefixesClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.GlobalPublicDelegatedPrefixesTransport, "_prep_wrapped_messages" + ) as prep: + client = GlobalPublicDelegatedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.GlobalPublicDelegatedPrefixesTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = GlobalPublicDelegatedPrefixesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_health_checks.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_health_checks.py index 7167dd9b2b5a..717aa23e3fc9 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_health_checks.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_health_checks.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.health_checks import HealthChecksClient from google.cloud.compute_v1.services.health_checks import pagers from google.cloud.compute_v1.services.health_checks import transports -from google.cloud.compute_v1.services.health_checks.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.health_checks.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -583,6 +571,7 @@ def test_delete_rest( 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", @@ -618,6 +607,7 @@ def test_delete_rest( 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" @@ -823,6 +813,7 @@ def test_insert_rest( 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", @@ -858,6 +849,7 @@ def test_insert_rest( 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" @@ -1083,6 +1075,7 @@ def test_patch_rest( 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", @@ -1118,6 +1111,7 @@ def test_patch_rest( 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" @@ -1216,6 +1210,7 @@ def test_update_rest( 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", @@ -1251,6 +1246,7 @@ def test_update_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_images.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_images.py index 7bdd5f0d9ac2..2b1393a4d5db 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_images.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_images.py @@ -36,15 +36,15 @@ from google.cloud.compute_v1.services.images import ImagesClient from google.cloud.compute_v1.services.images import pagers from google.cloud.compute_v1.services.images import transports -from google.cloud.compute_v1.services.images.transports.base import _API_CORE_VERSION from google.cloud.compute_v1.services.images.transports.base import _GOOGLE_AUTH_VERSION from google.cloud.compute_v1.types import compute from google.oauth2 import service_account import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -55,16 +55,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -414,6 +404,7 @@ def test_delete_rest(transport: str = "rest", request_type=compute.DeleteImageRe 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", @@ -449,6 +440,7 @@ def test_delete_rest(transport: str = "rest", request_type=compute.DeleteImageRe 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" @@ -536,6 +528,7 @@ def test_deprecate_rest( 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", @@ -571,6 +564,7 @@ def test_deprecate_rest( 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" @@ -680,6 +674,7 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetImageRequest) licenses=["licenses_value"], name="name_value", raw_disk=compute.RawDisk(container_type=compute.RawDisk.ContainerType.TAR), + satisfies_pzs=True, self_link="self_link_value", shielded_instance_initial_state=compute.InitialStateConfig( dbs=[compute.FileContentBuffer(content="content_value")] @@ -738,6 +733,7 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetImageRequest) assert response.raw_disk == compute.RawDisk( container_type=compute.RawDisk.ContainerType.TAR ) + assert response.satisfies_pzs is True assert response.self_link == "self_link_value" assert response.shielded_instance_initial_state == compute.InitialStateConfig( dbs=[compute.FileContentBuffer(content="content_value")] @@ -844,6 +840,7 @@ def test_get_from_family_rest( licenses=["licenses_value"], name="name_value", raw_disk=compute.RawDisk(container_type=compute.RawDisk.ContainerType.TAR), + satisfies_pzs=True, self_link="self_link_value", shielded_instance_initial_state=compute.InitialStateConfig( dbs=[compute.FileContentBuffer(content="content_value")] @@ -902,6 +899,7 @@ def test_get_from_family_rest( assert response.raw_disk == compute.RawDisk( container_type=compute.RawDisk.ContainerType.TAR ) + assert response.satisfies_pzs is True assert response.self_link == "self_link_value" assert response.shielded_instance_initial_state == compute.InitialStateConfig( dbs=[compute.FileContentBuffer(content="content_value")] @@ -1099,6 +1097,7 @@ def test_insert_rest(transport: str = "rest", request_type=compute.InsertImageRe 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", @@ -1134,6 +1133,7 @@ def test_insert_rest(transport: str = "rest", request_type=compute.InsertImageRe 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" @@ -1349,6 +1349,7 @@ def test_patch_rest(transport: str = "rest", request_type=compute.PatchImageRequ 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", @@ -1384,6 +1385,7 @@ def test_patch_rest(transport: str = "rest", request_type=compute.PatchImageRequ 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" @@ -1595,6 +1597,7 @@ def test_set_labels_rest( 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", @@ -1630,6 +1633,7 @@ def test_set_labels_rest( 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" 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 dc42e79c062a..03427414b795 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 @@ -38,9 +38,6 @@ ) from google.cloud.compute_v1.services.instance_group_managers import pagers from google.cloud.compute_v1.services.instance_group_managers import transports -from google.cloud.compute_v1.services.instance_group_managers.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.instance_group_managers.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -49,8 +46,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -61,16 +59,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -464,6 +452,7 @@ def test_abandon_instances_rest( 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", @@ -499,6 +488,7 @@ def test_abandon_instances_rest( 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" @@ -798,6 +788,7 @@ def test_apply_updates_to_instances_rest( 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", @@ -833,6 +824,7 @@ def test_apply_updates_to_instances_rest( 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" @@ -943,6 +935,7 @@ def test_create_instances_rest( 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", @@ -978,6 +971,7 @@ def test_create_instances_rest( 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" @@ -1087,6 +1081,7 @@ def test_delete_rest( 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", @@ -1122,6 +1117,7 @@ def test_delete_rest( 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" @@ -1220,6 +1216,7 @@ def test_delete_instances_rest( 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", @@ -1255,6 +1252,7 @@ def test_delete_instances_rest( 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" @@ -1365,6 +1363,7 @@ def test_delete_per_instance_configs_rest( 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", @@ -1400,6 +1399,7 @@ def test_delete_per_instance_configs_rest( 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" @@ -1508,7 +1508,7 @@ def test_get_rest( current_actions=compute.InstanceGroupManagerActionsSummary(abandoning=1041), description="description_value", distribution_policy=compute.DistributionPolicy( - zones=[compute.DistributionPolicyZoneConfiguration(zone="zone_value")] + target_shape=compute.DistributionPolicy.TargetShape.ANY ), fingerprint="fingerprint_value", id="id_value", @@ -1562,7 +1562,7 @@ def test_get_rest( ) assert response.description == "description_value" assert response.distribution_policy == compute.DistributionPolicy( - zones=[compute.DistributionPolicyZoneConfiguration(zone="zone_value")] + target_shape=compute.DistributionPolicy.TargetShape.ANY ) assert response.fingerprint == "fingerprint_value" assert response.id == "id_value" @@ -1677,6 +1677,7 @@ def test_insert_rest( 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", @@ -1712,6 +1713,7 @@ def test_insert_rest( 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" @@ -2456,6 +2458,7 @@ def test_patch_rest( 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", @@ -2491,6 +2494,7 @@ def test_patch_rest( 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" @@ -2609,6 +2613,7 @@ def test_patch_per_instance_configs_rest( 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", @@ -2644,6 +2649,7 @@ def test_patch_per_instance_configs_rest( 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" @@ -2758,6 +2764,7 @@ def test_recreate_instances_rest( 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", @@ -2793,6 +2800,7 @@ def test_recreate_instances_rest( 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" @@ -2902,6 +2910,7 @@ def test_resize_rest( 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", @@ -2937,6 +2946,7 @@ def test_resize_rest( 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" @@ -3038,6 +3048,7 @@ def test_set_instance_template_rest( 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", @@ -3073,6 +3084,7 @@ def test_set_instance_template_rest( 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" @@ -3183,6 +3195,7 @@ def test_set_target_pools_rest( 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", @@ -3218,6 +3231,7 @@ def test_set_target_pools_rest( 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" @@ -3328,6 +3342,7 @@ def test_update_per_instance_configs_rest( 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", @@ -3363,6 +3378,7 @@ def test_update_per_instance_configs_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_groups.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_groups.py index 1b0835bc8a0d..ea9d87d46caa 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_groups.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_groups.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.instance_groups import InstanceGroupsClient from google.cloud.compute_v1.services.instance_groups import pagers from google.cloud.compute_v1.services.instance_groups import transports -from google.cloud.compute_v1.services.instance_groups.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.instance_groups.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -432,6 +420,7 @@ def test_add_instances_rest( 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", @@ -467,6 +456,7 @@ def test_add_instances_rest( 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" @@ -736,6 +726,7 @@ def test_delete_rest( 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", @@ -771,6 +762,7 @@ def test_delete_rest( 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" @@ -970,6 +962,7 @@ def test_insert_rest( 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", @@ -1005,6 +998,7 @@ def test_insert_rest( 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" @@ -1404,6 +1398,7 @@ def test_remove_instances_rest( 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", @@ -1439,6 +1434,7 @@ def test_remove_instances_rest( 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" @@ -1544,6 +1540,7 @@ def test_set_named_ports_rest( 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", @@ -1579,6 +1576,7 @@ def test_set_named_ports_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_templates.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_templates.py index 1cc5e0d4ccd7..f751a07d4870 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_templates.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_templates.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.instance_templates import InstanceTemplatesClient from google.cloud.compute_v1.services.instance_templates import pagers from google.cloud.compute_v1.services.instance_templates import transports -from google.cloud.compute_v1.services.instance_templates.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.instance_templates.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -443,6 +431,7 @@ def test_delete_rest( 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", @@ -478,6 +467,7 @@ def test_delete_rest( 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" @@ -561,7 +551,11 @@ def test_get_rest( id="id_value", kind="kind_value", name="name_value", - properties=compute.InstanceProperties(can_ip_forward=True), + properties=compute.InstanceProperties( + advanced_machine_features=compute.AdvancedMachineFeatures( + enable_nested_virtualization=True + ) + ), self_link="self_link_value", source_instance="source_instance_value", source_instance_params=compute.SourceInstanceParams( @@ -584,7 +578,11 @@ def test_get_rest( assert response.id == "id_value" assert response.kind == "kind_value" assert response.name == "name_value" - assert response.properties == compute.InstanceProperties(can_ip_forward=True) + assert response.properties == compute.InstanceProperties( + advanced_machine_features=compute.AdvancedMachineFeatures( + enable_nested_virtualization=True + ) + ) assert response.self_link == "self_link_value" assert response.source_instance == "source_instance_value" assert response.source_instance_params == compute.SourceInstanceParams( @@ -767,6 +765,7 @@ def test_insert_rest( 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", @@ -802,6 +801,7 @@ def test_insert_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instances.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instances.py index 319de0ce0c8c..8800d3fe0ed4 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instances.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instances.py @@ -36,7 +36,6 @@ from google.cloud.compute_v1.services.instances import InstancesClient from google.cloud.compute_v1.services.instances import pagers from google.cloud.compute_v1.services.instances import transports -from google.cloud.compute_v1.services.instances.transports.base import _API_CORE_VERSION from google.cloud.compute_v1.services.instances.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -45,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -57,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -419,6 +409,7 @@ def test_add_access_config_rest( 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", @@ -454,6 +445,7 @@ def test_add_access_config_rest( 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" @@ -558,6 +550,7 @@ def test_add_resource_policies_rest( 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", @@ -593,6 +586,7 @@ def test_add_resource_policies_rest( 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" @@ -690,7 +684,13 @@ def test_aggregated_list_rest( id="id_value", items={ "key_value": compute.InstancesScopedList( - instances=[compute.Instance(can_ip_forward=True)] + instances=[ + compute.Instance( + advanced_machine_features=compute.AdvancedMachineFeatures( + enable_nested_virtualization=True + ) + ) + ] ) }, kind="kind_value", @@ -713,7 +713,13 @@ def test_aggregated_list_rest( assert response.id == "id_value" assert response.items == { "key_value": compute.InstancesScopedList( - instances=[compute.Instance(can_ip_forward=True)] + instances=[ + compute.Instance( + advanced_machine_features=compute.AdvancedMachineFeatures( + enable_nested_virtualization=True + ) + ) + ] ) } assert response.kind == "kind_value" @@ -851,6 +857,7 @@ def test_attach_disk_rest( 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", @@ -886,6 +893,7 @@ def test_attach_disk_rest( 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" @@ -961,6 +969,145 @@ def test_attach_disk_rest_flattened_error(): ) +def test_bulk_insert_rest( + transport: str = "rest", request_type=compute.BulkInsertInstanceRequest +): + client = InstancesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + error=compute.Error(errors=[compute.Errors(code="code_value")]), + http_error_message="http_error_message_value", + http_error_status_code=2374, + id="id_value", + 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="target_id_value", + target_link="target_link_value", + user="user_value", + warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)], + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.bulk_insert(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Operation) + 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.error == compute.Error(errors=[compute.Errors(code="code_value")]) + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == "id_value" + 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 == "target_id_value" + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.warnings == [ + compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED) + ] + assert response.zone == "zone_value" + + +def test_bulk_insert_rest_from_dict(): + test_bulk_insert_rest(request_type=dict) + + +def test_bulk_insert_rest_flattened(): + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + bulk_insert_instance_resource_resource = compute.BulkInsertInstanceResource( + count="count_value" + ) + client.bulk_insert( + project="project_value", + zone="zone_value", + bulk_insert_instance_resource_resource=bulk_insert_instance_resource_resource, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "project_value" in http_call[1] + str(body) + assert "zone_value" in http_call[1] + str(body) + assert compute.BulkInsertInstanceResource.to_json( + bulk_insert_instance_resource_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) in http_call[1] + str(body) + + +def test_bulk_insert_rest_flattened_error(): + client = InstancesClient(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_insert( + compute.BulkInsertInstanceRequest(), + project="project_value", + zone="zone_value", + bulk_insert_instance_resource_resource=compute.BulkInsertInstanceResource( + count="count_value" + ), + ) + + def test_delete_rest( transport: str = "rest", request_type=compute.DeleteInstanceRequest ): @@ -987,6 +1134,7 @@ def test_delete_rest( 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", @@ -1022,6 +1170,7 @@ def test_delete_rest( 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" @@ -1113,6 +1262,7 @@ def test_delete_access_config_rest( 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", @@ -1148,6 +1298,7 @@ def test_delete_access_config_rest( 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" @@ -1247,6 +1398,7 @@ def test_detach_disk_rest( 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", @@ -1282,6 +1434,7 @@ def test_detach_disk_rest( 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" @@ -1365,6 +1518,9 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetInstanceReque with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. return_value = compute.Instance( + advanced_machine_features=compute.AdvancedMachineFeatures( + enable_nested_virtualization=True + ), can_ip_forward=True, confidential_instance_config=compute.ConfidentialInstanceConfig( enable_confidential_compute=True @@ -1399,6 +1555,7 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetInstanceReque consume_reservation_type=compute.ReservationAffinity.ConsumeReservationType.ANY_RESERVATION ), resource_policies=["resource_policies_value"], + satisfies_pzs=True, scheduling=compute.Scheduling(automatic_restart=True), self_link="self_link_value", service_accounts=[compute.ServiceAccount(email="email_value")], @@ -1425,6 +1582,9 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetInstanceReque # Establish that the response is the type that we expect. assert isinstance(response, compute.Instance) + assert response.advanced_machine_features == compute.AdvancedMachineFeatures( + enable_nested_virtualization=True + ) assert response.can_ip_forward is True assert response.confidential_instance_config == compute.ConfidentialInstanceConfig( enable_confidential_compute=True @@ -1464,6 +1624,7 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetInstanceReque consume_reservation_type=compute.ReservationAffinity.ConsumeReservationType.ANY_RESERVATION ) assert response.resource_policies == ["resource_policies_value"] + assert response.satisfies_pzs is True assert response.scheduling == compute.Scheduling(automatic_restart=True) assert response.self_link == "self_link_value" assert response.service_accounts == [compute.ServiceAccount(email="email_value")] @@ -1530,6 +1691,111 @@ def test_get_rest_flattened_error(): ) +def test_get_effective_firewalls_rest( + transport: str = "rest", request_type=compute.GetEffectiveFirewallsInstanceRequest +): + client = InstancesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.InstancesGetEffectiveFirewallsResponse( + firewall_policys=[ + compute.InstancesGetEffectiveFirewallsResponseEffectiveFirewallPolicy( + display_name="display_name_value" + ) + ], + firewalls=[ + compute.Firewall( + allowed=[compute.Allowed(I_p_protocol="I_p_protocol_value")] + ) + ], + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.InstancesGetEffectiveFirewallsResponse.to_json( + return_value + ) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_effective_firewalls(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.InstancesGetEffectiveFirewallsResponse) + assert response.firewall_policys == [ + compute.InstancesGetEffectiveFirewallsResponseEffectiveFirewallPolicy( + display_name="display_name_value" + ) + ] + assert response.firewalls == [ + compute.Firewall(allowed=[compute.Allowed(I_p_protocol="I_p_protocol_value")]) + ] + + +def test_get_effective_firewalls_rest_from_dict(): + test_get_effective_firewalls_rest(request_type=dict) + + +def test_get_effective_firewalls_rest_flattened(): + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.InstancesGetEffectiveFirewallsResponse() + + # Wrap the value into a proper Response obj + json_return_value = compute.InstancesGetEffectiveFirewallsResponse.to_json( + return_value + ) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_effective_firewalls( + project="project_value", + zone="zone_value", + instance="instance_value", + network_interface="network_interface_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "project_value" in http_call[1] + str(body) + assert "zone_value" in http_call[1] + str(body) + assert "instance_value" in http_call[1] + str(body) + assert "network_interface_value" in http_call[1] + str(body) + + +def test_get_effective_firewalls_rest_flattened_error(): + client = InstancesClient(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_effective_firewalls( + compute.GetEffectiveFirewallsInstanceRequest(), + project="project_value", + zone="zone_value", + instance="instance_value", + network_interface="network_interface_value", + ) + + def test_get_guest_attributes_rest( transport: str = "rest", request_type=compute.GetGuestAttributesInstanceRequest ): @@ -2012,6 +2278,7 @@ def test_insert_rest( 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", @@ -2047,6 +2314,7 @@ def test_insert_rest( 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" @@ -2084,7 +2352,11 @@ def test_insert_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - instance_resource = compute.Instance(can_ip_forward=True) + instance_resource = compute.Instance( + advanced_machine_features=compute.AdvancedMachineFeatures( + enable_nested_virtualization=True + ) + ) client.insert( project="project_value", zone="zone_value", @@ -2115,7 +2387,11 @@ def test_insert_rest_flattened_error(): compute.InsertInstanceRequest(), project="project_value", zone="zone_value", - instance_resource=compute.Instance(can_ip_forward=True), + instance_resource=compute.Instance( + advanced_machine_features=compute.AdvancedMachineFeatures( + enable_nested_virtualization=True + ) + ), ) @@ -2133,7 +2409,13 @@ def test_list_rest(transport: str = "rest", request_type=compute.ListInstancesRe # Designate an appropriate value for the returned response. return_value = compute.InstanceList( id="id_value", - items=[compute.Instance(can_ip_forward=True)], + items=[ + compute.Instance( + advanced_machine_features=compute.AdvancedMachineFeatures( + enable_nested_virtualization=True + ) + ) + ], kind="kind_value", next_page_token="next_page_token_value", self_link="self_link_value", @@ -2151,7 +2433,13 @@ def test_list_rest(transport: str = "rest", request_type=compute.ListInstancesRe # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListPager) assert response.id == "id_value" - assert response.items == [compute.Instance(can_ip_forward=True)] + assert response.items == [ + compute.Instance( + advanced_machine_features=compute.AdvancedMachineFeatures( + enable_nested_virtualization=True + ) + ) + ] assert response.kind == "kind_value" assert response.next_page_token == "next_page_token_value" assert response.self_link == "self_link_value" @@ -2403,6 +2691,7 @@ def test_remove_resource_policies_rest( 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", @@ -2438,6 +2727,7 @@ def test_remove_resource_policies_rest( 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" @@ -2541,6 +2831,7 @@ def test_reset_rest(transport: str = "rest", request_type=compute.ResetInstanceR 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", @@ -2576,6 +2867,7 @@ def test_reset_rest(transport: str = "rest", request_type=compute.ResetInstanceR 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" @@ -2667,6 +2959,7 @@ def test_set_deletion_protection_rest( 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", @@ -2702,6 +2995,7 @@ def test_set_deletion_protection_rest( 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" @@ -2793,6 +3087,7 @@ def test_set_disk_auto_delete_rest( 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", @@ -2828,6 +3123,7 @@ def test_set_disk_auto_delete_rest( 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" @@ -3045,6 +3341,7 @@ def test_set_labels_rest( 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", @@ -3080,6 +3377,7 @@ def test_set_labels_rest( 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" @@ -3185,6 +3483,7 @@ def test_set_machine_resources_rest( 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", @@ -3220,6 +3519,7 @@ def test_set_machine_resources_rest( 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" @@ -3325,6 +3625,7 @@ def test_set_machine_type_rest( 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", @@ -3360,6 +3661,7 @@ def test_set_machine_type_rest( 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" @@ -3465,6 +3767,7 @@ def test_set_metadata_rest( 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", @@ -3500,6 +3803,7 @@ def test_set_metadata_rest( 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" @@ -3601,6 +3905,7 @@ def test_set_min_cpu_platform_rest( 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", @@ -3636,6 +3941,7 @@ def test_set_min_cpu_platform_rest( 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" @@ -3741,6 +4047,7 @@ def test_set_scheduling_rest( 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", @@ -3776,6 +4083,7 @@ def test_set_scheduling_rest( 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" @@ -3877,6 +4185,7 @@ def test_set_service_account_rest( 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", @@ -3912,6 +4221,7 @@ def test_set_service_account_rest( 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" @@ -4018,6 +4328,7 @@ def test_set_shielded_instance_integrity_policy_rest( 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", @@ -4053,6 +4364,7 @@ def test_set_shielded_instance_integrity_policy_rest( 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" @@ -4158,6 +4470,7 @@ def test_set_tags_rest( 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", @@ -4193,6 +4506,7 @@ def test_set_tags_rest( 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" @@ -4295,6 +4609,7 @@ def test_simulate_maintenance_event_rest( 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", @@ -4330,6 +4645,7 @@ def test_simulate_maintenance_event_rest( 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" @@ -4419,6 +4735,7 @@ def test_start_rest(transport: str = "rest", request_type=compute.StartInstanceR 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", @@ -4454,6 +4771,7 @@ def test_start_rest(transport: str = "rest", request_type=compute.StartInstanceR 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" @@ -4545,6 +4863,7 @@ def test_start_with_encryption_key_rest( 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", @@ -4580,6 +4899,7 @@ def test_start_with_encryption_key_rest( 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" @@ -4695,6 +5015,7 @@ def test_stop_rest(transport: str = "rest", request_type=compute.StopInstanceReq 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", @@ -4730,6 +5051,7 @@ def test_stop_rest(transport: str = "rest", request_type=compute.StopInstanceReq 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" @@ -4915,6 +5237,7 @@ def test_update_rest( 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", @@ -4950,6 +5273,7 @@ def test_update_rest( 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" @@ -4987,7 +5311,11 @@ def test_update_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - instance_resource = compute.Instance(can_ip_forward=True) + instance_resource = compute.Instance( + advanced_machine_features=compute.AdvancedMachineFeatures( + enable_nested_virtualization=True + ) + ) client.update( project="project_value", zone="zone_value", @@ -5021,7 +5349,11 @@ def test_update_rest_flattened_error(): project="project_value", zone="zone_value", instance="instance_value", - instance_resource=compute.Instance(can_ip_forward=True), + instance_resource=compute.Instance( + advanced_machine_features=compute.AdvancedMachineFeatures( + enable_nested_virtualization=True + ) + ), ) @@ -5051,6 +5383,7 @@ def test_update_access_config_rest( 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", @@ -5086,6 +5419,7 @@ def test_update_access_config_rest( 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" @@ -5190,6 +5524,7 @@ def test_update_display_device_rest( 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", @@ -5225,6 +5560,7 @@ def test_update_display_device_rest( 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" @@ -5326,6 +5662,7 @@ def test_update_network_interface_rest( 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", @@ -5361,6 +5698,7 @@ def test_update_network_interface_rest( 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" @@ -5470,6 +5808,7 @@ def test_update_shielded_instance_config_rest( 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", @@ -5505,6 +5844,7 @@ def test_update_shielded_instance_config_rest( 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" @@ -5658,10 +5998,12 @@ def test_instances_base_transport(): "add_resource_policies", "aggregated_list", "attach_disk", + "bulk_insert", "delete", "delete_access_config", "detach_disk", "get", + "get_effective_firewalls", "get_guest_attributes", "get_iam_policy", "get_screenshot", diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnect_attachments.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnect_attachments.py index a9a9916fd96a..9154a4d03e96 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnect_attachments.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnect_attachments.py @@ -38,9 +38,6 @@ ) from google.cloud.compute_v1.services.interconnect_attachments import pagers from google.cloud.compute_v1.services.interconnect_attachments import transports -from google.cloud.compute_v1.services.interconnect_attachments.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.interconnect_attachments.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -49,8 +46,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -61,16 +59,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -640,6 +628,7 @@ def test_delete_rest( 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", @@ -675,6 +664,7 @@ def test_delete_rest( 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" @@ -770,9 +760,11 @@ def test_get_rest( dataplane_version=1807, description="description_value", edge_availability_domain=compute.InterconnectAttachment.EdgeAvailabilityDomain.AVAILABILITY_DOMAIN_1, + encryption=compute.InterconnectAttachment.Encryption.IPSEC, google_reference_id="google_reference_id_value", id="id_value", interconnect="interconnect_value", + ipsec_internal_addresses=["ipsec_internal_addresses_value"], kind="kind_value", mtu=342, name="name_value", @@ -815,9 +807,11 @@ def test_get_rest( response.edge_availability_domain == compute.InterconnectAttachment.EdgeAvailabilityDomain.AVAILABILITY_DOMAIN_1 ) + assert response.encryption == compute.InterconnectAttachment.Encryption.IPSEC assert response.google_reference_id == "google_reference_id_value" assert response.id == "id_value" assert response.interconnect == "interconnect_value" + assert response.ipsec_internal_addresses == ["ipsec_internal_addresses_value"] assert response.kind == "kind_value" assert response.mtu == 342 assert response.name == "name_value" @@ -923,6 +917,7 @@ def test_insert_rest( 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", @@ -958,6 +953,7 @@ def test_insert_rest( 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" @@ -1211,6 +1207,7 @@ def test_patch_rest( 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", @@ -1246,6 +1243,7 @@ def test_patch_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnect_locations.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnect_locations.py index d0b5f3b9520e..d2c4d138132c 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnect_locations.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnect_locations.py @@ -38,9 +38,6 @@ ) from google.cloud.compute_v1.services.interconnect_locations import pagers from google.cloud.compute_v1.services.interconnect_locations import transports -from google.cloud.compute_v1.services.interconnect_locations.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.interconnect_locations.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -49,8 +46,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -61,16 +59,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnects.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnects.py index 528d548ff4fe..d694e3f79277 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnects.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnects.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.interconnects import InterconnectsClient from google.cloud.compute_v1.services.interconnects import pagers from google.cloud.compute_v1.services.interconnects import transports -from google.cloud.compute_v1.services.interconnects.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.interconnects.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -432,6 +420,7 @@ def test_delete_rest( 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", @@ -467,6 +456,7 @@ def test_delete_rest( 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" @@ -784,6 +774,7 @@ def test_insert_rest( 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", @@ -819,6 +810,7 @@ def test_insert_rest( 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" @@ -1044,6 +1036,7 @@ def test_patch_rest( 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", @@ -1079,6 +1072,7 @@ def test_patch_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_license_codes.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_license_codes.py index a0176fc5a442..bb88f4b761d5 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_license_codes.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_license_codes.py @@ -35,9 +35,6 @@ from google.auth.exceptions import MutualTLSChannelError from google.cloud.compute_v1.services.license_codes import LicenseCodesClient from google.cloud.compute_v1.services.license_codes import transports -from google.cloud.compute_v1.services.license_codes.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.license_codes.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -46,8 +43,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -58,16 +56,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_licenses.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_licenses.py index 3412a78156c2..50ad26ff1d7a 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_licenses.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_licenses.py @@ -36,7 +36,6 @@ from google.cloud.compute_v1.services.licenses import LicensesClient from google.cloud.compute_v1.services.licenses import pagers from google.cloud.compute_v1.services.licenses import transports -from google.cloud.compute_v1.services.licenses.transports.base import _API_CORE_VERSION from google.cloud.compute_v1.services.licenses.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -45,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -57,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -419,6 +409,7 @@ def test_delete_rest( 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", @@ -454,6 +445,7 @@ def test_delete_rest( 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" @@ -743,6 +735,7 @@ def test_insert_rest( 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", @@ -778,6 +771,7 @@ def test_insert_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_machine_types.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_machine_types.py index ed104fedbc08..bd7232bf8cd6 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_machine_types.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_machine_types.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.machine_types import MachineTypesClient from google.cloud.compute_v1.services.machine_types import pagers from google.cloud.compute_v1.services.machine_types import transports -from google.cloud.compute_v1.services.machine_types.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.machine_types.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_network_endpoint_groups.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_network_endpoint_groups.py index 9f3cc9e562c3..b02392cab3ca 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_network_endpoint_groups.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_network_endpoint_groups.py @@ -38,9 +38,6 @@ ) from google.cloud.compute_v1.services.network_endpoint_groups import pagers from google.cloud.compute_v1.services.network_endpoint_groups import transports -from google.cloud.compute_v1.services.network_endpoint_groups.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.network_endpoint_groups.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -49,8 +46,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -61,16 +59,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -643,6 +631,7 @@ def test_attach_network_endpoints_rest( 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", @@ -678,6 +667,7 @@ def test_attach_network_endpoints_rest( 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" @@ -791,6 +781,7 @@ def test_delete_rest( 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", @@ -826,6 +817,7 @@ def test_delete_rest( 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" @@ -924,6 +916,7 @@ def test_detach_network_endpoints_rest( 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", @@ -959,6 +952,7 @@ def test_detach_network_endpoints_rest( 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" @@ -1074,7 +1068,7 @@ def test_get_rest( kind="kind_value", name="name_value", network="network_value", - network_endpoint_type=compute.NetworkEndpointGroup.NetworkEndpointType.GCE_VM_IP_PORT, + network_endpoint_type=compute.NetworkEndpointGroup.NetworkEndpointType.GCE_VM_IP, region="region_value", self_link="self_link_value", size=443, @@ -1111,7 +1105,7 @@ def test_get_rest( assert response.network == "network_value" assert ( response.network_endpoint_type - == compute.NetworkEndpointGroup.NetworkEndpointType.GCE_VM_IP_PORT + == compute.NetworkEndpointGroup.NetworkEndpointType.GCE_VM_IP ) assert response.region == "region_value" assert response.self_link == "self_link_value" @@ -1201,6 +1195,7 @@ def test_insert_rest( 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", @@ -1236,6 +1231,7 @@ def test_insert_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_networks.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_networks.py index 67fe1caba1e9..2c71147e5f7e 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_networks.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_networks.py @@ -36,7 +36,6 @@ from google.cloud.compute_v1.services.networks import NetworksClient from google.cloud.compute_v1.services.networks import pagers from google.cloud.compute_v1.services.networks import transports -from google.cloud.compute_v1.services.networks.transports.base import _API_CORE_VERSION from google.cloud.compute_v1.services.networks.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -45,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -57,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -419,6 +409,7 @@ def test_add_peering_rest( 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", @@ -454,6 +445,7 @@ def test_add_peering_rest( 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" @@ -556,6 +548,7 @@ def test_delete_rest( 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", @@ -591,6 +584,7 @@ def test_delete_rest( 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" @@ -667,11 +661,11 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetNetworkReques with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. return_value = compute.Network( + I_pv4_range="I_pv4_range_value", auto_create_subnetworks=True, creation_timestamp="creation_timestamp_value", description="description_value", gateway_i_pv4="gateway_i_pv4_value", - i_pv4_range="i_pv4_range_value", id="id_value", kind="kind_value", mtu=342, @@ -694,11 +688,11 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetNetworkReques # Establish that the response is the type that we expect. assert isinstance(response, compute.Network) + assert response.I_pv4_range == "I_pv4_range_value" assert response.auto_create_subnetworks is True assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" assert response.gateway_i_pv4 == "gateway_i_pv4_value" - assert response.i_pv4_range == "i_pv4_range_value" assert response.id == "id_value" assert response.kind == "kind_value" assert response.mtu == 342 @@ -758,6 +752,104 @@ def test_get_rest_flattened_error(): ) +def test_get_effective_firewalls_rest( + transport: str = "rest", request_type=compute.GetEffectiveFirewallsNetworkRequest +): + client = NetworksClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.NetworksGetEffectiveFirewallsResponse( + firewall_policys=[ + compute.NetworksGetEffectiveFirewallsResponseEffectiveFirewallPolicy( + display_name="display_name_value" + ) + ], + firewalls=[ + compute.Firewall( + allowed=[compute.Allowed(I_p_protocol="I_p_protocol_value")] + ) + ], + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.NetworksGetEffectiveFirewallsResponse.to_json( + return_value + ) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_effective_firewalls(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.NetworksGetEffectiveFirewallsResponse) + assert response.firewall_policys == [ + compute.NetworksGetEffectiveFirewallsResponseEffectiveFirewallPolicy( + display_name="display_name_value" + ) + ] + assert response.firewalls == [ + compute.Firewall(allowed=[compute.Allowed(I_p_protocol="I_p_protocol_value")]) + ] + + +def test_get_effective_firewalls_rest_from_dict(): + test_get_effective_firewalls_rest(request_type=dict) + + +def test_get_effective_firewalls_rest_flattened(): + client = NetworksClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.NetworksGetEffectiveFirewallsResponse() + + # Wrap the value into a proper Response obj + json_return_value = compute.NetworksGetEffectiveFirewallsResponse.to_json( + return_value + ) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_effective_firewalls( + project="project_value", network="network_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "project_value" in http_call[1] + str(body) + assert "network_value" in http_call[1] + str(body) + + +def test_get_effective_firewalls_rest_flattened_error(): + client = NetworksClient(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_effective_firewalls( + compute.GetEffectiveFirewallsNetworkRequest(), + project="project_value", + network="network_value", + ) + + def test_insert_rest( transport: str = "rest", request_type=compute.InsertNetworkRequest ): @@ -784,6 +876,7 @@ def test_insert_rest( 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", @@ -819,6 +912,7 @@ def test_insert_rest( 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" @@ -856,7 +950,7 @@ def test_insert_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - network_resource = compute.Network(auto_create_subnetworks=True) + network_resource = compute.Network(I_pv4_range="I_pv4_range_value") client.insert( project="project_value", network_resource=network_resource, ) @@ -883,7 +977,7 @@ def test_insert_rest_flattened_error(): client.insert( compute.InsertNetworkRequest(), project="project_value", - network_resource=compute.Network(auto_create_subnetworks=True), + network_resource=compute.Network(I_pv4_range="I_pv4_range_value"), ) @@ -901,7 +995,7 @@ def test_list_rest(transport: str = "rest", request_type=compute.ListNetworksReq # Designate an appropriate value for the returned response. return_value = compute.NetworkList( id="id_value", - items=[compute.Network(auto_create_subnetworks=True)], + items=[compute.Network(I_pv4_range="I_pv4_range_value")], kind="kind_value", next_page_token="next_page_token_value", self_link="self_link_value", @@ -919,7 +1013,7 @@ def test_list_rest(transport: str = "rest", request_type=compute.ListNetworksReq # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListPager) assert response.id == "id_value" - assert response.items == [compute.Network(auto_create_subnetworks=True)] + assert response.items == [compute.Network(I_pv4_range="I_pv4_range_value")] assert response.kind == "kind_value" assert response.next_page_token == "next_page_token_value" assert response.self_link == "self_link_value" @@ -1175,6 +1269,7 @@ def test_patch_rest(transport: str = "rest", request_type=compute.PatchNetworkRe 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", @@ -1210,6 +1305,7 @@ def test_patch_rest(transport: str = "rest", request_type=compute.PatchNetworkRe 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" @@ -1247,7 +1343,7 @@ def test_patch_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - network_resource = compute.Network(auto_create_subnetworks=True) + network_resource = compute.Network(I_pv4_range="I_pv4_range_value") client.patch( project="project_value", network="network_value", @@ -1278,7 +1374,7 @@ def test_patch_rest_flattened_error(): compute.PatchNetworkRequest(), project="project_value", network="network_value", - network_resource=compute.Network(auto_create_subnetworks=True), + network_resource=compute.Network(I_pv4_range="I_pv4_range_value"), ) @@ -1308,6 +1404,7 @@ def test_remove_peering_rest( 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", @@ -1343,6 +1440,7 @@ def test_remove_peering_rest( 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" @@ -1445,6 +1543,7 @@ def test_switch_to_custom_mode_rest( 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", @@ -1480,6 +1579,7 @@ def test_switch_to_custom_mode_rest( 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" @@ -1569,6 +1669,7 @@ def test_update_peering_rest( 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", @@ -1604,6 +1705,7 @@ def test_update_peering_rest( 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" @@ -1753,6 +1855,7 @@ def test_networks_base_transport(): "add_peering", "delete", "get", + "get_effective_firewalls", "insert", "list", "list_peering_routes", diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_node_groups.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_node_groups.py index c204aea49b1b..f085711e31f5 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_node_groups.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_node_groups.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.node_groups import NodeGroupsClient from google.cloud.compute_v1.services.node_groups import pagers from google.cloud.compute_v1.services.node_groups import transports -from google.cloud.compute_v1.services.node_groups.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.node_groups.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -425,6 +413,7 @@ def test_add_nodes_rest( 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", @@ -460,6 +449,7 @@ def test_add_nodes_rest( 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" @@ -728,6 +718,7 @@ def test_delete_rest( 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", @@ -763,6 +754,7 @@ def test_delete_rest( 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" @@ -854,6 +846,7 @@ def test_delete_nodes_rest( 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", @@ -889,6 +882,7 @@ def test_delete_nodes_rest( 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" @@ -987,6 +981,7 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetNodeGroupRequ fingerprint="fingerprint_value", id="id_value", kind="kind_value", + location_hint="location_hint_value", maintenance_policy=compute.NodeGroup.MaintenancePolicy.DEFAULT, maintenance_window=compute.NodeGroupMaintenanceWindow( maintenance_duration=compute.Duration(nanos=543) @@ -1017,6 +1012,7 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetNodeGroupRequ assert response.fingerprint == "fingerprint_value" assert response.id == "id_value" assert response.kind == "kind_value" + assert response.location_hint == "location_hint_value" assert response.maintenance_policy == compute.NodeGroup.MaintenancePolicy.DEFAULT assert response.maintenance_window == compute.NodeGroupMaintenanceWindow( maintenance_duration=compute.Duration(nanos=543) @@ -1208,6 +1204,7 @@ def test_insert_rest( 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", @@ -1243,6 +1240,7 @@ def test_insert_rest( 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" @@ -1626,6 +1624,7 @@ def test_patch_rest( 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", @@ -1661,6 +1660,7 @@ def test_patch_rest( 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" @@ -1884,6 +1884,7 @@ def test_set_node_template_rest( 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", @@ -1919,6 +1920,7 @@ def test_set_node_template_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_node_templates.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_node_templates.py index 67768c82f410..8b0ad9201df9 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_node_templates.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_node_templates.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.node_templates import NodeTemplatesClient from google.cloud.compute_v1.services.node_templates import pagers from google.cloud.compute_v1.services.node_templates import transports -from google.cloud.compute_v1.services.node_templates.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.node_templates.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -600,6 +588,7 @@ def test_delete_rest( 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", @@ -635,6 +624,7 @@ def test_delete_rest( 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" @@ -953,6 +943,7 @@ def test_insert_rest( 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", @@ -988,6 +979,7 @@ def test_insert_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_node_types.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_node_types.py index 8270587281e5..575856b682ac 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_node_types.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_node_types.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.node_types import NodeTypesClient from google.cloud.compute_v1.services.node_types import pagers from google.cloud.compute_v1.services.node_types import transports -from google.cloud.compute_v1.services.node_types.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.node_types.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_packet_mirrorings.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_packet_mirrorings.py index b9e21e117f66..4f459cc8bf66 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_packet_mirrorings.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_packet_mirrorings.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.packet_mirrorings import PacketMirroringsClient from google.cloud.compute_v1.services.packet_mirrorings import pagers from google.cloud.compute_v1.services.packet_mirrorings import transports -from google.cloud.compute_v1.services.packet_mirrorings.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.packet_mirrorings.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -614,6 +602,7 @@ def test_delete_rest( 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", @@ -649,6 +638,7 @@ def test_delete_rest( 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" @@ -737,7 +727,7 @@ def test_get_rest( creation_timestamp="creation_timestamp_value", description="description_value", enable=compute.PacketMirroring.Enable.FALSE, - filter=compute.PacketMirroringFilter(cidr_ranges=["cidr_ranges_value"]), + filter=compute.PacketMirroringFilter(I_p_protocols=["I_p_protocols_value"]), id="id_value", kind="kind_value", mirrored_resources=compute.PacketMirroringMirroredResourceInfo( @@ -773,7 +763,7 @@ def test_get_rest( assert response.description == "description_value" assert response.enable == compute.PacketMirroring.Enable.FALSE assert response.filter == compute.PacketMirroringFilter( - cidr_ranges=["cidr_ranges_value"] + I_p_protocols=["I_p_protocols_value"] ) assert response.id == "id_value" assert response.kind == "kind_value" @@ -870,6 +860,7 @@ def test_insert_rest( 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", @@ -905,6 +896,7 @@ def test_insert_rest( 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" @@ -1159,6 +1151,7 @@ def test_patch_rest( 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", @@ -1194,6 +1187,7 @@ def test_patch_rest( 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" 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 bff8cfd6170e..913e8ffb9bce 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 @@ -36,7 +36,6 @@ from google.cloud.compute_v1.services.projects import ProjectsClient from google.cloud.compute_v1.services.projects import pagers from google.cloud.compute_v1.services.projects import transports -from google.cloud.compute_v1.services.projects.transports.base import _API_CORE_VERSION from google.cloud.compute_v1.services.projects.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -45,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -57,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -419,6 +409,7 @@ def test_disable_xpn_host_rest( 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", @@ -454,6 +445,7 @@ def test_disable_xpn_host_rest( 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" @@ -538,6 +530,7 @@ def test_disable_xpn_resource_rest( 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", @@ -573,6 +566,7 @@ def test_disable_xpn_resource_rest( 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" @@ -672,6 +666,7 @@ def test_enable_xpn_host_rest( 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", @@ -707,6 +702,7 @@ def test_enable_xpn_host_rest( 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" @@ -791,6 +787,7 @@ def test_enable_xpn_resource_rest( 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", @@ -826,6 +823,7 @@ def test_enable_xpn_resource_rest( 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" @@ -1402,6 +1400,7 @@ def test_move_disk_rest( 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", @@ -1437,6 +1436,7 @@ def test_move_disk_rest( 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" @@ -1536,6 +1536,7 @@ def test_move_instance_rest( 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", @@ -1571,6 +1572,7 @@ def test_move_instance_rest( 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" @@ -1671,6 +1673,7 @@ def test_set_common_instance_metadata_rest( 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", @@ -1706,6 +1709,7 @@ def test_set_common_instance_metadata_rest( 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" @@ -1800,6 +1804,7 @@ def test_set_default_network_tier_rest( 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", @@ -1835,6 +1840,7 @@ def test_set_default_network_tier_rest( 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" @@ -1934,6 +1940,7 @@ def test_set_usage_export_bucket_rest( 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", @@ -1969,6 +1976,7 @@ def test_set_usage_export_bucket_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_public_advertised_prefixes.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_public_advertised_prefixes.py new file mode 100644 index 000000000000..e1330fc061c9 --- /dev/null +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_public_advertised_prefixes.py @@ -0,0 +1,1422 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from requests import Response +from requests.sessions import Session + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.compute_v1.services.public_advertised_prefixes import ( + PublicAdvertisedPrefixesClient, +) +from google.cloud.compute_v1.services.public_advertised_prefixes import pagers +from google.cloud.compute_v1.services.public_advertised_prefixes import transports +from google.cloud.compute_v1.services.public_advertised_prefixes.transports.base import ( + _GOOGLE_AUTH_VERSION, +) +from google.cloud.compute_v1.types import compute +from google.oauth2 import service_account +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + + +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 + ) + + +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 PublicAdvertisedPrefixesClient._get_default_mtls_endpoint(None) is None + assert ( + PublicAdvertisedPrefixesClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + PublicAdvertisedPrefixesClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + PublicAdvertisedPrefixesClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + PublicAdvertisedPrefixesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + PublicAdvertisedPrefixesClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +@pytest.mark.parametrize("client_class", [PublicAdvertisedPrefixesClient,]) +def test_public_advertised_prefixes_client_from_service_account_info(client_class): + 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) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == "compute.googleapis.com:443" + + +@pytest.mark.parametrize("client_class", [PublicAdvertisedPrefixesClient,]) +def test_public_advertised_prefixes_client_from_service_account_file(client_class): + 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") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == "compute.googleapis.com:443" + + +def test_public_advertised_prefixes_client_get_transport_class(): + transport = PublicAdvertisedPrefixesClient.get_transport_class() + available_transports = [ + transports.PublicAdvertisedPrefixesRestTransport, + ] + assert transport in available_transports + + transport = PublicAdvertisedPrefixesClient.get_transport_class("rest") + assert transport == transports.PublicAdvertisedPrefixesRestTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + PublicAdvertisedPrefixesClient, + transports.PublicAdvertisedPrefixesRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + PublicAdvertisedPrefixesClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(PublicAdvertisedPrefixesClient), +) +def test_public_advertised_prefixes_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( + PublicAdvertisedPrefixesClient, "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( + PublicAdvertisedPrefixesClient, "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(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, + ) + + # 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() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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() + 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, + ) + + # 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): + client = client_class() + + # 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): + client = client_class() + + # 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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + PublicAdvertisedPrefixesClient, + transports.PublicAdvertisedPrefixesRestTransport, + "rest", + "true", + ), + ( + PublicAdvertisedPrefixesClient, + transports.PublicAdvertisedPrefixesRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + PublicAdvertisedPrefixesClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(PublicAdvertisedPrefixesClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_public_advertised_prefixes_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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + 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, + ) + + # 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 + 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() + 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, + ) + + # 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() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + PublicAdvertisedPrefixesClient, + transports.PublicAdvertisedPrefixesRestTransport, + "rest", + ), + ], +) +def test_public_advertised_prefixes_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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + PublicAdvertisedPrefixesClient, + transports.PublicAdvertisedPrefixesRestTransport, + "rest", + ), + ], +) +def test_public_advertised_prefixes_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # 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) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_delete_rest( + transport: str = "rest", request_type=compute.DeletePublicAdvertisedPrefixeRequest +): + client = PublicAdvertisedPrefixesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + error=compute.Error(errors=[compute.Errors(code="code_value")]), + http_error_message="http_error_message_value", + http_error_status_code=2374, + id="id_value", + 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="target_id_value", + target_link="target_link_value", + user="user_value", + warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)], + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + 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, compute.Operation) + 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.error == compute.Error(errors=[compute.Errors(code="code_value")]) + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == "id_value" + 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 == "target_id_value" + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.warnings == [ + compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED) + ] + assert response.zone == "zone_value" + + +def test_delete_rest_from_dict(): + test_delete_rest(request_type=dict) + + +def test_delete_rest_flattened(): + client = PublicAdvertisedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete( + project="project_value", + public_advertised_prefix="public_advertised_prefix_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "project_value" in http_call[1] + str(body) + assert "public_advertised_prefix_value" in http_call[1] + str(body) + + +def test_delete_rest_flattened_error(): + client = PublicAdvertisedPrefixesClient( + 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( + compute.DeletePublicAdvertisedPrefixeRequest(), + project="project_value", + public_advertised_prefix="public_advertised_prefix_value", + ) + + +def test_get_rest( + transport: str = "rest", request_type=compute.GetPublicAdvertisedPrefixeRequest +): + client = PublicAdvertisedPrefixesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.PublicAdvertisedPrefix( + creation_timestamp="creation_timestamp_value", + description="description_value", + dns_verification_ip="dns_verification_ip_value", + fingerprint="fingerprint_value", + id="id_value", + ip_cidr_range="ip_cidr_range_value", + kind="kind_value", + name="name_value", + public_delegated_prefixs=[ + compute.PublicAdvertisedPrefixPublicDelegatedPrefix( + ip_range="ip_range_value" + ) + ], + self_link="self_link_value", + shared_secret="shared_secret_value", + status=compute.PublicAdvertisedPrefix.Status.INITIAL, + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.PublicAdvertisedPrefix.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + 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.PublicAdvertisedPrefix) + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.dns_verification_ip == "dns_verification_ip_value" + assert response.fingerprint == "fingerprint_value" + assert response.id == "id_value" + assert response.ip_cidr_range == "ip_cidr_range_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.public_delegated_prefixs == [ + compute.PublicAdvertisedPrefixPublicDelegatedPrefix(ip_range="ip_range_value") + ] + assert response.self_link == "self_link_value" + assert response.shared_secret == "shared_secret_value" + assert response.status == compute.PublicAdvertisedPrefix.Status.INITIAL + + +def test_get_rest_from_dict(): + test_get_rest(request_type=dict) + + +def test_get_rest_flattened(): + client = PublicAdvertisedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.PublicAdvertisedPrefix() + + # Wrap the value into a proper Response obj + json_return_value = compute.PublicAdvertisedPrefix.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get( + project="project_value", + public_advertised_prefix="public_advertised_prefix_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "project_value" in http_call[1] + str(body) + assert "public_advertised_prefix_value" in http_call[1] + str(body) + + +def test_get_rest_flattened_error(): + client = PublicAdvertisedPrefixesClient( + 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( + compute.GetPublicAdvertisedPrefixeRequest(), + project="project_value", + public_advertised_prefix="public_advertised_prefix_value", + ) + + +def test_insert_rest( + transport: str = "rest", request_type=compute.InsertPublicAdvertisedPrefixeRequest +): + client = PublicAdvertisedPrefixesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + error=compute.Error(errors=[compute.Errors(code="code_value")]), + http_error_message="http_error_message_value", + http_error_status_code=2374, + id="id_value", + 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="target_id_value", + target_link="target_link_value", + user="user_value", + warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)], + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + 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, compute.Operation) + 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.error == compute.Error(errors=[compute.Errors(code="code_value")]) + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == "id_value" + 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 == "target_id_value" + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.warnings == [ + compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED) + ] + assert response.zone == "zone_value" + + +def test_insert_rest_from_dict(): + test_insert_rest(request_type=dict) + + +def test_insert_rest_flattened(): + client = PublicAdvertisedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + public_advertised_prefix_resource = compute.PublicAdvertisedPrefix( + creation_timestamp="creation_timestamp_value" + ) + client.insert( + project="project_value", + public_advertised_prefix_resource=public_advertised_prefix_resource, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "project_value" in http_call[1] + str(body) + assert compute.PublicAdvertisedPrefix.to_json( + public_advertised_prefix_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) in http_call[1] + str(body) + + +def test_insert_rest_flattened_error(): + client = PublicAdvertisedPrefixesClient( + 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.insert( + compute.InsertPublicAdvertisedPrefixeRequest(), + project="project_value", + public_advertised_prefix_resource=compute.PublicAdvertisedPrefix( + creation_timestamp="creation_timestamp_value" + ), + ) + + +def test_list_rest( + transport: str = "rest", request_type=compute.ListPublicAdvertisedPrefixesRequest +): + client = PublicAdvertisedPrefixesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.PublicAdvertisedPrefixList( + id="id_value", + items=[ + compute.PublicAdvertisedPrefix( + creation_timestamp="creation_timestamp_value" + ) + ], + kind="kind_value", + next_page_token="next_page_token_value", + self_link="self_link_value", + warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.PublicAdvertisedPrefixList.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + 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.items == [ + compute.PublicAdvertisedPrefix(creation_timestamp="creation_timestamp_value") + ] + assert response.kind == "kind_value" + assert response.next_page_token == "next_page_token_value" + assert response.self_link == "self_link_value" + assert response.warning == compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED) + + +def test_list_rest_from_dict(): + test_list_rest(request_type=dict) + + +def test_list_rest_flattened(): + client = PublicAdvertisedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.PublicAdvertisedPrefixList() + + # Wrap the value into a proper Response obj + json_return_value = compute.PublicAdvertisedPrefixList.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list(project="project_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "project_value" in http_call[1] + str(body) + + +def test_list_rest_flattened_error(): + client = PublicAdvertisedPrefixesClient( + 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( + compute.ListPublicAdvertisedPrefixesRequest(), project="project_value", + ) + + +def test_list_pager(): + client = PublicAdvertisedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Set the response as a series of pages + response = ( + compute.PublicAdvertisedPrefixList( + items=[ + compute.PublicAdvertisedPrefix(), + compute.PublicAdvertisedPrefix(), + compute.PublicAdvertisedPrefix(), + ], + next_page_token="abc", + ), + compute.PublicAdvertisedPrefixList(items=[], next_page_token="def",), + compute.PublicAdvertisedPrefixList( + items=[compute.PublicAdvertisedPrefix(),], next_page_token="ghi", + ), + compute.PublicAdvertisedPrefixList( + items=[ + compute.PublicAdvertisedPrefix(), + compute.PublicAdvertisedPrefix(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + compute.PublicAdvertisedPrefixList.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 + + metadata = () + pager = client.list(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, compute.PublicAdvertisedPrefix) for i in results) + + pages = list(client.list(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_patch_rest( + transport: str = "rest", request_type=compute.PatchPublicAdvertisedPrefixeRequest +): + client = PublicAdvertisedPrefixesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + error=compute.Error(errors=[compute.Errors(code="code_value")]), + http_error_message="http_error_message_value", + http_error_status_code=2374, + id="id_value", + 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="target_id_value", + target_link="target_link_value", + user="user_value", + warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)], + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.patch(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Operation) + 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.error == compute.Error(errors=[compute.Errors(code="code_value")]) + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == "id_value" + 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 == "target_id_value" + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.warnings == [ + compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED) + ] + assert response.zone == "zone_value" + + +def test_patch_rest_from_dict(): + test_patch_rest(request_type=dict) + + +def test_patch_rest_flattened(): + client = PublicAdvertisedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + public_advertised_prefix_resource = compute.PublicAdvertisedPrefix( + creation_timestamp="creation_timestamp_value" + ) + client.patch( + project="project_value", + public_advertised_prefix="public_advertised_prefix_value", + public_advertised_prefix_resource=public_advertised_prefix_resource, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "project_value" in http_call[1] + str(body) + assert "public_advertised_prefix_value" in http_call[1] + str(body) + assert compute.PublicAdvertisedPrefix.to_json( + public_advertised_prefix_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) in http_call[1] + str(body) + + +def test_patch_rest_flattened_error(): + client = PublicAdvertisedPrefixesClient( + 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.patch( + compute.PatchPublicAdvertisedPrefixeRequest(), + project="project_value", + public_advertised_prefix="public_advertised_prefix_value", + public_advertised_prefix_resource=compute.PublicAdvertisedPrefix( + creation_timestamp="creation_timestamp_value" + ), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.PublicAdvertisedPrefixesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PublicAdvertisedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.PublicAdvertisedPrefixesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PublicAdvertisedPrefixesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.PublicAdvertisedPrefixesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PublicAdvertisedPrefixesClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.PublicAdvertisedPrefixesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = PublicAdvertisedPrefixesClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", [transports.PublicAdvertisedPrefixesRestTransport,] +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_public_advertised_prefixes_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PublicAdvertisedPrefixesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_public_advertised_prefixes_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.compute_v1.services.public_advertised_prefixes.transports.PublicAdvertisedPrefixesTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.PublicAdvertisedPrefixesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "delete", + "get", + "insert", + "list", + "patch", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_public_advertised_prefixes_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.public_advertised_prefixes.transports.PublicAdvertisedPrefixesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PublicAdvertisedPrefixesTransport( + 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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_public_advertised_prefixes_base_transport_with_credentials_file_old_google_auth(): + # 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.public_advertised_prefixes.transports.PublicAdvertisedPrefixesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PublicAdvertisedPrefixesTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +def test_public_advertised_prefixes_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.public_advertised_prefixes.transports.PublicAdvertisedPrefixesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PublicAdvertisedPrefixesTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_public_advertised_prefixes_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) + PublicAdvertisedPrefixesClient() + 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, + ) + + +@requires_google_auth_lt_1_25_0 +def test_public_advertised_prefixes_auth_adc_old_google_auth(): + # 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) + PublicAdvertisedPrefixesClient() + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +def test_public_advertised_prefixes_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.PublicAdvertisedPrefixesRestTransport( + 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_public_advertised_prefixes_host_no_port(): + client = PublicAdvertisedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="compute.googleapis.com" + ), + ) + assert client.transport._host == "compute.googleapis.com:443" + + +def test_public_advertised_prefixes_host_with_port(): + client = PublicAdvertisedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="compute.googleapis.com:8000" + ), + ) + assert client.transport._host == "compute.googleapis.com:8000" + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = PublicAdvertisedPrefixesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = PublicAdvertisedPrefixesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = PublicAdvertisedPrefixesClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder,) + actual = PublicAdvertisedPrefixesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = PublicAdvertisedPrefixesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = PublicAdvertisedPrefixesClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization,) + actual = PublicAdvertisedPrefixesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = PublicAdvertisedPrefixesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = PublicAdvertisedPrefixesClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project,) + actual = PublicAdvertisedPrefixesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = PublicAdvertisedPrefixesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = PublicAdvertisedPrefixesClient.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 = PublicAdvertisedPrefixesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = PublicAdvertisedPrefixesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = PublicAdvertisedPrefixesClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.PublicAdvertisedPrefixesTransport, "_prep_wrapped_messages" + ) as prep: + client = PublicAdvertisedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.PublicAdvertisedPrefixesTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = PublicAdvertisedPrefixesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_public_delegated_prefixes.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_public_delegated_prefixes.py new file mode 100644 index 000000000000..665f7ac29468 --- /dev/null +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_public_delegated_prefixes.py @@ -0,0 +1,1619 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from requests import Response +from requests.sessions import Session + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.compute_v1.services.public_delegated_prefixes import ( + PublicDelegatedPrefixesClient, +) +from google.cloud.compute_v1.services.public_delegated_prefixes import pagers +from google.cloud.compute_v1.services.public_delegated_prefixes import transports +from google.cloud.compute_v1.services.public_delegated_prefixes.transports.base import ( + _GOOGLE_AUTH_VERSION, +) +from google.cloud.compute_v1.types import compute +from google.oauth2 import service_account +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + + +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 + ) + + +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 PublicDelegatedPrefixesClient._get_default_mtls_endpoint(None) is None + assert ( + PublicDelegatedPrefixesClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + PublicDelegatedPrefixesClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + PublicDelegatedPrefixesClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + PublicDelegatedPrefixesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + PublicDelegatedPrefixesClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +@pytest.mark.parametrize("client_class", [PublicDelegatedPrefixesClient,]) +def test_public_delegated_prefixes_client_from_service_account_info(client_class): + 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) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == "compute.googleapis.com:443" + + +@pytest.mark.parametrize("client_class", [PublicDelegatedPrefixesClient,]) +def test_public_delegated_prefixes_client_from_service_account_file(client_class): + 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") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == "compute.googleapis.com:443" + + +def test_public_delegated_prefixes_client_get_transport_class(): + transport = PublicDelegatedPrefixesClient.get_transport_class() + available_transports = [ + transports.PublicDelegatedPrefixesRestTransport, + ] + assert transport in available_transports + + transport = PublicDelegatedPrefixesClient.get_transport_class("rest") + assert transport == transports.PublicDelegatedPrefixesRestTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + PublicDelegatedPrefixesClient, + transports.PublicDelegatedPrefixesRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + PublicDelegatedPrefixesClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(PublicDelegatedPrefixesClient), +) +def test_public_delegated_prefixes_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(PublicDelegatedPrefixesClient, "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(PublicDelegatedPrefixesClient, "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(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, + ) + + # 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() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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() + 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, + ) + + # 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): + client = client_class() + + # 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): + client = client_class() + + # 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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + PublicDelegatedPrefixesClient, + transports.PublicDelegatedPrefixesRestTransport, + "rest", + "true", + ), + ( + PublicDelegatedPrefixesClient, + transports.PublicDelegatedPrefixesRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + PublicDelegatedPrefixesClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(PublicDelegatedPrefixesClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_public_delegated_prefixes_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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + 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, + ) + + # 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 + 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() + 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, + ) + + # 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() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + PublicDelegatedPrefixesClient, + transports.PublicDelegatedPrefixesRestTransport, + "rest", + ), + ], +) +def test_public_delegated_prefixes_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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + PublicDelegatedPrefixesClient, + transports.PublicDelegatedPrefixesRestTransport, + "rest", + ), + ], +) +def test_public_delegated_prefixes_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # 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) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_aggregated_list_rest( + transport: str = "rest", + request_type=compute.AggregatedListPublicDelegatedPrefixesRequest, +): + client = PublicDelegatedPrefixesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.PublicDelegatedPrefixAggregatedList( + id="id_value", + items={ + "key_value": compute.PublicDelegatedPrefixesScopedList( + public_delegated_prefixes=[ + compute.PublicDelegatedPrefix( + creation_timestamp="creation_timestamp_value" + ) + ] + ) + }, + kind="kind_value", + next_page_token="next_page_token_value", + self_link="self_link_value", + unreachables=["unreachables_value"], + warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.PublicDelegatedPrefixAggregatedList.to_json( + return_value + ) + response_value = Response() + response_value.status_code = 200 + 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.items == { + "key_value": compute.PublicDelegatedPrefixesScopedList( + public_delegated_prefixes=[ + compute.PublicDelegatedPrefix( + creation_timestamp="creation_timestamp_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"] + assert response.warning == compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED) + + +def test_aggregated_list_rest_from_dict(): + test_aggregated_list_rest(request_type=dict) + + +def test_aggregated_list_rest_flattened(): + client = PublicDelegatedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.PublicDelegatedPrefixAggregatedList() + + # Wrap the value into a proper Response obj + json_return_value = compute.PublicDelegatedPrefixAggregatedList.to_json( + return_value + ) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.aggregated_list(project="project_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "project_value" in http_call[1] + str(body) + + +def test_aggregated_list_rest_flattened_error(): + client = PublicDelegatedPrefixesClient( + 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.aggregated_list( + compute.AggregatedListPublicDelegatedPrefixesRequest(), + project="project_value", + ) + + +def test_aggregated_list_pager(): + client = PublicDelegatedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Set the response as a series of pages + response = ( + compute.PublicDelegatedPrefixAggregatedList( + items={ + "a": compute.PublicDelegatedPrefixesScopedList(), + "b": compute.PublicDelegatedPrefixesScopedList(), + "c": compute.PublicDelegatedPrefixesScopedList(), + }, + next_page_token="abc", + ), + compute.PublicDelegatedPrefixAggregatedList( + items={}, next_page_token="def", + ), + compute.PublicDelegatedPrefixAggregatedList( + items={"g": compute.PublicDelegatedPrefixesScopedList(),}, + next_page_token="ghi", + ), + compute.PublicDelegatedPrefixAggregatedList( + items={ + "h": compute.PublicDelegatedPrefixesScopedList(), + "i": compute.PublicDelegatedPrefixesScopedList(), + }, + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + compute.PublicDelegatedPrefixAggregatedList.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 + + metadata = () + pager = client.aggregated_list(request={}) + + assert pager._metadata == metadata + + assert isinstance(pager.get("a"), compute.PublicDelegatedPrefixesScopedList) + 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.PublicDelegatedPrefixesScopedList, + ) + + assert pager.get("a") is None + assert isinstance(pager.get("h"), compute.PublicDelegatedPrefixesScopedList) + + pages = list(client.aggregated_list(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_delete_rest( + transport: str = "rest", request_type=compute.DeletePublicDelegatedPrefixeRequest +): + client = PublicDelegatedPrefixesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + error=compute.Error(errors=[compute.Errors(code="code_value")]), + http_error_message="http_error_message_value", + http_error_status_code=2374, + id="id_value", + 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="target_id_value", + target_link="target_link_value", + user="user_value", + warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)], + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + 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, compute.Operation) + 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.error == compute.Error(errors=[compute.Errors(code="code_value")]) + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == "id_value" + 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 == "target_id_value" + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.warnings == [ + compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED) + ] + assert response.zone == "zone_value" + + +def test_delete_rest_from_dict(): + test_delete_rest(request_type=dict) + + +def test_delete_rest_flattened(): + client = PublicDelegatedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete( + project="project_value", + region="region_value", + public_delegated_prefix="public_delegated_prefix_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "project_value" in http_call[1] + str(body) + assert "region_value" in http_call[1] + str(body) + assert "public_delegated_prefix_value" in http_call[1] + str(body) + + +def test_delete_rest_flattened_error(): + client = PublicDelegatedPrefixesClient( + 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( + compute.DeletePublicDelegatedPrefixeRequest(), + project="project_value", + region="region_value", + public_delegated_prefix="public_delegated_prefix_value", + ) + + +def test_get_rest( + transport: str = "rest", request_type=compute.GetPublicDelegatedPrefixeRequest +): + client = PublicDelegatedPrefixesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.PublicDelegatedPrefix( + creation_timestamp="creation_timestamp_value", + description="description_value", + fingerprint="fingerprint_value", + id="id_value", + ip_cidr_range="ip_cidr_range_value", + is_live_migration=True, + kind="kind_value", + name="name_value", + parent_prefix="parent_prefix_value", + public_delegated_sub_prefixs=[ + compute.PublicDelegatedPrefixPublicDelegatedSubPrefix( + delegatee_project="delegatee_project_value" + ) + ], + region="region_value", + self_link="self_link_value", + status=compute.PublicDelegatedPrefix.Status.ANNOUNCED, + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.PublicDelegatedPrefix.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + 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.PublicDelegatedPrefix) + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.fingerprint == "fingerprint_value" + assert response.id == "id_value" + assert response.ip_cidr_range == "ip_cidr_range_value" + assert response.is_live_migration is True + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.parent_prefix == "parent_prefix_value" + assert response.public_delegated_sub_prefixs == [ + compute.PublicDelegatedPrefixPublicDelegatedSubPrefix( + delegatee_project="delegatee_project_value" + ) + ] + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.status == compute.PublicDelegatedPrefix.Status.ANNOUNCED + + +def test_get_rest_from_dict(): + test_get_rest(request_type=dict) + + +def test_get_rest_flattened(): + client = PublicDelegatedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.PublicDelegatedPrefix() + + # Wrap the value into a proper Response obj + json_return_value = compute.PublicDelegatedPrefix.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get( + project="project_value", + region="region_value", + public_delegated_prefix="public_delegated_prefix_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "project_value" in http_call[1] + str(body) + assert "region_value" in http_call[1] + str(body) + assert "public_delegated_prefix_value" in http_call[1] + str(body) + + +def test_get_rest_flattened_error(): + client = PublicDelegatedPrefixesClient( + 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( + compute.GetPublicDelegatedPrefixeRequest(), + project="project_value", + region="region_value", + public_delegated_prefix="public_delegated_prefix_value", + ) + + +def test_insert_rest( + transport: str = "rest", request_type=compute.InsertPublicDelegatedPrefixeRequest +): + client = PublicDelegatedPrefixesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + error=compute.Error(errors=[compute.Errors(code="code_value")]), + http_error_message="http_error_message_value", + http_error_status_code=2374, + id="id_value", + 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="target_id_value", + target_link="target_link_value", + user="user_value", + warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)], + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + 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, compute.Operation) + 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.error == compute.Error(errors=[compute.Errors(code="code_value")]) + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == "id_value" + 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 == "target_id_value" + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.warnings == [ + compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED) + ] + assert response.zone == "zone_value" + + +def test_insert_rest_from_dict(): + test_insert_rest(request_type=dict) + + +def test_insert_rest_flattened(): + client = PublicDelegatedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + public_delegated_prefix_resource = compute.PublicDelegatedPrefix( + creation_timestamp="creation_timestamp_value" + ) + client.insert( + project="project_value", + region="region_value", + public_delegated_prefix_resource=public_delegated_prefix_resource, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "project_value" in http_call[1] + str(body) + assert "region_value" in http_call[1] + str(body) + assert compute.PublicDelegatedPrefix.to_json( + public_delegated_prefix_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) in http_call[1] + str(body) + + +def test_insert_rest_flattened_error(): + client = PublicDelegatedPrefixesClient( + 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.insert( + compute.InsertPublicDelegatedPrefixeRequest(), + project="project_value", + region="region_value", + public_delegated_prefix_resource=compute.PublicDelegatedPrefix( + creation_timestamp="creation_timestamp_value" + ), + ) + + +def test_list_rest( + transport: str = "rest", request_type=compute.ListPublicDelegatedPrefixesRequest +): + client = PublicDelegatedPrefixesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.PublicDelegatedPrefixList( + id="id_value", + items=[ + compute.PublicDelegatedPrefix( + creation_timestamp="creation_timestamp_value" + ) + ], + kind="kind_value", + next_page_token="next_page_token_value", + self_link="self_link_value", + warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.PublicDelegatedPrefixList.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + 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.items == [ + compute.PublicDelegatedPrefix(creation_timestamp="creation_timestamp_value") + ] + assert response.kind == "kind_value" + assert response.next_page_token == "next_page_token_value" + assert response.self_link == "self_link_value" + assert response.warning == compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED) + + +def test_list_rest_from_dict(): + test_list_rest(request_type=dict) + + +def test_list_rest_flattened(): + client = PublicDelegatedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.PublicDelegatedPrefixList() + + # Wrap the value into a proper Response obj + json_return_value = compute.PublicDelegatedPrefixList.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list( + project="project_value", region="region_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "project_value" in http_call[1] + str(body) + assert "region_value" in http_call[1] + str(body) + + +def test_list_rest_flattened_error(): + client = PublicDelegatedPrefixesClient( + 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( + compute.ListPublicDelegatedPrefixesRequest(), + project="project_value", + region="region_value", + ) + + +def test_list_pager(): + client = PublicDelegatedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Set the response as a series of pages + response = ( + compute.PublicDelegatedPrefixList( + items=[ + compute.PublicDelegatedPrefix(), + compute.PublicDelegatedPrefix(), + compute.PublicDelegatedPrefix(), + ], + next_page_token="abc", + ), + compute.PublicDelegatedPrefixList(items=[], next_page_token="def",), + compute.PublicDelegatedPrefixList( + items=[compute.PublicDelegatedPrefix(),], next_page_token="ghi", + ), + compute.PublicDelegatedPrefixList( + items=[ + compute.PublicDelegatedPrefix(), + compute.PublicDelegatedPrefix(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(compute.PublicDelegatedPrefixList.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 + + metadata = () + pager = client.list(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, compute.PublicDelegatedPrefix) for i in results) + + pages = list(client.list(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_patch_rest( + transport: str = "rest", request_type=compute.PatchPublicDelegatedPrefixeRequest +): + client = PublicDelegatedPrefixesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + error=compute.Error(errors=[compute.Errors(code="code_value")]), + http_error_message="http_error_message_value", + http_error_status_code=2374, + id="id_value", + 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="target_id_value", + target_link="target_link_value", + user="user_value", + warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)], + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.patch(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Operation) + 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.error == compute.Error(errors=[compute.Errors(code="code_value")]) + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == "id_value" + 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 == "target_id_value" + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.warnings == [ + compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED) + ] + assert response.zone == "zone_value" + + +def test_patch_rest_from_dict(): + test_patch_rest(request_type=dict) + + +def test_patch_rest_flattened(): + client = PublicDelegatedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + public_delegated_prefix_resource = compute.PublicDelegatedPrefix( + creation_timestamp="creation_timestamp_value" + ) + client.patch( + project="project_value", + region="region_value", + public_delegated_prefix="public_delegated_prefix_value", + public_delegated_prefix_resource=public_delegated_prefix_resource, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "project_value" in http_call[1] + str(body) + assert "region_value" in http_call[1] + str(body) + assert "public_delegated_prefix_value" in http_call[1] + str(body) + assert compute.PublicDelegatedPrefix.to_json( + public_delegated_prefix_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) in http_call[1] + str(body) + + +def test_patch_rest_flattened_error(): + client = PublicDelegatedPrefixesClient( + 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.patch( + compute.PatchPublicDelegatedPrefixeRequest(), + project="project_value", + region="region_value", + public_delegated_prefix="public_delegated_prefix_value", + public_delegated_prefix_resource=compute.PublicDelegatedPrefix( + creation_timestamp="creation_timestamp_value" + ), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.PublicDelegatedPrefixesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PublicDelegatedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.PublicDelegatedPrefixesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PublicDelegatedPrefixesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.PublicDelegatedPrefixesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PublicDelegatedPrefixesClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.PublicDelegatedPrefixesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = PublicDelegatedPrefixesClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", [transports.PublicDelegatedPrefixesRestTransport,] +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_public_delegated_prefixes_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PublicDelegatedPrefixesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_public_delegated_prefixes_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.compute_v1.services.public_delegated_prefixes.transports.PublicDelegatedPrefixesTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.PublicDelegatedPrefixesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "aggregated_list", + "delete", + "get", + "insert", + "list", + "patch", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_public_delegated_prefixes_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.public_delegated_prefixes.transports.PublicDelegatedPrefixesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PublicDelegatedPrefixesTransport( + 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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_public_delegated_prefixes_base_transport_with_credentials_file_old_google_auth(): + # 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.public_delegated_prefixes.transports.PublicDelegatedPrefixesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PublicDelegatedPrefixesTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +def test_public_delegated_prefixes_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.public_delegated_prefixes.transports.PublicDelegatedPrefixesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PublicDelegatedPrefixesTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_public_delegated_prefixes_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) + PublicDelegatedPrefixesClient() + 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, + ) + + +@requires_google_auth_lt_1_25_0 +def test_public_delegated_prefixes_auth_adc_old_google_auth(): + # 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) + PublicDelegatedPrefixesClient() + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +def test_public_delegated_prefixes_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.PublicDelegatedPrefixesRestTransport( + 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_public_delegated_prefixes_host_no_port(): + client = PublicDelegatedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="compute.googleapis.com" + ), + ) + assert client.transport._host == "compute.googleapis.com:443" + + +def test_public_delegated_prefixes_host_with_port(): + client = PublicDelegatedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="compute.googleapis.com:8000" + ), + ) + assert client.transport._host == "compute.googleapis.com:8000" + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = PublicDelegatedPrefixesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = PublicDelegatedPrefixesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = PublicDelegatedPrefixesClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder,) + actual = PublicDelegatedPrefixesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = PublicDelegatedPrefixesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = PublicDelegatedPrefixesClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization,) + actual = PublicDelegatedPrefixesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = PublicDelegatedPrefixesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = PublicDelegatedPrefixesClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project,) + actual = PublicDelegatedPrefixesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = PublicDelegatedPrefixesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = PublicDelegatedPrefixesClient.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 = PublicDelegatedPrefixesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = PublicDelegatedPrefixesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = PublicDelegatedPrefixesClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.PublicDelegatedPrefixesTransport, "_prep_wrapped_messages" + ) as prep: + client = PublicDelegatedPrefixesClient( + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.PublicDelegatedPrefixesTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = PublicDelegatedPrefixesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_autoscalers.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_autoscalers.py index d22537abefcd..9bcec6b41983 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_autoscalers.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_autoscalers.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.region_autoscalers import RegionAutoscalersClient from google.cloud.compute_v1.services.region_autoscalers import pagers from google.cloud.compute_v1.services.region_autoscalers import transports -from google.cloud.compute_v1.services.region_autoscalers.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.region_autoscalers.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -443,6 +431,7 @@ def test_delete_rest( 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", @@ -478,6 +467,7 @@ def test_delete_rest( 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" @@ -568,6 +558,11 @@ def test_get_rest( name="name_value", recommended_size=1693, region="region_value", + scaling_schedule_status={ + "key_value": compute.ScalingScheduleStatus( + last_start_time="last_start_time_value" + ) + }, self_link="self_link_value", status=compute.Autoscaler.Status.ACTIVE, status_details=[compute.AutoscalerStatusDetails(message="message_value")], @@ -595,6 +590,11 @@ def test_get_rest( assert response.name == "name_value" assert response.recommended_size == 1693 assert response.region == "region_value" + assert response.scaling_schedule_status == { + "key_value": compute.ScalingScheduleStatus( + last_start_time="last_start_time_value" + ) + } assert response.self_link == "self_link_value" assert response.status == compute.Autoscaler.Status.ACTIVE assert response.status_details == [ @@ -681,6 +681,7 @@ def test_insert_rest( 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", @@ -716,6 +717,7 @@ def test_insert_rest( 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" @@ -964,6 +966,7 @@ def test_patch_rest( 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", @@ -999,6 +1002,7 @@ def test_patch_rest( 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" @@ -1101,6 +1105,7 @@ def test_update_rest( 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", @@ -1136,6 +1141,7 @@ def test_update_rest( 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" 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 edde9feb2ab1..dd5bb80e6e79 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 @@ -38,9 +38,6 @@ ) from google.cloud.compute_v1.services.region_backend_services import pagers from google.cloud.compute_v1.services.region_backend_services import transports -from google.cloud.compute_v1.services.region_backend_services.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.region_backend_services.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -49,8 +46,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -61,16 +59,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -463,6 +451,7 @@ def test_delete_rest( 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", @@ -498,6 +487,7 @@ def test_delete_rest( 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" @@ -589,7 +579,11 @@ def test_get_rest( compute.Backend(balancing_mode=compute.Backend.BalancingMode.CONNECTION) ], cdn_policy=compute.BackendServiceCdnPolicy( - cache_key_policy=compute.CacheKeyPolicy(include_host=True) + bypass_cache_on_request_headers=[ + compute.BackendServiceCdnPolicyBypassCacheOnRequestHeader( + header_name="header_name_value" + ) + ] ), circuit_breakers=compute.CircuitBreakers(max_connections=1608), connection_draining=compute.ConnectionDraining(draining_timeout_sec=2124), @@ -614,6 +608,7 @@ def test_get_rest( load_balancing_scheme=compute.BackendService.LoadBalancingScheme.EXTERNAL, locality_lb_policy=compute.BackendService.LocalityLbPolicy.INVALID_LB_POLICY, log_config=compute.BackendServiceLogConfig(enable=True), + max_stream_duration=compute.Duration(nanos=543), name="name_value", network="network_value", outlier_detection=compute.OutlierDetection( @@ -647,7 +642,11 @@ def test_get_rest( compute.Backend(balancing_mode=compute.Backend.BalancingMode.CONNECTION) ] assert response.cdn_policy == compute.BackendServiceCdnPolicy( - cache_key_policy=compute.CacheKeyPolicy(include_host=True) + bypass_cache_on_request_headers=[ + compute.BackendServiceCdnPolicyBypassCacheOnRequestHeader( + header_name="header_name_value" + ) + ] ) assert response.circuit_breakers == compute.CircuitBreakers(max_connections=1608) assert response.connection_draining == compute.ConnectionDraining( @@ -680,6 +679,7 @@ def test_get_rest( == compute.BackendService.LocalityLbPolicy.INVALID_LB_POLICY ) assert response.log_config == compute.BackendServiceLogConfig(enable=True) + assert response.max_stream_duration == compute.Duration(nanos=543) assert response.name == "name_value" assert response.network == "network_value" assert response.outlier_detection == compute.OutlierDetection( @@ -885,6 +885,7 @@ def test_insert_rest( 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", @@ -920,6 +921,7 @@ def test_insert_rest( 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" @@ -1166,6 +1168,7 @@ def test_patch_rest( 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", @@ -1201,6 +1204,7 @@ def test_patch_rest( 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" @@ -1308,6 +1312,7 @@ def test_update_rest( 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", @@ -1343,6 +1348,7 @@ def test_update_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_commitments.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_commitments.py index 77220fc2c8a2..9cd8457a5aed 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_commitments.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_commitments.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.region_commitments import RegionCommitmentsClient from google.cloud.compute_v1.services.region_commitments import pagers from google.cloud.compute_v1.services.region_commitments import transports -from google.cloud.compute_v1.services.region_commitments.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.region_commitments.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -725,6 +713,7 @@ def test_insert_rest( 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", @@ -760,6 +749,7 @@ def test_insert_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_disk_types.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_disk_types.py index 3b431f16a244..456fb5c8df0e 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_disk_types.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_disk_types.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.region_disk_types import RegionDiskTypesClient from google.cloud.compute_v1.services.region_disk_types import pagers from google.cloud.compute_v1.services.region_disk_types import transports -from google.cloud.compute_v1.services.region_disk_types.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.region_disk_types.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" 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 8a24d33e6237..1d0cebbb124e 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 @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.region_disks import RegionDisksClient from google.cloud.compute_v1.services.region_disks import pagers from google.cloud.compute_v1.services.region_disks import transports -from google.cloud.compute_v1.services.region_disks.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.region_disks.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -425,6 +413,7 @@ def test_add_resource_policies_rest( 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", @@ -460,6 +449,7 @@ def test_add_resource_policies_rest( 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" @@ -565,6 +555,7 @@ def test_create_snapshot_rest( 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", @@ -600,6 +591,7 @@ def test_create_snapshot_rest( 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" @@ -701,6 +693,7 @@ def test_delete_rest( 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", @@ -736,6 +729,7 @@ def test_delete_rest( 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" @@ -832,12 +826,15 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetRegionDiskReq last_detach_timestamp="last_detach_timestamp_value", license_codes=["license_codes_value"], licenses=["licenses_value"], + location_hint="location_hint_value", name="name_value", options="options_value", physical_block_size_bytes="physical_block_size_bytes_value", + provisioned_iops="provisioned_iops_value", region="region_value", replica_zones=["replica_zones_value"], resource_policies=["resource_policies_value"], + satisfies_pzs=True, self_link="self_link_value", size_gb="size_gb_value", source_disk="source_disk_value", @@ -852,6 +849,7 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetRegionDiskReq kms_key_name="kms_key_name_value" ), source_snapshot_id="source_snapshot_id_value", + source_storage_object="source_storage_object_value", status=compute.Disk.Status.CREATING, type_="type__value", users=["users_value"], @@ -886,12 +884,15 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetRegionDiskReq assert response.last_detach_timestamp == "last_detach_timestamp_value" assert response.license_codes == ["license_codes_value"] assert response.licenses == ["licenses_value"] + assert response.location_hint == "location_hint_value" assert response.name == "name_value" assert response.options == "options_value" assert response.physical_block_size_bytes == "physical_block_size_bytes_value" + assert response.provisioned_iops == "provisioned_iops_value" assert response.region == "region_value" assert response.replica_zones == ["replica_zones_value"] assert response.resource_policies == ["resource_policies_value"] + assert response.satisfies_pzs is True assert response.self_link == "self_link_value" assert response.size_gb == "size_gb_value" assert response.source_disk == "source_disk_value" @@ -906,6 +907,7 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetRegionDiskReq kms_key_name="kms_key_name_value" ) assert response.source_snapshot_id == "source_snapshot_id_value" + assert response.source_storage_object == "source_storage_object_value" assert response.status == compute.Disk.Status.CREATING assert response.type_ == "type__value" assert response.users == ["users_value"] @@ -1091,6 +1093,7 @@ def test_insert_rest( 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", @@ -1126,6 +1129,7 @@ def test_insert_rest( 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" @@ -1353,6 +1357,7 @@ def test_remove_resource_policies_rest( 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", @@ -1388,6 +1393,7 @@ def test_remove_resource_policies_rest( 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" @@ -1493,6 +1499,7 @@ def test_resize_rest( 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", @@ -1528,6 +1535,7 @@ def test_resize_rest( 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" @@ -1751,6 +1759,7 @@ def test_set_labels_rest( 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", @@ -1786,6 +1795,7 @@ def test_set_labels_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_health_check_services.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_health_check_services.py index 9d710d512a29..40d7ad53c8a4 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_health_check_services.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_health_check_services.py @@ -38,9 +38,6 @@ ) from google.cloud.compute_v1.services.region_health_check_services import pagers from google.cloud.compute_v1.services.region_health_check_services import transports -from google.cloud.compute_v1.services.region_health_check_services.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.region_health_check_services.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -49,8 +46,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -61,16 +59,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -469,6 +457,7 @@ def test_delete_rest( 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", @@ -504,6 +493,7 @@ def test_delete_rest( 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" @@ -712,6 +702,7 @@ def test_insert_rest( 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", @@ -747,6 +738,7 @@ def test_insert_rest( 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" @@ -1001,6 +993,7 @@ def test_patch_rest( 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", @@ -1036,6 +1029,7 @@ def test_patch_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_health_checks.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_health_checks.py index 6287e072d80d..4d1eb1d5b708 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_health_checks.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_health_checks.py @@ -38,9 +38,6 @@ ) from google.cloud.compute_v1.services.region_health_checks import pagers from google.cloud.compute_v1.services.region_health_checks import transports -from google.cloud.compute_v1.services.region_health_checks.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.region_health_checks.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -49,8 +46,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -61,16 +59,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -445,6 +433,7 @@ def test_delete_rest( 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", @@ -480,6 +469,7 @@ def test_delete_rest( 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" @@ -703,6 +693,7 @@ def test_insert_rest( 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", @@ -738,6 +729,7 @@ def test_insert_rest( 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" @@ -982,6 +974,7 @@ def test_patch_rest( 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", @@ -1017,6 +1010,7 @@ def test_patch_rest( 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" @@ -1122,6 +1116,7 @@ def test_update_rest( 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", @@ -1157,6 +1152,7 @@ def test_update_rest( 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" 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 bf3a0c6098df..f9c68594cc07 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 @@ -38,9 +38,6 @@ ) from google.cloud.compute_v1.services.region_instance_group_managers import pagers from google.cloud.compute_v1.services.region_instance_group_managers import transports -from google.cloud.compute_v1.services.region_instance_group_managers.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.region_instance_group_managers.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -49,8 +46,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -61,16 +59,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -470,6 +458,7 @@ def test_abandon_instances_rest( 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", @@ -505,6 +494,7 @@ def test_abandon_instances_rest( 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" @@ -615,6 +605,7 @@ def test_apply_updates_to_instances_rest( 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", @@ -650,6 +641,7 @@ def test_apply_updates_to_instances_rest( 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" @@ -760,6 +752,7 @@ def test_create_instances_rest( 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", @@ -795,6 +788,7 @@ def test_create_instances_rest( 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" @@ -905,6 +899,7 @@ def test_delete_rest( 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", @@ -940,6 +935,7 @@ def test_delete_rest( 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" @@ -1038,6 +1034,7 @@ def test_delete_instances_rest( 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", @@ -1073,6 +1070,7 @@ def test_delete_instances_rest( 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" @@ -1183,6 +1181,7 @@ def test_delete_per_instance_configs_rest( 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", @@ -1218,6 +1217,7 @@ def test_delete_per_instance_configs_rest( 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" @@ -1326,7 +1326,7 @@ def test_get_rest( current_actions=compute.InstanceGroupManagerActionsSummary(abandoning=1041), description="description_value", distribution_policy=compute.DistributionPolicy( - zones=[compute.DistributionPolicyZoneConfiguration(zone="zone_value")] + target_shape=compute.DistributionPolicy.TargetShape.ANY ), fingerprint="fingerprint_value", id="id_value", @@ -1380,7 +1380,7 @@ def test_get_rest( ) assert response.description == "description_value" assert response.distribution_policy == compute.DistributionPolicy( - zones=[compute.DistributionPolicyZoneConfiguration(zone="zone_value")] + target_shape=compute.DistributionPolicy.TargetShape.ANY ) assert response.fingerprint == "fingerprint_value" assert response.id == "id_value" @@ -1496,6 +1496,7 @@ def test_insert_rest( 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", @@ -1531,6 +1532,7 @@ def test_insert_rest( 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" @@ -2279,6 +2281,7 @@ def test_patch_rest( 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", @@ -2314,6 +2317,7 @@ def test_patch_rest( 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" @@ -2432,6 +2436,7 @@ def test_patch_per_instance_configs_rest( 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", @@ -2467,6 +2472,7 @@ def test_patch_per_instance_configs_rest( 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" @@ -2581,6 +2587,7 @@ def test_recreate_instances_rest( 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", @@ -2616,6 +2623,7 @@ def test_recreate_instances_rest( 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" @@ -2726,6 +2734,7 @@ def test_resize_rest( 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", @@ -2761,6 +2770,7 @@ def test_resize_rest( 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" @@ -2862,6 +2872,7 @@ def test_set_instance_template_rest( 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", @@ -2897,6 +2908,7 @@ def test_set_instance_template_rest( 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" @@ -3007,6 +3019,7 @@ def test_set_target_pools_rest( 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", @@ -3042,6 +3055,7 @@ def test_set_target_pools_rest( 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" @@ -3152,6 +3166,7 @@ def test_update_per_instance_configs_rest( 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", @@ -3187,6 +3202,7 @@ def test_update_per_instance_configs_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_groups.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_groups.py index 855764bf33b4..54b92c4735fa 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_groups.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_groups.py @@ -38,9 +38,6 @@ ) from google.cloud.compute_v1.services.region_instance_groups import pagers from google.cloud.compute_v1.services.region_instance_groups import transports -from google.cloud.compute_v1.services.region_instance_groups.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.region_instance_groups.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -49,8 +46,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -61,16 +59,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -888,6 +876,7 @@ def test_set_named_ports_rest( 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", @@ -923,6 +912,7 @@ def test_set_named_ports_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instances.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instances.py new file mode 100644 index 000000000000..e38868e108fe --- /dev/null +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instances.py @@ -0,0 +1,854 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from requests import Response +from requests.sessions import Session + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.compute_v1.services.region_instances import RegionInstancesClient +from google.cloud.compute_v1.services.region_instances import transports +from google.cloud.compute_v1.services.region_instances.transports.base import ( + _GOOGLE_AUTH_VERSION, +) +from google.cloud.compute_v1.types import compute +from google.oauth2 import service_account +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + + +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 + ) + + +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 RegionInstancesClient._get_default_mtls_endpoint(None) is None + assert ( + RegionInstancesClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + RegionInstancesClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + RegionInstancesClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + RegionInstancesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + RegionInstancesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + + +@pytest.mark.parametrize("client_class", [RegionInstancesClient,]) +def test_region_instances_client_from_service_account_info(client_class): + 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) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == "compute.googleapis.com:443" + + +@pytest.mark.parametrize("client_class", [RegionInstancesClient,]) +def test_region_instances_client_from_service_account_file(client_class): + 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") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == "compute.googleapis.com:443" + + +def test_region_instances_client_get_transport_class(): + transport = RegionInstancesClient.get_transport_class() + available_transports = [ + transports.RegionInstancesRestTransport, + ] + assert transport in available_transports + + transport = RegionInstancesClient.get_transport_class("rest") + assert transport == transports.RegionInstancesRestTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [(RegionInstancesClient, transports.RegionInstancesRestTransport, "rest"),], +) +@mock.patch.object( + RegionInstancesClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RegionInstancesClient), +) +def test_region_instances_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(RegionInstancesClient, "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(RegionInstancesClient, "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(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, + ) + + # 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() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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() + 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, + ) + + # 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): + client = client_class() + + # 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): + client = client_class() + + # 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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + RegionInstancesClient, + transports.RegionInstancesRestTransport, + "rest", + "true", + ), + ( + RegionInstancesClient, + transports.RegionInstancesRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + RegionInstancesClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RegionInstancesClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_region_instances_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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + 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, + ) + + # 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 + 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() + 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, + ) + + # 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() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [(RegionInstancesClient, transports.RegionInstancesRestTransport, "rest"),], +) +def test_region_instances_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) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [(RegionInstancesClient, transports.RegionInstancesRestTransport, "rest"),], +) +def test_region_instances_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # 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) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_bulk_insert_rest( + transport: str = "rest", request_type=compute.BulkInsertRegionInstanceRequest +): + client = RegionInstancesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + error=compute.Error(errors=[compute.Errors(code="code_value")]), + http_error_message="http_error_message_value", + http_error_status_code=2374, + id="id_value", + 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="target_id_value", + target_link="target_link_value", + user="user_value", + warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)], + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.bulk_insert(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Operation) + 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.error == compute.Error(errors=[compute.Errors(code="code_value")]) + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == "id_value" + 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 == "target_id_value" + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.warnings == [ + compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED) + ] + assert response.zone == "zone_value" + + +def test_bulk_insert_rest_from_dict(): + test_bulk_insert_rest(request_type=dict) + + +def test_bulk_insert_rest_flattened(): + client = RegionInstancesClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + bulk_insert_instance_resource_resource = compute.BulkInsertInstanceResource( + count="count_value" + ) + client.bulk_insert( + project="project_value", + region="region_value", + bulk_insert_instance_resource_resource=bulk_insert_instance_resource_resource, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "project_value" in http_call[1] + str(body) + assert "region_value" in http_call[1] + str(body) + assert compute.BulkInsertInstanceResource.to_json( + bulk_insert_instance_resource_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) in http_call[1] + str(body) + + +def test_bulk_insert_rest_flattened_error(): + client = RegionInstancesClient(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_insert( + compute.BulkInsertRegionInstanceRequest(), + project="project_value", + region="region_value", + bulk_insert_instance_resource_resource=compute.BulkInsertInstanceResource( + count="count_value" + ), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RegionInstancesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionInstancesClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RegionInstancesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionInstancesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RegionInstancesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionInstancesClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RegionInstancesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RegionInstancesClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize("transport_class", [transports.RegionInstancesRestTransport,]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_region_instances_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.RegionInstancesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_region_instances_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.compute_v1.services.region_instances.transports.RegionInstancesTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.RegionInstancesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ("bulk_insert",) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_region_instances_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_instances.transports.RegionInstancesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionInstancesTransport( + 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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_region_instances_base_transport_with_credentials_file_old_google_auth(): + # 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_instances.transports.RegionInstancesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionInstancesTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +def test_region_instances_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_instances.transports.RegionInstancesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionInstancesTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_region_instances_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) + RegionInstancesClient() + 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, + ) + + +@requires_google_auth_lt_1_25_0 +def test_region_instances_auth_adc_old_google_auth(): + # 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) + RegionInstancesClient() + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +def test_region_instances_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.RegionInstancesRestTransport( + 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_region_instances_host_no_port(): + client = RegionInstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="compute.googleapis.com" + ), + ) + assert client.transport._host == "compute.googleapis.com:443" + + +def test_region_instances_host_with_port(): + client = RegionInstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="compute.googleapis.com:8000" + ), + ) + assert client.transport._host == "compute.googleapis.com:8000" + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = RegionInstancesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = RegionInstancesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RegionInstancesClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder,) + actual = RegionInstancesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = RegionInstancesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RegionInstancesClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization,) + actual = RegionInstancesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = RegionInstancesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RegionInstancesClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project,) + actual = RegionInstancesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = RegionInstancesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RegionInstancesClient.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 = RegionInstancesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = RegionInstancesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RegionInstancesClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.RegionInstancesTransport, "_prep_wrapped_messages" + ) as prep: + client = RegionInstancesClient( + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.RegionInstancesTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = RegionInstancesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_network_endpoint_groups.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_network_endpoint_groups.py index 5afc043adcd5..099f677e4925 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_network_endpoint_groups.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_network_endpoint_groups.py @@ -38,9 +38,6 @@ ) from google.cloud.compute_v1.services.region_network_endpoint_groups import pagers from google.cloud.compute_v1.services.region_network_endpoint_groups import transports -from google.cloud.compute_v1.services.region_network_endpoint_groups.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.region_network_endpoint_groups.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -49,8 +46,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -61,16 +59,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -470,6 +458,7 @@ def test_delete_rest( 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", @@ -505,6 +494,7 @@ def test_delete_rest( 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" @@ -604,7 +594,7 @@ def test_get_rest( kind="kind_value", name="name_value", network="network_value", - network_endpoint_type=compute.NetworkEndpointGroup.NetworkEndpointType.GCE_VM_IP_PORT, + network_endpoint_type=compute.NetworkEndpointGroup.NetworkEndpointType.GCE_VM_IP, region="region_value", self_link="self_link_value", size=443, @@ -641,7 +631,7 @@ def test_get_rest( assert response.network == "network_value" assert ( response.network_endpoint_type - == compute.NetworkEndpointGroup.NetworkEndpointType.GCE_VM_IP_PORT + == compute.NetworkEndpointGroup.NetworkEndpointType.GCE_VM_IP ) assert response.region == "region_value" assert response.self_link == "self_link_value" @@ -732,6 +722,7 @@ def test_insert_rest( 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", @@ -767,6 +758,7 @@ def test_insert_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_notification_endpoints.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_notification_endpoints.py index ab5f0e2b45b0..8719081af9e2 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_notification_endpoints.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_notification_endpoints.py @@ -38,9 +38,6 @@ ) from google.cloud.compute_v1.services.region_notification_endpoints import pagers from google.cloud.compute_v1.services.region_notification_endpoints import transports -from google.cloud.compute_v1.services.region_notification_endpoints.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.region_notification_endpoints.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -49,8 +46,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -61,16 +59,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -470,6 +458,7 @@ def test_delete_rest( 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", @@ -505,6 +494,7 @@ def test_delete_rest( 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" @@ -707,6 +697,7 @@ def test_insert_rest( 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", @@ -742,6 +733,7 @@ def test_insert_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_operations.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_operations.py index d4dbfe84860f..94ca3699c648 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_operations.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_operations.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.region_operations import RegionOperationsClient from google.cloud.compute_v1.services.region_operations import pagers from google.cloud.compute_v1.services.region_operations import transports -from google.cloud.compute_v1.services.region_operations.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.region_operations.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -520,6 +508,7 @@ def test_get_rest( 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", @@ -555,6 +544,7 @@ def test_get_rest( 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" @@ -776,6 +766,7 @@ def test_wait_rest( 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", @@ -811,6 +802,7 @@ def test_wait_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_ssl_certificates.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_ssl_certificates.py index e2e60bb87991..a869abde50b1 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_ssl_certificates.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_ssl_certificates.py @@ -38,9 +38,6 @@ ) from google.cloud.compute_v1.services.region_ssl_certificates import pagers from google.cloud.compute_v1.services.region_ssl_certificates import transports -from google.cloud.compute_v1.services.region_ssl_certificates.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.region_ssl_certificates.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -49,8 +46,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -61,16 +59,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -463,6 +451,7 @@ def test_delete_rest( 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", @@ -498,6 +487,7 @@ def test_delete_rest( 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" @@ -715,6 +705,7 @@ def test_insert_rest( 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", @@ -750,6 +741,7 @@ def test_insert_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_target_http_proxies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_target_http_proxies.py index 146189aecac1..a5d92bff52a2 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_target_http_proxies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_target_http_proxies.py @@ -38,9 +38,6 @@ ) from google.cloud.compute_v1.services.region_target_http_proxies import pagers from google.cloud.compute_v1.services.region_target_http_proxies import transports -from google.cloud.compute_v1.services.region_target_http_proxies.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.region_target_http_proxies.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -49,8 +46,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -61,16 +59,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -463,6 +451,7 @@ def test_delete_rest( 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", @@ -498,6 +487,7 @@ def test_delete_rest( 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" @@ -699,6 +689,7 @@ def test_insert_rest( 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", @@ -734,6 +725,7 @@ def test_insert_rest( 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" @@ -986,6 +978,7 @@ def test_set_url_map_rest( 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", @@ -1021,6 +1014,7 @@ def test_set_url_map_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_target_https_proxies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_target_https_proxies.py index eb6a150f0f4d..d926deebdf1d 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_target_https_proxies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_target_https_proxies.py @@ -38,9 +38,6 @@ ) from google.cloud.compute_v1.services.region_target_https_proxies import pagers from google.cloud.compute_v1.services.region_target_https_proxies import transports -from google.cloud.compute_v1.services.region_target_https_proxies.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.region_target_https_proxies.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -49,8 +46,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -61,16 +59,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -467,6 +455,7 @@ def test_delete_rest( 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", @@ -502,6 +491,7 @@ def test_delete_rest( 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" @@ -591,6 +581,7 @@ def test_get_rest( authorization_policy="authorization_policy_value", creation_timestamp="creation_timestamp_value", description="description_value", + fingerprint="fingerprint_value", id="id_value", kind="kind_value", name="name_value", @@ -617,6 +608,7 @@ def test_get_rest( assert response.authorization_policy == "authorization_policy_value" assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" + assert response.fingerprint == "fingerprint_value" assert response.id == "id_value" assert response.kind == "kind_value" assert response.name == "name_value" @@ -711,6 +703,7 @@ def test_insert_rest( 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", @@ -746,6 +739,7 @@ def test_insert_rest( 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" @@ -1001,6 +995,7 @@ def test_set_ssl_certificates_rest( 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", @@ -1036,6 +1031,7 @@ def test_set_ssl_certificates_rest( 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" @@ -1145,6 +1141,7 @@ def test_set_url_map_rest( 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", @@ -1180,6 +1177,7 @@ def test_set_url_map_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_url_maps.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_url_maps.py index 863019f4d5e4..6aa557a5975b 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_url_maps.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_url_maps.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.region_url_maps import RegionUrlMapsClient from google.cloud.compute_v1.services.region_url_maps import pagers from google.cloud.compute_v1.services.region_url_maps import transports -from google.cloud.compute_v1.services.region_url_maps.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.region_url_maps.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -432,6 +420,7 @@ def test_delete_rest( 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", @@ -467,6 +456,7 @@ def test_delete_rest( 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" @@ -692,6 +682,7 @@ def test_insert_rest( 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", @@ -727,6 +718,7 @@ def test_insert_rest( 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" @@ -957,6 +949,7 @@ def test_patch_rest( 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", @@ -992,6 +985,7 @@ def test_patch_rest( 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" @@ -1095,6 +1089,7 @@ def test_update_rest( 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", @@ -1130,6 +1125,7 @@ def test_update_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_regions.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_regions.py index 324dc36c2316..dd53a7bf25b8 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_regions.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_regions.py @@ -36,7 +36,6 @@ from google.cloud.compute_v1.services.regions import RegionsClient from google.cloud.compute_v1.services.regions import pagers from google.cloud.compute_v1.services.regions import transports -from google.cloud.compute_v1.services.regions.transports.base import _API_CORE_VERSION from google.cloud.compute_v1.services.regions.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -45,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -57,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -414,6 +404,7 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetRegionRequest quotas=[compute.Quota(limit=0.543)], self_link="self_link_value", status=compute.Region.Status.DOWN, + supports_pzs=True, zones=["zones_value"], ) @@ -436,6 +427,7 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetRegionRequest assert response.quotas == [compute.Quota(limit=0.543)] assert response.self_link == "self_link_value" assert response.status == compute.Region.Status.DOWN + assert response.supports_pzs is True assert response.zones == ["zones_value"] diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_reservations.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_reservations.py index 588da231f822..b207a87a6fb5 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_reservations.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_reservations.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.reservations import ReservationsClient from google.cloud.compute_v1.services.reservations import pagers from google.cloud.compute_v1.services.reservations import transports -from google.cloud.compute_v1.services.reservations.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.reservations.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -581,6 +569,7 @@ def test_delete_rest( 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", @@ -616,6 +605,7 @@ def test_delete_rest( 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" @@ -700,6 +690,7 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetReservationRe id="id_value", kind="kind_value", name="name_value", + satisfies_pzs=True, self_link="self_link_value", specific_reservation=compute.AllocationSpecificSKUReservation( count="count_value" @@ -725,6 +716,7 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetReservationRe assert response.id == "id_value" assert response.kind == "kind_value" assert response.name == "name_value" + assert response.satisfies_pzs is True assert response.self_link == "self_link_value" assert response.specific_reservation == compute.AllocationSpecificSKUReservation( count="count_value" @@ -913,6 +905,7 @@ def test_insert_rest( 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", @@ -948,6 +941,7 @@ def test_insert_rest( 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" @@ -1182,6 +1176,7 @@ def test_resize_rest( 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", @@ -1217,6 +1212,7 @@ def test_resize_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_resource_policies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_resource_policies.py index b082062c3134..05b8ed4c350b 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_resource_policies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_resource_policies.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.resource_policies import ResourcePoliciesClient from google.cloud.compute_v1.services.resource_policies import pagers from google.cloud.compute_v1.services.resource_policies import transports -from google.cloud.compute_v1.services.resource_policies.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.resource_policies.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -610,6 +598,7 @@ def test_delete_rest( 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", @@ -645,6 +634,7 @@ def test_delete_rest( 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" @@ -733,9 +723,17 @@ def test_get_rest( availability_domain_count=2650 ), id="id_value", + instance_schedule_policy=compute.ResourcePolicyInstanceSchedulePolicy( + expiration_time="expiration_time_value" + ), kind="kind_value", name="name_value", region="region_value", + resource_status=compute.ResourcePolicyResourceStatus( + instance_schedule_policy=compute.ResourcePolicyResourceStatusInstanceSchedulePolicyStatus( + last_run_start_time="last_run_start_time_value" + ) + ), self_link="self_link_value", snapshot_schedule_policy=compute.ResourcePolicySnapshotSchedulePolicy( retention_policy=compute.ResourcePolicySnapshotSchedulePolicyRetentionPolicy( @@ -762,9 +760,20 @@ def test_get_rest( == compute.ResourcePolicyGroupPlacementPolicy(availability_domain_count=2650) ) assert response.id == "id_value" + assert ( + response.instance_schedule_policy + == compute.ResourcePolicyInstanceSchedulePolicy( + expiration_time="expiration_time_value" + ) + ) assert response.kind == "kind_value" assert response.name == "name_value" assert response.region == "region_value" + assert response.resource_status == compute.ResourcePolicyResourceStatus( + instance_schedule_policy=compute.ResourcePolicyResourceStatusInstanceSchedulePolicyStatus( + last_run_start_time="last_run_start_time_value" + ) + ) assert response.self_link == "self_link_value" assert ( response.snapshot_schedule_policy @@ -958,6 +967,7 @@ def test_insert_rest( 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", @@ -993,6 +1003,7 @@ def test_insert_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_routers.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_routers.py index 990e3f53f601..9d215ccd0f1d 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_routers.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_routers.py @@ -36,7 +36,6 @@ from google.cloud.compute_v1.services.routers import RoutersClient from google.cloud.compute_v1.services.routers import pagers from google.cloud.compute_v1.services.routers import transports -from google.cloud.compute_v1.services.routers.transports.base import _API_CORE_VERSION from google.cloud.compute_v1.services.routers.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -45,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -57,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -581,6 +571,7 @@ def test_delete_rest(transport: str = "rest", request_type=compute.DeleteRouterR 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", @@ -616,6 +607,7 @@ def test_delete_rest(transport: str = "rest", request_type=compute.DeleteRouterR 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" @@ -704,6 +696,7 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetRouterRequest ], creation_timestamp="creation_timestamp_value", description="description_value", + encrypted_interconnect_router=True, id="id_value", interfaces=[compute.RouterInterface(ip_range="ip_range_value")], kind="kind_value", @@ -732,6 +725,7 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetRouterRequest ] assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" + assert response.encrypted_interconnect_router is True assert response.id == "id_value" assert response.interfaces == [compute.RouterInterface(ip_range="ip_range_value")] assert response.kind == "kind_value" @@ -1046,6 +1040,7 @@ def test_insert_rest(transport: str = "rest", request_type=compute.InsertRouterR 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", @@ -1081,6 +1076,7 @@ def test_insert_rest(transport: str = "rest", request_type=compute.InsertRouterR 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" @@ -1319,6 +1315,7 @@ def test_patch_rest(transport: str = "rest", request_type=compute.PatchRouterReq 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", @@ -1354,6 +1351,7 @@ def test_patch_rest(transport: str = "rest", request_type=compute.PatchRouterReq 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" @@ -1561,6 +1559,7 @@ def test_update_rest(transport: str = "rest", request_type=compute.UpdateRouterR 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", @@ -1596,6 +1595,7 @@ def test_update_rest(transport: str = "rest", request_type=compute.UpdateRouterR 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_routes.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_routes.py index 63fef8c82e74..98571a88bd23 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_routes.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_routes.py @@ -36,15 +36,15 @@ from google.cloud.compute_v1.services.routes import RoutesClient from google.cloud.compute_v1.services.routes import pagers from google.cloud.compute_v1.services.routes import transports -from google.cloud.compute_v1.services.routes.transports.base import _API_CORE_VERSION from google.cloud.compute_v1.services.routes.transports.base import _GOOGLE_AUTH_VERSION from google.cloud.compute_v1.types import compute from google.oauth2 import service_account import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -55,16 +55,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -414,6 +404,7 @@ def test_delete_rest(transport: str = "rest", request_type=compute.DeleteRouteRe 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", @@ -449,6 +440,7 @@ def test_delete_rest(transport: str = "rest", request_type=compute.DeleteRouteRe 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" @@ -644,6 +636,7 @@ def test_insert_rest(transport: str = "rest", request_type=compute.InsertRouteRe 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", @@ -679,6 +672,7 @@ def test_insert_rest(transport: str = "rest", request_type=compute.InsertRouteRe 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_security_policies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_security_policies.py index 85b8e2e4386e..620812004242 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_security_policies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_security_policies.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.security_policies import SecurityPoliciesClient from google.cloud.compute_v1.services.security_policies import pagers from google.cloud.compute_v1.services.security_policies import transports -from google.cloud.compute_v1.services.security_policies.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.security_policies.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -443,6 +431,7 @@ def test_add_rule_rest( 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", @@ -478,6 +467,7 @@ def test_add_rule_rest( 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" @@ -580,6 +570,7 @@ def test_delete_rest( 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", @@ -615,6 +606,7 @@ def test_delete_rest( 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" @@ -892,6 +884,7 @@ def test_insert_rest( 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", @@ -927,6 +920,7 @@ def test_insert_rest( 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" @@ -1249,6 +1243,7 @@ def test_patch_rest( 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", @@ -1284,6 +1279,7 @@ def test_patch_rest( 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" @@ -1386,6 +1382,7 @@ def test_patch_rule_rest( 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", @@ -1421,6 +1418,7 @@ def test_patch_rule_rest( 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" @@ -1523,6 +1521,7 @@ def test_remove_rule_rest( 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", @@ -1558,6 +1557,7 @@ def test_remove_rule_rest( 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" 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 3e5d6dd2c1f3..7cf38a538ad7 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 @@ -36,7 +36,6 @@ from google.cloud.compute_v1.services.snapshots import SnapshotsClient from google.cloud.compute_v1.services.snapshots import pagers from google.cloud.compute_v1.services.snapshots import transports -from google.cloud.compute_v1.services.snapshots.transports.base import _API_CORE_VERSION from google.cloud.compute_v1.services.snapshots.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -45,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -57,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -419,6 +409,7 @@ def test_delete_rest( 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", @@ -454,6 +445,7 @@ def test_delete_rest( 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" @@ -542,7 +534,9 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetSnapshotReque labels={"key_value": "value_value"}, license_codes=["license_codes_value"], licenses=["licenses_value"], + location_hint="location_hint_value", name="name_value", + satisfies_pzs=True, self_link="self_link_value", snapshot_encryption_key=compute.CustomerEncryptionKey( kms_key_name="kms_key_name_value" @@ -580,7 +574,9 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetSnapshotReque assert response.labels == {"key_value": "value_value"} assert response.license_codes == ["license_codes_value"] assert response.licenses == ["licenses_value"] + assert response.location_hint == "location_hint_value" assert response.name == "name_value" + assert response.satisfies_pzs is True assert response.self_link == "self_link_value" assert response.snapshot_encryption_key == compute.CustomerEncryptionKey( kms_key_name="kms_key_name_value" @@ -1007,6 +1003,7 @@ def test_set_labels_rest( 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", @@ -1042,6 +1039,7 @@ def test_set_labels_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_ssl_certificates.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_ssl_certificates.py index 4cc2ddf82234..08064f887a8a 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_ssl_certificates.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_ssl_certificates.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.ssl_certificates import SslCertificatesClient from google.cloud.compute_v1.services.ssl_certificates import pagers from google.cloud.compute_v1.services.ssl_certificates import transports -from google.cloud.compute_v1.services.ssl_certificates.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.ssl_certificates.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -603,6 +591,7 @@ def test_delete_rest( 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", @@ -638,6 +627,7 @@ def test_delete_rest( 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" @@ -839,6 +829,7 @@ def test_insert_rest( 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", @@ -874,6 +865,7 @@ def test_insert_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_ssl_policies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_ssl_policies.py index 845a11bd4d4f..08844d4ba353 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_ssl_policies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_ssl_policies.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.ssl_policies import SslPoliciesClient from google.cloud.compute_v1.services.ssl_policies import pagers from google.cloud.compute_v1.services.ssl_policies import transports -from google.cloud.compute_v1.services.ssl_policies.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.ssl_policies.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -425,6 +413,7 @@ def test_delete_rest( 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", @@ -460,6 +449,7 @@ def test_delete_rest( 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" @@ -649,6 +639,7 @@ def test_insert_rest( 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", @@ -684,6 +675,7 @@ def test_insert_rest( 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" @@ -987,6 +979,7 @@ def test_patch_rest( 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", @@ -1022,6 +1015,7 @@ def test_patch_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_subnetworks.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_subnetworks.py index 5502d59dec5e..4ac9a417532e 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_subnetworks.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_subnetworks.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.subnetworks import SubnetworksClient from google.cloud.compute_v1.services.subnetworks import pagers from google.cloud.compute_v1.services.subnetworks import transports -from google.cloud.compute_v1.services.subnetworks.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.subnetworks.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -587,6 +575,7 @@ def test_delete_rest( 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", @@ -622,6 +611,7 @@ def test_delete_rest( 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" @@ -715,6 +705,7 @@ def test_expand_ip_cidr_range_rest( 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", @@ -750,6 +741,7 @@ def test_expand_ip_cidr_range_rest( 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" @@ -1088,6 +1080,7 @@ def test_insert_rest( 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", @@ -1123,6 +1116,7 @@ def test_insert_rest( 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" @@ -1502,6 +1496,7 @@ def test_patch_rest( 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", @@ -1537,6 +1532,7 @@ def test_patch_rest( 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" @@ -1761,6 +1757,7 @@ def test_set_private_ip_google_access_rest( 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", @@ -1796,6 +1793,7 @@ def test_set_private_ip_google_access_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_grpc_proxies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_grpc_proxies.py index 5fd2bb1d2969..8f313530ec3e 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_grpc_proxies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_grpc_proxies.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.target_grpc_proxies import TargetGrpcProxiesClient from google.cloud.compute_v1.services.target_grpc_proxies import pagers from google.cloud.compute_v1.services.target_grpc_proxies import transports -from google.cloud.compute_v1.services.target_grpc_proxies.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.target_grpc_proxies.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -443,6 +431,7 @@ def test_delete_rest( 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", @@ -478,6 +467,7 @@ def test_delete_rest( 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" @@ -663,6 +653,7 @@ def test_insert_rest( 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", @@ -698,6 +689,7 @@ def test_insert_rest( 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" @@ -932,6 +924,7 @@ def test_patch_rest( 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", @@ -967,6 +960,7 @@ def test_patch_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_http_proxies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_http_proxies.py index 379a93a825eb..81575216d8cf 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_http_proxies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_http_proxies.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.target_http_proxies import TargetHttpProxiesClient from google.cloud.compute_v1.services.target_http_proxies import pagers from google.cloud.compute_v1.services.target_http_proxies import transports -from google.cloud.compute_v1.services.target_http_proxies.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.target_http_proxies.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -606,6 +594,7 @@ def test_delete_rest( 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", @@ -641,6 +630,7 @@ def test_delete_rest( 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" @@ -826,6 +816,7 @@ def test_insert_rest( 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", @@ -861,6 +852,7 @@ def test_insert_rest( 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" @@ -1095,6 +1087,7 @@ def test_patch_rest( 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", @@ -1130,6 +1123,7 @@ def test_patch_rest( 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" @@ -1232,6 +1226,7 @@ def test_set_url_map_rest( 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", @@ -1267,6 +1262,7 @@ def test_set_url_map_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_https_proxies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_https_proxies.py index 10ccf7f813bd..07c0591de764 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_https_proxies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_https_proxies.py @@ -38,9 +38,6 @@ ) from google.cloud.compute_v1.services.target_https_proxies import pagers from google.cloud.compute_v1.services.target_https_proxies import transports -from google.cloud.compute_v1.services.target_https_proxies.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.target_https_proxies.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -49,8 +46,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -61,16 +59,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -619,6 +607,7 @@ def test_delete_rest( 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", @@ -654,6 +643,7 @@ def test_delete_rest( 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" @@ -739,6 +729,7 @@ def test_get_rest( authorization_policy="authorization_policy_value", creation_timestamp="creation_timestamp_value", description="description_value", + fingerprint="fingerprint_value", id="id_value", kind="kind_value", name="name_value", @@ -765,6 +756,7 @@ def test_get_rest( assert response.authorization_policy == "authorization_policy_value" assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" + assert response.fingerprint == "fingerprint_value" assert response.id == "id_value" assert response.kind == "kind_value" assert response.name == "name_value" @@ -855,6 +847,7 @@ def test_insert_rest( 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", @@ -890,6 +883,7 @@ def test_insert_rest( 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" @@ -1110,6 +1104,149 @@ def test_list_pager(): assert page_.raw_page.next_page_token == token +def test_patch_rest( + transport: str = "rest", request_type=compute.PatchTargetHttpsProxyRequest +): + client = TargetHttpsProxiesClient( + 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 http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + error=compute.Error(errors=[compute.Errors(code="code_value")]), + http_error_message="http_error_message_value", + http_error_status_code=2374, + id="id_value", + 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="target_id_value", + target_link="target_link_value", + user="user_value", + warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)], + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.patch(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Operation) + 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.error == compute.Error(errors=[compute.Errors(code="code_value")]) + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == "id_value" + 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 == "target_id_value" + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.warnings == [ + compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED) + ] + assert response.zone == "zone_value" + + +def test_patch_rest_from_dict(): + test_patch_rest(request_type=dict) + + +def test_patch_rest_flattened(): + client = TargetHttpsProxiesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # Wrap the value into a proper Response obj + json_return_value = compute.Operation.to_json(return_value) + response_value = Response() + response_value.status_code = 200 + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + target_https_proxy_resource = compute.TargetHttpsProxy( + authorization_policy="authorization_policy_value" + ) + client.patch( + project="project_value", + target_https_proxy="target_https_proxy_value", + target_https_proxy_resource=target_https_proxy_resource, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, http_call, http_params = req.mock_calls[0] + body = http_params.get("data") + assert "project_value" in http_call[1] + str(body) + assert "target_https_proxy_value" in http_call[1] + str(body) + assert compute.TargetHttpsProxy.to_json( + target_https_proxy_resource, + including_default_value_fields=False, + use_integers_for_enums=False, + ) in http_call[1] + str(body) + + +def test_patch_rest_flattened_error(): + client = TargetHttpsProxiesClient( + 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.patch( + compute.PatchTargetHttpsProxyRequest(), + project="project_value", + target_https_proxy="target_https_proxy_value", + target_https_proxy_resource=compute.TargetHttpsProxy( + authorization_policy="authorization_policy_value" + ), + ) + + def test_set_quic_override_rest( transport: str = "rest", request_type=compute.SetQuicOverrideTargetHttpsProxyRequest ): @@ -1136,6 +1273,7 @@ def test_set_quic_override_rest( 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", @@ -1171,6 +1309,7 @@ def test_set_quic_override_rest( 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" @@ -1278,6 +1417,7 @@ def test_set_ssl_certificates_rest( 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", @@ -1313,6 +1453,7 @@ def test_set_ssl_certificates_rest( 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" @@ -1419,6 +1560,7 @@ def test_set_ssl_policy_rest( 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", @@ -1454,6 +1596,7 @@ def test_set_ssl_policy_rest( 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" @@ -1560,6 +1703,7 @@ def test_set_url_map_rest( 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", @@ -1595,6 +1739,7 @@ def test_set_url_map_rest( 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" @@ -1748,6 +1893,7 @@ def test_target_https_proxies_base_transport(): "get", "insert", "list", + "patch", "set_quic_override", "set_ssl_certificates", "set_ssl_policy", diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_instances.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_instances.py index 1c8099e93a4d..a2b6fd1bab24 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_instances.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_instances.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.target_instances import TargetInstancesClient from google.cloud.compute_v1.services.target_instances import pagers from google.cloud.compute_v1.services.target_instances import transports -from google.cloud.compute_v1.services.target_instances.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.target_instances.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -607,6 +595,7 @@ def test_delete_rest( 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", @@ -642,6 +631,7 @@ def test_delete_rest( 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" @@ -833,6 +823,7 @@ def test_insert_rest( 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", @@ -868,6 +859,7 @@ def test_insert_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_pools.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_pools.py index e34ef3b29dc9..7a5254ad5e30 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_pools.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_pools.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.target_pools import TargetPoolsClient from google.cloud.compute_v1.services.target_pools import pagers from google.cloud.compute_v1.services.target_pools import transports -from google.cloud.compute_v1.services.target_pools.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.target_pools.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -425,6 +413,7 @@ def test_add_health_check_rest( 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", @@ -460,6 +449,7 @@ def test_add_health_check_rest( 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" @@ -569,6 +559,7 @@ def test_add_instance_rest( 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", @@ -604,6 +595,7 @@ def test_add_instance_rest( 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" @@ -865,6 +857,7 @@ def test_delete_rest( 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", @@ -900,6 +893,7 @@ def test_delete_rest( 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" @@ -1195,6 +1189,7 @@ def test_insert_rest( 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", @@ -1230,6 +1225,7 @@ def test_insert_rest( 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" @@ -1464,6 +1460,7 @@ def test_remove_health_check_rest( 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", @@ -1499,6 +1496,7 @@ def test_remove_health_check_rest( 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" @@ -1608,6 +1606,7 @@ def test_remove_instance_rest( 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", @@ -1643,6 +1642,7 @@ def test_remove_instance_rest( 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" @@ -1748,6 +1748,7 @@ def test_set_backup_rest( 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", @@ -1783,6 +1784,7 @@ def test_set_backup_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_ssl_proxies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_ssl_proxies.py index c1c8265b63ae..aa4a5ec16de6 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_ssl_proxies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_ssl_proxies.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.target_ssl_proxies import TargetSslProxiesClient from google.cloud.compute_v1.services.target_ssl_proxies import pagers from google.cloud.compute_v1.services.target_ssl_proxies import transports -from google.cloud.compute_v1.services.target_ssl_proxies.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.target_ssl_proxies.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -443,6 +431,7 @@ def test_delete_rest( 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", @@ -478,6 +467,7 @@ def test_delete_rest( 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" @@ -663,6 +653,7 @@ def test_insert_rest( 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", @@ -698,6 +689,7 @@ def test_insert_rest( 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" @@ -932,6 +924,7 @@ def test_set_backend_service_rest( 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", @@ -967,6 +960,7 @@ def test_set_backend_service_rest( 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" @@ -1069,6 +1063,7 @@ def test_set_proxy_header_rest( 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", @@ -1104,6 +1099,7 @@ def test_set_proxy_header_rest( 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" @@ -1207,6 +1203,7 @@ def test_set_ssl_certificates_rest( 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", @@ -1242,6 +1239,7 @@ def test_set_ssl_certificates_rest( 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" @@ -1344,6 +1342,7 @@ def test_set_ssl_policy_rest( 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", @@ -1379,6 +1378,7 @@ def test_set_ssl_policy_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_tcp_proxies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_tcp_proxies.py index 15c3146d1f24..0b5da0d8b228 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_tcp_proxies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_tcp_proxies.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.target_tcp_proxies import TargetTcpProxiesClient from google.cloud.compute_v1.services.target_tcp_proxies import pagers from google.cloud.compute_v1.services.target_tcp_proxies import transports -from google.cloud.compute_v1.services.target_tcp_proxies.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.target_tcp_proxies.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -443,6 +431,7 @@ def test_delete_rest( 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", @@ -478,6 +467,7 @@ def test_delete_rest( 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" @@ -561,6 +551,7 @@ def test_get_rest( id="id_value", kind="kind_value", name="name_value", + proxy_bind=True, proxy_header=compute.TargetTcpProxy.ProxyHeader.NONE, self_link="self_link_value", service="service_value", @@ -581,6 +572,7 @@ def test_get_rest( assert response.id == "id_value" assert response.kind == "kind_value" assert response.name == "name_value" + assert response.proxy_bind is True assert response.proxy_header == compute.TargetTcpProxy.ProxyHeader.NONE assert response.self_link == "self_link_value" assert response.service == "service_value" @@ -659,6 +651,7 @@ def test_insert_rest( 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", @@ -694,6 +687,7 @@ def test_insert_rest( 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" @@ -928,6 +922,7 @@ def test_set_backend_service_rest( 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", @@ -963,6 +958,7 @@ def test_set_backend_service_rest( 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" @@ -1065,6 +1061,7 @@ def test_set_proxy_header_rest( 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", @@ -1100,6 +1097,7 @@ def test_set_proxy_header_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_vpn_gateways.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_vpn_gateways.py index 332c8edd6da6..d04398cae6cf 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_vpn_gateways.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_vpn_gateways.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.target_vpn_gateways import TargetVpnGatewaysClient from google.cloud.compute_v1.services.target_vpn_gateways import pagers from google.cloud.compute_v1.services.target_vpn_gateways import transports -from google.cloud.compute_v1.services.target_vpn_gateways.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.target_vpn_gateways.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -608,6 +596,7 @@ def test_delete_rest( 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", @@ -643,6 +632,7 @@ def test_delete_rest( 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" @@ -838,6 +828,7 @@ def test_insert_rest( 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", @@ -873,6 +864,7 @@ def test_insert_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_url_maps.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_url_maps.py index f627743c346a..1cc472f9ce92 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_url_maps.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_url_maps.py @@ -36,7 +36,6 @@ from google.cloud.compute_v1.services.url_maps import UrlMapsClient from google.cloud.compute_v1.services.url_maps import pagers from google.cloud.compute_v1.services.url_maps import transports -from google.cloud.compute_v1.services.url_maps.transports.base import _API_CORE_VERSION from google.cloud.compute_v1.services.url_maps.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -45,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -57,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -571,6 +561,7 @@ def test_delete_rest(transport: str = "rest", request_type=compute.DeleteUrlMapR 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", @@ -606,6 +597,7 @@ def test_delete_rest(transport: str = "rest", request_type=compute.DeleteUrlMapR 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" @@ -825,6 +817,7 @@ def test_insert_rest(transport: str = "rest", request_type=compute.InsertUrlMapR 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", @@ -860,6 +853,7 @@ def test_insert_rest(transport: str = "rest", request_type=compute.InsertUrlMapR 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" @@ -956,6 +950,7 @@ def test_invalidate_cache_rest( 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", @@ -991,6 +986,7 @@ def test_invalidate_cache_rest( 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" @@ -1214,6 +1210,7 @@ def test_patch_rest(transport: str = "rest", request_type=compute.PatchUrlMapReq 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", @@ -1249,6 +1246,7 @@ def test_patch_rest(transport: str = "rest", request_type=compute.PatchUrlMapReq 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" @@ -1347,6 +1345,7 @@ def test_update_rest(transport: str = "rest", request_type=compute.UpdateUrlMapR 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", @@ -1382,6 +1381,7 @@ def test_update_rest(transport: str = "rest", request_type=compute.UpdateUrlMapR 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" 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 35b1b409223e..05b241ad4bc1 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 @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.vpn_gateways import VpnGatewaysClient from google.cloud.compute_v1.services.vpn_gateways import pagers from google.cloud.compute_v1.services.vpn_gateways import transports -from google.cloud.compute_v1.services.vpn_gateways.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.vpn_gateways.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -587,6 +575,7 @@ def test_delete_rest( 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", @@ -622,6 +611,7 @@ def test_delete_rest( 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" @@ -909,6 +899,7 @@ def test_insert_rest( 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", @@ -944,6 +935,7 @@ def test_insert_rest( 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" @@ -1184,6 +1176,7 @@ def test_set_labels_rest( 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", @@ -1219,6 +1212,7 @@ def test_set_labels_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_vpn_tunnels.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_vpn_tunnels.py index 732e5ed8f7b3..1e8687427562 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_vpn_tunnels.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_vpn_tunnels.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.vpn_tunnels import VpnTunnelsClient from google.cloud.compute_v1.services.vpn_tunnels import pagers from google.cloud.compute_v1.services.vpn_tunnels import transports -from google.cloud.compute_v1.services.vpn_tunnels.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.vpn_tunnels.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -582,6 +570,7 @@ def test_delete_rest( 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", @@ -617,6 +606,7 @@ def test_delete_rest( 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" @@ -832,6 +822,7 @@ def test_insert_rest( 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", @@ -867,6 +858,7 @@ def test_insert_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_zone_operations.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_zone_operations.py index 57ddbeb46932..d37181c35b95 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_zone_operations.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_zone_operations.py @@ -36,9 +36,6 @@ from google.cloud.compute_v1.services.zone_operations import ZoneOperationsClient from google.cloud.compute_v1.services.zone_operations import pagers from google.cloud.compute_v1.services.zone_operations import transports -from google.cloud.compute_v1.services.zone_operations.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.compute_v1.services.zone_operations.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -509,6 +497,7 @@ def test_get_rest( 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", @@ -544,6 +533,7 @@ def test_get_rest( 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" @@ -765,6 +755,7 @@ def test_wait_rest( 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", @@ -800,6 +791,7 @@ def test_wait_rest( 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" diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_zones.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_zones.py index c4436babc7ac..9f513c918fae 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_zones.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_zones.py @@ -36,15 +36,15 @@ from google.cloud.compute_v1.services.zones import ZonesClient from google.cloud.compute_v1.services.zones import pagers from google.cloud.compute_v1.services.zones import transports -from google.cloud.compute_v1.services.zones.transports.base import _API_CORE_VERSION from google.cloud.compute_v1.services.zones.transports.base import _GOOGLE_AUTH_VERSION from google.cloud.compute_v1.types import compute from google.oauth2 import service_account import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -55,16 +55,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -413,6 +403,7 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetZoneRequest): region="region_value", self_link="self_link_value", status=compute.Zone.Status.DOWN, + supports_pzs=True, ) # Wrap the value into a proper Response obj @@ -435,6 +426,7 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetZoneRequest): assert response.region == "region_value" assert response.self_link == "self_link_value" assert response.status == compute.Zone.Status.DOWN + assert response.supports_pzs is True def test_get_rest_from_dict():