From 61814609cdd8f9d26ba2b4f121e91dab4c565849 Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Mon, 10 May 2021 07:38:29 -0700 Subject: [PATCH] feat: Regenerate newest version of python-compute with field presence support (#49) --- .coveragerc | 1 - .github/header-checker-lint.yml | 2 +- .kokoro/release.sh | 4 +- .kokoro/release/common.cfg | 14 +- .pre-commit-config.yaml | 2 +- CONTRIBUTING.rst | 16 +- docs/_static/custom.css | 13 +- docs/compute_v1/accelerator_types.rst | 1 - docs/compute_v1/addresses.rst | 1 - docs/compute_v1/autoscalers.rst | 1 - docs/compute_v1/backend_buckets.rst | 1 - docs/compute_v1/backend_services.rst | 1 - docs/compute_v1/disk_types.rst | 1 - docs/compute_v1/disks.rst | 1 - docs/compute_v1/external_vpn_gateways.rst | 1 - docs/compute_v1/firewalls.rst | 1 - docs/compute_v1/forwarding_rules.rst | 1 - docs/compute_v1/global_addresses.rst | 1 - docs/compute_v1/global_forwarding_rules.rst | 1 - .../global_network_endpoint_groups.rst | 1 - docs/compute_v1/global_operations.rst | 1 - .../global_organization_operations.rst | 1 - docs/compute_v1/health_checks.rst | 1 - docs/compute_v1/images.rst | 1 - docs/compute_v1/instance_group_managers.rst | 1 - docs/compute_v1/instance_groups.rst | 1 - docs/compute_v1/instance_templates.rst | 1 - docs/compute_v1/instances.rst | 1 - docs/compute_v1/interconnect_attachments.rst | 1 - docs/compute_v1/interconnect_locations.rst | 1 - docs/compute_v1/interconnects.rst | 1 - docs/compute_v1/licenses.rst | 1 - docs/compute_v1/machine_types.rst | 1 - docs/compute_v1/network_endpoint_groups.rst | 1 - docs/compute_v1/networks.rst | 1 - docs/compute_v1/node_groups.rst | 1 - docs/compute_v1/node_templates.rst | 1 - docs/compute_v1/node_types.rst | 1 - docs/compute_v1/packet_mirrorings.rst | 1 - docs/compute_v1/projects.rst | 1 - docs/compute_v1/region_autoscalers.rst | 1 - docs/compute_v1/region_backend_services.rst | 1 - docs/compute_v1/region_commitments.rst | 1 - docs/compute_v1/region_disk_types.rst | 1 - docs/compute_v1/region_disks.rst | 1 - .../region_health_check_services.rst | 1 - docs/compute_v1/region_health_checks.rst | 1 - .../region_instance_group_managers.rst | 1 - docs/compute_v1/region_instance_groups.rst | 1 - .../region_network_endpoint_groups.rst | 1 - .../region_notification_endpoints.rst | 1 - docs/compute_v1/region_operations.rst | 1 - docs/compute_v1/region_ssl_certificates.rst | 1 - .../compute_v1/region_target_http_proxies.rst | 1 - .../region_target_https_proxies.rst | 1 - docs/compute_v1/region_url_maps.rst | 1 - docs/compute_v1/regions.rst | 1 - docs/compute_v1/reservations.rst | 1 - docs/compute_v1/resource_policies.rst | 1 - docs/compute_v1/routers.rst | 1 - docs/compute_v1/routes.rst | 1 - docs/compute_v1/security_policies.rst | 1 - docs/compute_v1/snapshots.rst | 1 - docs/compute_v1/ssl_certificates.rst | 1 - docs/compute_v1/ssl_policies.rst | 1 - docs/compute_v1/subnetworks.rst | 1 - docs/compute_v1/target_grpc_proxies.rst | 1 - docs/compute_v1/target_http_proxies.rst | 1 - docs/compute_v1/target_https_proxies.rst | 1 - docs/compute_v1/target_instances.rst | 1 - docs/compute_v1/target_pools.rst | 1 - docs/compute_v1/target_ssl_proxies.rst | 1 - docs/compute_v1/target_tcp_proxies.rst | 1 - docs/compute_v1/target_vpn_gateways.rst | 1 - docs/compute_v1/url_maps.rst | 1 - docs/compute_v1/vpn_gateways.rst | 1 - docs/compute_v1/vpn_tunnels.rst | 1 - docs/compute_v1/zone_operations.rst | 1 - docs/compute_v1/zones.rst | 1 - google/cloud/compute/__init__.py | 362 +- google/cloud/compute_v1/__init__.py | 109 +- google/cloud/compute_v1/gapic_metadata.json | 3331 ++++ google/cloud/compute_v1/services/__init__.py | 1 - .../services/accelerator_types/__init__.py | 2 - .../services/accelerator_types/client.py | 18 +- .../services/accelerator_types/pagers.py | 2 - .../accelerator_types/transports/__init__.py | 2 - .../accelerator_types/transports/base.py | 128 +- .../accelerator_types/transports/rest.py | 100 +- .../compute_v1/services/addresses/__init__.py | 2 - .../compute_v1/services/addresses/client.py | 24 +- .../compute_v1/services/addresses/pagers.py | 2 - .../services/addresses/transports/__init__.py | 2 - .../services/addresses/transports/base.py | 134 +- .../services/addresses/transports/rest.py | 127 +- .../services/autoscalers/__init__.py | 2 - .../compute_v1/services/autoscalers/client.py | 30 +- .../compute_v1/services/autoscalers/pagers.py | 2 - .../autoscalers/transports/__init__.py | 2 - .../services/autoscalers/transports/base.py | 140 +- .../services/autoscalers/transports/rest.py | 161 +- .../services/backend_buckets/__init__.py | 2 - .../services/backend_buckets/client.py | 33 +- .../services/backend_buckets/pagers.py | 2 - .../backend_buckets/transports/__init__.py | 2 - .../backend_buckets/transports/base.py | 144 +- .../backend_buckets/transports/rest.py | 157 +- .../services/backend_services/__init__.py | 2 - .../services/backend_services/client.py | 42 +- .../services/backend_services/pagers.py | 2 - .../backend_services/transports/__init__.py | 2 - .../backend_services/transports/base.py | 160 +- .../backend_services/transports/rest.py | 213 +- .../services/disk_types/__init__.py | 2 - .../compute_v1/services/disk_types/client.py | 18 +- .../compute_v1/services/disk_types/pagers.py | 2 - .../disk_types/transports/__init__.py | 2 - .../services/disk_types/transports/base.py | 125 +- .../services/disk_types/transports/rest.py | 97 +- .../compute_v1/services/disks/__init__.py | 2 - .../cloud/compute_v1/services/disks/client.py | 48 +- .../cloud/compute_v1/services/disks/pagers.py | 2 - .../services/disks/transports/__init__.py | 2 - .../services/disks/transports/base.py | 169 +- .../services/disks/transports/rest.py | 237 +- .../external_vpn_gateways/__init__.py | 2 - .../services/external_vpn_gateways/client.py | 27 +- .../services/external_vpn_gateways/pagers.py | 2 - .../transports/__init__.py | 2 - .../external_vpn_gateways/transports/base.py | 142 +- .../external_vpn_gateways/transports/rest.py | 112 +- .../compute_v1/services/firewalls/__init__.py | 2 - .../compute_v1/services/firewalls/client.py | 27 +- .../compute_v1/services/firewalls/pagers.py | 2 - .../services/firewalls/transports/__init__.py | 2 - .../services/firewalls/transports/base.py | 134 +- .../services/firewalls/transports/rest.py | 124 +- .../services/forwarding_rules/__init__.py | 2 - .../services/forwarding_rules/client.py | 30 +- .../services/forwarding_rules/pagers.py | 2 - .../forwarding_rules/transports/__init__.py | 2 - .../forwarding_rules/transports/base.py | 142 +- .../forwarding_rules/transports/rest.py | 158 +- .../services/global_addresses/__init__.py | 2 - .../services/global_addresses/client.py | 21 +- .../services/global_addresses/pagers.py | 2 - .../global_addresses/transports/__init__.py | 2 - .../global_addresses/transports/base.py | 126 +- .../global_addresses/transports/rest.py | 96 +- .../global_forwarding_rules/__init__.py | 2 - .../global_forwarding_rules/client.py | 27 +- .../global_forwarding_rules/pagers.py | 2 - .../transports/__init__.py | 2 - .../transports/base.py | 136 +- .../transports/rest.py | 124 +- .../__init__.py | 2 - .../global_network_endpoint_groups/client.py | 30 +- .../global_network_endpoint_groups/pagers.py | 2 - .../transports/__init__.py | 2 - .../transports/base.py | 144 +- .../transports/rest.py | 176 +- .../services/global_operations/__init__.py | 2 - .../services/global_operations/client.py | 24 +- .../services/global_operations/pagers.py | 2 - .../global_operations/transports/__init__.py | 2 - .../global_operations/transports/base.py | 135 +- .../global_operations/transports/rest.py | 120 +- .../__init__.py | 2 - .../global_organization_operations/client.py | 17 +- .../global_organization_operations/pagers.py | 2 - .../transports/__init__.py | 2 - .../transports/base.py | 124 +- .../transports/rest.py | 94 +- .../services/health_checks/__init__.py | 2 - .../services/health_checks/client.py | 30 +- .../services/health_checks/pagers.py | 2 - .../health_checks/transports/__init__.py | 2 - .../services/health_checks/transports/base.py | 142 +- .../services/health_checks/transports/rest.py | 155 +- .../compute_v1/services/images/__init__.py | 2 - .../compute_v1/services/images/client.py | 42 +- .../compute_v1/services/images/pagers.py | 2 - .../services/images/transports/__init__.py | 2 - .../services/images/transports/base.py | 158 +- .../services/images/transports/rest.py | 179 +- .../instance_group_managers/__init__.py | 2 - .../instance_group_managers/client.py | 69 +- .../instance_group_managers/pagers.py | 2 - .../transports/__init__.py | 2 - .../transports/base.py | 202 +- .../transports/rest.py | 408 +- .../services/instance_groups/__init__.py | 2 - .../services/instance_groups/client.py | 36 +- .../services/instance_groups/pagers.py | 2 - .../instance_groups/transports/__init__.py | 2 - .../instance_groups/transports/base.py | 152 +- .../instance_groups/transports/rest.py | 198 +- .../services/instance_templates/__init__.py | 2 - .../services/instance_templates/client.py | 30 +- .../services/instance_templates/pagers.py | 2 - .../instance_templates/transports/__init__.py | 2 - .../instance_templates/transports/base.py | 145 +- .../instance_templates/transports/rest.py | 133 +- .../compute_v1/services/instances/__init__.py | 2 - .../compute_v1/services/instances/client.py | 129 +- .../compute_v1/services/instances/pagers.py | 2 - .../services/instances/transports/__init__.py | 2 - .../services/instances/transports/base.py | 285 +- .../services/instances/transports/rest.py | 682 +- .../interconnect_attachments/__init__.py | 2 - .../interconnect_attachments/client.py | 27 +- .../interconnect_attachments/pagers.py | 2 - .../transports/__init__.py | 2 - .../transports/base.py | 141 +- .../transports/rest.py | 150 +- .../interconnect_locations/__init__.py | 2 - .../services/interconnect_locations/client.py | 15 +- .../services/interconnect_locations/pagers.py | 2 - .../transports/__init__.py | 2 - .../interconnect_locations/transports/base.py | 122 +- .../interconnect_locations/transports/rest.py | 66 +- .../services/interconnects/__init__.py | 2 - .../services/interconnects/client.py | 27 +- .../services/interconnects/pagers.py | 2 - .../interconnects/transports/__init__.py | 2 - .../services/interconnects/transports/base.py | 138 +- .../services/interconnects/transports/rest.py | 120 +- .../services/license_codes/__init__.py | 2 - .../services/license_codes/client.py | 15 +- .../license_codes/transports/__init__.py | 2 - .../services/license_codes/transports/base.py | 121 +- .../services/license_codes/transports/rest.py | 46 +- .../compute_v1/services/licenses/__init__.py | 2 - .../compute_v1/services/licenses/client.py | 30 +- .../compute_v1/services/licenses/pagers.py | 2 - .../services/licenses/transports/__init__.py | 2 - .../services/licenses/transports/base.py | 144 +- .../services/licenses/transports/rest.py | 142 +- .../services/machine_types/__init__.py | 2 - .../services/machine_types/client.py | 18 +- .../services/machine_types/pagers.py | 2 - .../machine_types/transports/__init__.py | 2 - .../services/machine_types/transports/base.py | 126 +- .../services/machine_types/transports/rest.py | 97 +- .../network_endpoint_groups/__init__.py | 2 - .../network_endpoint_groups/client.py | 36 +- .../network_endpoint_groups/pagers.py | 2 - .../transports/__init__.py | 2 - .../transports/base.py | 157 +- .../transports/rest.py | 210 +- .../compute_v1/services/networks/__init__.py | 2 - .../compute_v1/services/networks/client.py | 39 +- .../compute_v1/services/networks/pagers.py | 2 - .../services/networks/transports/__init__.py | 2 - .../services/networks/transports/base.py | 153 +- .../services/networks/transports/rest.py | 205 +- .../services/node_groups/__init__.py | 2 - .../compute_v1/services/node_groups/client.py | 48 +- .../compute_v1/services/node_groups/pagers.py | 2 - .../node_groups/transports/__init__.py | 2 - .../services/node_groups/transports/base.py | 170 +- .../services/node_groups/transports/rest.py | 251 +- .../services/node_templates/__init__.py | 2 - .../services/node_templates/client.py | 33 +- .../services/node_templates/pagers.py | 2 - .../node_templates/transports/__init__.py | 2 - .../node_templates/transports/base.py | 149 +- .../node_templates/transports/rest.py | 164 +- .../services/node_types/__init__.py | 2 - .../compute_v1/services/node_types/client.py | 18 +- .../compute_v1/services/node_types/pagers.py | 2 - .../node_types/transports/__init__.py | 2 - .../services/node_types/transports/base.py | 125 +- .../services/node_types/transports/rest.py | 97 +- .../services/packet_mirrorings/__init__.py | 2 - .../services/packet_mirrorings/client.py | 30 +- .../services/packet_mirrorings/pagers.py | 2 - .../packet_mirrorings/transports/__init__.py | 2 - .../packet_mirrorings/transports/base.py | 147 +- .../packet_mirrorings/transports/rest.py | 152 +- .../compute_v1/services/projects/__init__.py | 2 - .../compute_v1/services/projects/client.py | 48 +- .../compute_v1/services/projects/pagers.py | 2 - .../services/projects/transports/__init__.py | 2 - .../services/projects/transports/base.py | 166 +- .../services/projects/transports/rest.py | 232 +- .../services/region_autoscalers/__init__.py | 2 - .../services/region_autoscalers/client.py | 27 +- .../services/region_autoscalers/pagers.py | 2 - .../region_autoscalers/transports/__init__.py | 2 - .../region_autoscalers/transports/base.py | 136 +- .../region_autoscalers/transports/rest.py | 130 +- .../region_backend_services/__init__.py | 2 - .../region_backend_services/client.py | 30 +- .../region_backend_services/pagers.py | 2 - .../transports/__init__.py | 2 - .../transports/base.py | 142 +- .../transports/rest.py | 132 +- .../services/region_commitments/__init__.py | 2 - .../services/region_commitments/client.py | 21 +- .../services/region_commitments/pagers.py | 2 - .../region_commitments/transports/__init__.py | 2 - .../region_commitments/transports/base.py | 128 +- .../region_commitments/transports/rest.py | 114 +- .../services/region_disk_types/__init__.py | 2 - .../services/region_disk_types/client.py | 15 +- .../services/region_disk_types/pagers.py | 2 - .../region_disk_types/transports/__init__.py | 2 - .../region_disk_types/transports/base.py | 120 +- .../region_disk_types/transports/rest.py | 66 +- .../services/region_disks/__init__.py | 2 - .../services/region_disks/client.py | 45 +- .../services/region_disks/pagers.py | 2 - .../region_disks/transports/__init__.py | 2 - .../services/region_disks/transports/base.py | 162 +- .../services/region_disks/transports/rest.py | 206 +- .../region_health_check_services/__init__.py | 2 - .../region_health_check_services/client.py | 24 +- .../region_health_check_services/pagers.py | 2 - .../transports/__init__.py | 2 - .../transports/base.py | 135 +- .../transports/rest.py | 113 +- .../services/region_health_checks/__init__.py | 2 - .../services/region_health_checks/client.py | 27 +- .../services/region_health_checks/pagers.py | 2 - .../transports/__init__.py | 2 - .../region_health_checks/transports/base.py | 136 +- .../region_health_checks/transports/rest.py | 124 +- .../__init__.py | 2 - .../region_instance_group_managers/client.py | 66 +- .../region_instance_group_managers/pagers.py | 2 - .../transports/__init__.py | 2 - .../transports/base.py | 198 +- .../transports/rest.py | 401 +- .../region_instance_groups/__init__.py | 2 - .../services/region_instance_groups/client.py | 21 +- .../services/region_instance_groups/pagers.py | 2 - .../transports/__init__.py | 2 - .../region_instance_groups/transports/base.py | 131 +- .../region_instance_groups/transports/rest.py | 109 +- .../__init__.py | 2 - .../region_network_endpoint_groups/client.py | 21 +- .../region_network_endpoint_groups/pagers.py | 2 - .../transports/__init__.py | 2 - .../transports/base.py | 130 +- .../transports/rest.py | 99 +- .../region_notification_endpoints/__init__.py | 2 - .../region_notification_endpoints/client.py | 21 +- .../region_notification_endpoints/pagers.py | 2 - .../transports/__init__.py | 2 - .../transports/base.py | 130 +- .../transports/rest.py | 99 +- .../services/region_operations/__init__.py | 2 - .../services/region_operations/client.py | 21 +- .../services/region_operations/pagers.py | 2 - .../region_operations/transports/__init__.py | 2 - .../region_operations/transports/base.py | 128 +- .../region_operations/transports/rest.py | 86 +- .../region_ssl_certificates/__init__.py | 2 - .../region_ssl_certificates/client.py | 21 +- .../region_ssl_certificates/pagers.py | 2 - .../transports/__init__.py | 2 - .../transports/base.py | 128 +- .../transports/rest.py | 96 +- .../region_target_http_proxies/__init__.py | 2 - .../region_target_http_proxies/client.py | 24 +- .../region_target_http_proxies/pagers.py | 2 - .../transports/__init__.py | 2 - .../transports/base.py | 134 +- .../transports/rest.py | 110 +- .../region_target_https_proxies/__init__.py | 2 - .../region_target_https_proxies/client.py | 27 +- .../region_target_https_proxies/pagers.py | 2 - .../transports/__init__.py | 2 - .../transports/base.py | 138 +- .../transports/rest.py | 130 +- .../services/region_url_maps/__init__.py | 2 - .../services/region_url_maps/client.py | 30 +- .../services/region_url_maps/pagers.py | 2 - .../region_url_maps/transports/__init__.py | 2 - .../region_url_maps/transports/base.py | 141 +- .../region_url_maps/transports/rest.py | 132 +- .../compute_v1/services/regions/__init__.py | 2 - .../compute_v1/services/regions/client.py | 15 +- .../compute_v1/services/regions/pagers.py | 2 - .../services/regions/transports/__init__.py | 2 - .../services/regions/transports/base.py | 119 +- .../services/regions/transports/rest.py | 66 +- .../services/reservations/__init__.py | 2 - .../services/reservations/client.py | 36 +- .../services/reservations/pagers.py | 2 - .../reservations/transports/__init__.py | 2 - .../services/reservations/transports/base.py | 153 +- .../services/reservations/transports/rest.py | 178 +- .../services/resource_policies/__init__.py | 2 - .../services/resource_policies/client.py | 33 +- .../services/resource_policies/pagers.py | 2 - .../resource_policies/transports/__init__.py | 2 - .../resource_policies/transports/base.py | 149 +- .../resource_policies/transports/rest.py | 167 +- .../compute_v1/services/routers/__init__.py | 2 - .../compute_v1/services/routers/client.py | 39 +- .../compute_v1/services/routers/pagers.py | 2 - .../services/routers/transports/__init__.py | 2 - .../services/routers/transports/base.py | 160 +- .../services/routers/transports/rest.py | 201 +- .../compute_v1/services/routes/__init__.py | 2 - .../compute_v1/services/routes/client.py | 21 +- .../compute_v1/services/routes/pagers.py | 2 - .../services/routes/transports/__init__.py | 2 - .../services/routes/transports/base.py | 127 +- .../services/routes/transports/rest.py | 96 +- .../services/security_policies/__init__.py | 2 - .../services/security_policies/client.py | 39 +- .../services/security_policies/pagers.py | 2 - .../security_policies/transports/__init__.py | 2 - .../security_policies/transports/base.py | 158 +- .../security_policies/transports/rest.py | 207 +- .../compute_v1/services/snapshots/__init__.py | 2 - .../compute_v1/services/snapshots/client.py | 30 +- .../compute_v1/services/snapshots/pagers.py | 2 - .../services/snapshots/transports/__init__.py | 2 - .../services/snapshots/transports/base.py | 141 +- .../services/snapshots/transports/rest.py | 127 +- .../services/ssl_certificates/__init__.py | 2 - .../services/ssl_certificates/client.py | 24 +- .../services/ssl_certificates/pagers.py | 2 - .../ssl_certificates/transports/__init__.py | 2 - .../ssl_certificates/transports/base.py | 134 +- .../ssl_certificates/transports/rest.py | 130 +- .../services/ssl_policies/__init__.py | 2 - .../services/ssl_policies/client.py | 27 +- .../services/ssl_policies/pagers.py | 2 - .../ssl_policies/transports/__init__.py | 2 - .../services/ssl_policies/transports/base.py | 138 +- .../services/ssl_policies/transports/rest.py | 141 +- .../services/subnetworks/__init__.py | 2 - .../compute_v1/services/subnetworks/client.py | 45 +- .../compute_v1/services/subnetworks/pagers.py | 2 - .../subnetworks/transports/__init__.py | 2 - .../services/subnetworks/transports/base.py | 165 +- .../services/subnetworks/transports/rest.py | 237 +- .../services/target_grpc_proxies/__init__.py | 2 - .../services/target_grpc_proxies/client.py | 24 +- .../services/target_grpc_proxies/pagers.py | 2 - .../transports/__init__.py | 2 - .../target_grpc_proxies/transports/base.py | 134 +- .../target_grpc_proxies/transports/rest.py | 110 +- .../services/target_http_proxies/__init__.py | 2 - .../services/target_http_proxies/client.py | 30 +- .../services/target_http_proxies/pagers.py | 2 - .../transports/__init__.py | 2 - .../target_http_proxies/transports/base.py | 144 +- .../target_http_proxies/transports/rest.py | 158 +- .../services/target_https_proxies/__init__.py | 2 - .../services/target_https_proxies/client.py | 36 +- .../services/target_https_proxies/pagers.py | 2 - .../transports/__init__.py | 2 - .../target_https_proxies/transports/base.py | 152 +- .../target_https_proxies/transports/rest.py | 189 +- .../services/target_instances/__init__.py | 2 - .../services/target_instances/client.py | 24 +- .../services/target_instances/pagers.py | 2 - .../target_instances/transports/__init__.py | 2 - .../target_instances/transports/base.py | 134 +- .../target_instances/transports/rest.py | 130 +- .../services/target_pools/__init__.py | 2 - .../services/target_pools/client.py | 42 +- .../services/target_pools/pagers.py | 2 - .../target_pools/transports/__init__.py | 2 - .../services/target_pools/transports/base.py | 158 +- .../services/target_pools/transports/rest.py | 208 +- .../services/target_ssl_proxies/__init__.py | 2 - .../services/target_ssl_proxies/client.py | 33 +- .../services/target_ssl_proxies/pagers.py | 2 - .../target_ssl_proxies/transports/__init__.py | 2 - .../target_ssl_proxies/transports/base.py | 144 +- .../target_ssl_proxies/transports/rest.py | 152 +- .../services/target_tcp_proxies/__init__.py | 2 - .../services/target_tcp_proxies/client.py | 27 +- .../services/target_tcp_proxies/pagers.py | 2 - .../target_tcp_proxies/transports/__init__.py | 2 - .../target_tcp_proxies/transports/base.py | 136 +- .../target_tcp_proxies/transports/rest.py | 124 +- .../services/target_vpn_gateways/__init__.py | 2 - .../services/target_vpn_gateways/client.py | 24 +- .../services/target_vpn_gateways/pagers.py | 2 - .../transports/__init__.py | 2 - .../target_vpn_gateways/transports/base.py | 136 +- .../target_vpn_gateways/transports/rest.py | 130 +- .../compute_v1/services/url_maps/__init__.py | 2 - .../compute_v1/services/url_maps/client.py | 36 +- .../compute_v1/services/url_maps/pagers.py | 2 - .../services/url_maps/transports/__init__.py | 2 - .../services/url_maps/transports/base.py | 153 +- .../services/url_maps/transports/rest.py | 177 +- .../services/vpn_gateways/__init__.py | 2 - .../services/vpn_gateways/client.py | 33 +- .../services/vpn_gateways/pagers.py | 2 - .../vpn_gateways/transports/__init__.py | 2 - .../services/vpn_gateways/transports/base.py | 149 +- .../services/vpn_gateways/transports/rest.py | 159 +- .../services/vpn_tunnels/__init__.py | 2 - .../compute_v1/services/vpn_tunnels/client.py | 24 +- .../compute_v1/services/vpn_tunnels/pagers.py | 2 - .../vpn_tunnels/transports/__init__.py | 2 - .../services/vpn_tunnels/transports/base.py | 133 +- .../services/vpn_tunnels/transports/rest.py | 127 +- .../services/zone_operations/__init__.py | 2 - .../services/zone_operations/client.py | 21 +- .../services/zone_operations/pagers.py | 2 - .../zone_operations/transports/__init__.py | 2 - .../zone_operations/transports/base.py | 128 +- .../zone_operations/transports/rest.py | 86 +- .../compute_v1/services/zones/__init__.py | 2 - .../cloud/compute_v1/services/zones/client.py | 15 +- .../cloud/compute_v1/services/zones/pagers.py | 2 - .../services/zones/transports/__init__.py | 2 - .../services/zones/transports/base.py | 120 +- .../services/zones/transports/rest.py | 66 +- google/cloud/compute_v1/types/__init__.py | 3478 ++-- google/cloud/compute_v1/types/compute.py | 15169 ++++++---------- noxfile.py | 16 +- renovate.json | 5 +- synth.metadata | 22 +- tests/__init__.py | 15 + tests/unit/__init__.py | 15 + tests/unit/gapic/__init__.py | 15 + tests/unit/gapic/compute_v1/__init__.py | 1 - .../compute_v1/test_accelerator_types.py | 179 +- tests/unit/gapic/compute_v1/test_addresses.py | 200 +- .../unit/gapic/compute_v1/test_autoscalers.py | 228 +- .../gapic/compute_v1/test_backend_buckets.py | 235 +- .../gapic/compute_v1/test_backend_services.py | 276 +- .../unit/gapic/compute_v1/test_disk_types.py | 179 +- tests/unit/gapic/compute_v1/test_disks.py | 310 +- .../compute_v1/test_external_vpn_gateways.py | 235 +- tests/unit/gapic/compute_v1/test_firewalls.py | 208 +- .../gapic/compute_v1/test_forwarding_rules.py | 233 +- .../gapic/compute_v1/test_global_addresses.py | 183 +- .../test_global_forwarding_rules.py | 212 +- .../test_global_network_endpoint_groups.py | 225 +- .../compute_v1/test_global_operations.py | 197 +- .../test_global_organization_operations.py | 168 +- .../gapic/compute_v1/test_health_checks.py | 224 +- tests/unit/gapic/compute_v1/test_images.py | 268 +- .../test_instance_group_managers.py | 420 +- .../gapic/compute_v1/test_instance_groups.py | 263 +- .../compute_v1/test_instance_templates.py | 222 +- tests/unit/gapic/compute_v1/test_instances.py | 680 +- .../test_interconnect_attachments.py | 217 +- .../compute_v1/test_interconnect_locations.py | 162 +- .../gapic/compute_v1/test_interconnects.py | 208 +- .../gapic/compute_v1/test_license_codes.py | 161 +- tests/unit/gapic/compute_v1/test_licenses.py | 222 +- .../gapic/compute_v1/test_machine_types.py | 180 +- .../test_network_endpoint_groups.py | 263 +- tests/unit/gapic/compute_v1/test_networks.py | 261 +- .../unit/gapic/compute_v1/test_node_groups.py | 318 +- .../gapic/compute_v1/test_node_templates.py | 244 +- .../unit/gapic/compute_v1/test_node_types.py | 179 +- .../compute_v1/test_packet_mirrorings.py | 230 +- tests/unit/gapic/compute_v1/test_projects.py | 288 +- .../compute_v1/test_region_autoscalers.py | 213 +- .../test_region_backend_services.py | 230 +- .../compute_v1/test_region_commitments.py | 190 +- .../compute_v1/test_region_disk_types.py | 164 +- .../gapic/compute_v1/test_region_disks.py | 299 +- .../test_region_health_check_services.py | 201 +- .../compute_v1/test_region_health_checks.py | 241 +- .../test_region_instance_group_managers.py | 405 +- .../compute_v1/test_region_instance_groups.py | 215 +- .../test_region_network_endpoint_groups.py | 187 +- .../test_region_notification_endpoints.py | 187 +- .../compute_v1/test_region_operations.py | 186 +- .../test_region_ssl_certificates.py | 187 +- .../test_region_target_http_proxies.py | 202 +- .../test_region_target_https_proxies.py | 216 +- .../gapic/compute_v1/test_region_url_maps.py | 229 +- tests/unit/gapic/compute_v1/test_regions.py | 160 +- .../gapic/compute_v1/test_reservations.py | 259 +- .../compute_v1/test_resource_policies.py | 244 +- tests/unit/gapic/compute_v1/test_routers.py | 271 +- tests/unit/gapic/compute_v1/test_routes.py | 179 +- .../compute_v1/test_security_policies.py | 255 +- tests/unit/gapic/compute_v1/test_snapshots.py | 222 +- .../gapic/compute_v1/test_ssl_certificates.py | 198 +- .../gapic/compute_v1/test_ssl_policies.py | 206 +- .../unit/gapic/compute_v1/test_subnetworks.py | 303 +- .../compute_v1/test_target_grpc_proxies.py | 197 +- .../compute_v1/test_target_http_proxies.py | 225 +- .../compute_v1/test_target_https_proxies.py | 291 +- .../gapic/compute_v1/test_target_instances.py | 202 +- .../gapic/compute_v1/test_target_pools.py | 286 +- .../compute_v1/test_target_ssl_proxies.py | 235 +- .../compute_v1/test_target_tcp_proxies.py | 209 +- .../compute_v1/test_target_vpn_gateways.py | 202 +- tests/unit/gapic/compute_v1/test_url_maps.py | 248 +- .../gapic/compute_v1/test_vpn_gateways.py | 242 +- .../unit/gapic/compute_v1/test_vpn_tunnels.py | 202 +- .../gapic/compute_v1/test_zone_operations.py | 186 +- tests/unit/gapic/compute_v1/test_zones.py | 158 +- 602 files changed, 33998 insertions(+), 30170 deletions(-) create mode 100644 google/cloud/compute_v1/gapic_metadata.json create mode 100644 tests/__init__.py create mode 100644 tests/unit/__init__.py create mode 100644 tests/unit/gapic/__init__.py diff --git a/.coveragerc b/.coveragerc index dae07a2a5..3487bb298 100644 --- a/.coveragerc +++ b/.coveragerc @@ -2,7 +2,6 @@ branch = True [report] -fail_under = 100 show_missing = True omit = google/cloud/compute/__init__.py diff --git a/.github/header-checker-lint.yml b/.github/header-checker-lint.yml index fc281c05b..6fe78aa79 100644 --- a/.github/header-checker-lint.yml +++ b/.github/header-checker-lint.yml @@ -1,6 +1,6 @@ {"allowedCopyrightHolders": ["Google LLC"], "allowedLicenses": ["Apache-2.0", "MIT", "BSD-3"], - "ignoreFiles": ["**/requirements.txt", "**/requirements-test.txt"], + "ignoreFiles": ["**/requirements.txt", "**/requirements-test.txt", "**/__init__.py", "samples/**/constraints.txt", "samples/**/constraints-test.txt"], "sourceFileExtensions": [ "ts", "js", diff --git a/.kokoro/release.sh b/.kokoro/release.sh index 43ee7c428..ef70e9bec 100755 --- a/.kokoro/release.sh +++ b/.kokoro/release.sh @@ -26,7 +26,7 @@ python3 -m pip install --upgrade twine wheel setuptools export PYTHONUNBUFFERED=1 # Move into the package, build the distribution and upload. -TWINE_PASSWORD=$(cat "${KOKORO_KEYSTORE_DIR}/73713_google_cloud_pypi_password") +TWINE_PASSWORD=$(cat "${KOKORO_GFILE_DIR}/secret_manager/google-cloud-pypi-token") cd github/python-compute python3 setup.py sdist bdist_wheel -twine upload --username gcloudpypi --password "${TWINE_PASSWORD}" dist/* +twine upload --username __token__ --password "${TWINE_PASSWORD}" dist/* diff --git a/.kokoro/release/common.cfg b/.kokoro/release/common.cfg index 9f1a09da1..b36946fd2 100644 --- a/.kokoro/release/common.cfg +++ b/.kokoro/release/common.cfg @@ -23,18 +23,8 @@ env_vars: { value: "github/python-compute/.kokoro/release.sh" } -# Fetch PyPI password -before_action { - fetch_keystore { - keystore_resource { - keystore_config_id: 73713 - keyname: "google_cloud_pypi_password" - } - } -} - # Tokens needed to report release status back to GitHub env_vars: { key: "SECRET_MANAGER_KEYS" - value: "releasetool-publish-reporter-app,releasetool-publish-reporter-googleapis-installation,releasetool-publish-reporter-pem" -} \ No newline at end of file + value: "releasetool-publish-reporter-app,releasetool-publish-reporter-googleapis-installation,releasetool-publish-reporter-pem,google-cloud-pypi-token" +} diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 8912e9b5d..1bbd78783 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -26,6 +26,6 @@ repos: hooks: - id: black - repo: https://gitlab.com/pycqa/flake8 - rev: 3.9.0 + rev: 3.9.1 hooks: - id: flake8 diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 7eae3021e..afc0cdfb1 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -160,21 +160,7 @@ Running System Tests auth settings and change some configuration in your project to run all the tests. -- System tests will be run against an actual project and - so you'll need to provide some environment variables to facilitate - authentication to your project: - - - ``GOOGLE_APPLICATION_CREDENTIALS``: The path to a JSON key file; - Such a file can be downloaded directly from the developer's console by clicking - "Generate new JSON key". See private key - `docs `__ - for more details. - -- Once you have downloaded your json keys, set the environment variable - ``GOOGLE_APPLICATION_CREDENTIALS`` to the absolute path of the json file:: - - $ export GOOGLE_APPLICATION_CREDENTIALS="/Users//path/to/app_credentials.json" - +- System tests will be run against an actual project. You should use local credentials from gcloud when possible. See `Best practices for application authentication `__. Some tests require a service account. For those tests see `Authenticating as a service account `__. ************* Test Coverage diff --git a/docs/_static/custom.css b/docs/_static/custom.css index bcd37bbd3..b0a295464 100644 --- a/docs/_static/custom.css +++ b/docs/_static/custom.css @@ -1,9 +1,20 @@ div#python2-eol { border-color: red; border-width: medium; -} +} /* Ensure minimum width for 'Parameters' / 'Returns' column */ dl.field-list > dt { min-width: 100px } + +/* Insert space between methods for readability */ +dl.method { + padding-top: 10px; + padding-bottom: 10px +} + +/* Insert empty space between classes */ +dl.class { + padding-bottom: 50px +} diff --git a/docs/compute_v1/accelerator_types.rst b/docs/compute_v1/accelerator_types.rst index 5eb8673b0..f865b6225 100644 --- a/docs/compute_v1/accelerator_types.rst +++ b/docs/compute_v1/accelerator_types.rst @@ -5,7 +5,6 @@ AcceleratorTypes :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.accelerator_types.pagers :members: :inherited-members: diff --git a/docs/compute_v1/addresses.rst b/docs/compute_v1/addresses.rst index 0579da503..cb88b008e 100644 --- a/docs/compute_v1/addresses.rst +++ b/docs/compute_v1/addresses.rst @@ -5,7 +5,6 @@ Addresses :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.addresses.pagers :members: :inherited-members: diff --git a/docs/compute_v1/autoscalers.rst b/docs/compute_v1/autoscalers.rst index 7e7acb14c..59e44e672 100644 --- a/docs/compute_v1/autoscalers.rst +++ b/docs/compute_v1/autoscalers.rst @@ -5,7 +5,6 @@ Autoscalers :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.autoscalers.pagers :members: :inherited-members: diff --git a/docs/compute_v1/backend_buckets.rst b/docs/compute_v1/backend_buckets.rst index 6b71dfbb6..2a8d5210c 100644 --- a/docs/compute_v1/backend_buckets.rst +++ b/docs/compute_v1/backend_buckets.rst @@ -5,7 +5,6 @@ BackendBuckets :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.backend_buckets.pagers :members: :inherited-members: diff --git a/docs/compute_v1/backend_services.rst b/docs/compute_v1/backend_services.rst index 9d387953b..80a321599 100644 --- a/docs/compute_v1/backend_services.rst +++ b/docs/compute_v1/backend_services.rst @@ -5,7 +5,6 @@ BackendServices :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.backend_services.pagers :members: :inherited-members: diff --git a/docs/compute_v1/disk_types.rst b/docs/compute_v1/disk_types.rst index a4853da43..be3cfb6c3 100644 --- a/docs/compute_v1/disk_types.rst +++ b/docs/compute_v1/disk_types.rst @@ -5,7 +5,6 @@ DiskTypes :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.disk_types.pagers :members: :inherited-members: diff --git a/docs/compute_v1/disks.rst b/docs/compute_v1/disks.rst index 154429e8a..898c491c2 100644 --- a/docs/compute_v1/disks.rst +++ b/docs/compute_v1/disks.rst @@ -5,7 +5,6 @@ Disks :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.disks.pagers :members: :inherited-members: diff --git a/docs/compute_v1/external_vpn_gateways.rst b/docs/compute_v1/external_vpn_gateways.rst index ff28cc2ea..804891507 100644 --- a/docs/compute_v1/external_vpn_gateways.rst +++ b/docs/compute_v1/external_vpn_gateways.rst @@ -5,7 +5,6 @@ ExternalVpnGateways :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.external_vpn_gateways.pagers :members: :inherited-members: diff --git a/docs/compute_v1/firewalls.rst b/docs/compute_v1/firewalls.rst index ef6049d7c..24448c98b 100644 --- a/docs/compute_v1/firewalls.rst +++ b/docs/compute_v1/firewalls.rst @@ -5,7 +5,6 @@ Firewalls :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.firewalls.pagers :members: :inherited-members: diff --git a/docs/compute_v1/forwarding_rules.rst b/docs/compute_v1/forwarding_rules.rst index 08b543649..6a808d3fc 100644 --- a/docs/compute_v1/forwarding_rules.rst +++ b/docs/compute_v1/forwarding_rules.rst @@ -5,7 +5,6 @@ ForwardingRules :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.forwarding_rules.pagers :members: :inherited-members: diff --git a/docs/compute_v1/global_addresses.rst b/docs/compute_v1/global_addresses.rst index 8755a1855..d106676a0 100644 --- a/docs/compute_v1/global_addresses.rst +++ b/docs/compute_v1/global_addresses.rst @@ -5,7 +5,6 @@ GlobalAddresses :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.global_addresses.pagers :members: :inherited-members: diff --git a/docs/compute_v1/global_forwarding_rules.rst b/docs/compute_v1/global_forwarding_rules.rst index a54eb4b0a..710d24590 100644 --- a/docs/compute_v1/global_forwarding_rules.rst +++ b/docs/compute_v1/global_forwarding_rules.rst @@ -5,7 +5,6 @@ GlobalForwardingRules :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.global_forwarding_rules.pagers :members: :inherited-members: diff --git a/docs/compute_v1/global_network_endpoint_groups.rst b/docs/compute_v1/global_network_endpoint_groups.rst index 430a202f2..a13a31a67 100644 --- a/docs/compute_v1/global_network_endpoint_groups.rst +++ b/docs/compute_v1/global_network_endpoint_groups.rst @@ -5,7 +5,6 @@ GlobalNetworkEndpointGroups :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.global_network_endpoint_groups.pagers :members: :inherited-members: diff --git a/docs/compute_v1/global_operations.rst b/docs/compute_v1/global_operations.rst index 6c4cef346..94450a7ee 100644 --- a/docs/compute_v1/global_operations.rst +++ b/docs/compute_v1/global_operations.rst @@ -5,7 +5,6 @@ GlobalOperations :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.global_operations.pagers :members: :inherited-members: diff --git a/docs/compute_v1/global_organization_operations.rst b/docs/compute_v1/global_organization_operations.rst index 2fb034517..d4e514357 100644 --- a/docs/compute_v1/global_organization_operations.rst +++ b/docs/compute_v1/global_organization_operations.rst @@ -5,7 +5,6 @@ GlobalOrganizationOperations :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.global_organization_operations.pagers :members: :inherited-members: diff --git a/docs/compute_v1/health_checks.rst b/docs/compute_v1/health_checks.rst index 68e2841a2..4f6fbf590 100644 --- a/docs/compute_v1/health_checks.rst +++ b/docs/compute_v1/health_checks.rst @@ -5,7 +5,6 @@ HealthChecks :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.health_checks.pagers :members: :inherited-members: diff --git a/docs/compute_v1/images.rst b/docs/compute_v1/images.rst index 318fd8073..a128da7e5 100644 --- a/docs/compute_v1/images.rst +++ b/docs/compute_v1/images.rst @@ -5,7 +5,6 @@ Images :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.images.pagers :members: :inherited-members: diff --git a/docs/compute_v1/instance_group_managers.rst b/docs/compute_v1/instance_group_managers.rst index 0010acecf..eec48ff06 100644 --- a/docs/compute_v1/instance_group_managers.rst +++ b/docs/compute_v1/instance_group_managers.rst @@ -5,7 +5,6 @@ InstanceGroupManagers :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.instance_group_managers.pagers :members: :inherited-members: diff --git a/docs/compute_v1/instance_groups.rst b/docs/compute_v1/instance_groups.rst index 094150adb..30ccb2bcb 100644 --- a/docs/compute_v1/instance_groups.rst +++ b/docs/compute_v1/instance_groups.rst @@ -5,7 +5,6 @@ InstanceGroups :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.instance_groups.pagers :members: :inherited-members: diff --git a/docs/compute_v1/instance_templates.rst b/docs/compute_v1/instance_templates.rst index 35a6f2f09..1e04745dc 100644 --- a/docs/compute_v1/instance_templates.rst +++ b/docs/compute_v1/instance_templates.rst @@ -5,7 +5,6 @@ InstanceTemplates :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.instance_templates.pagers :members: :inherited-members: diff --git a/docs/compute_v1/instances.rst b/docs/compute_v1/instances.rst index f8ba5f34b..ff79fdecc 100644 --- a/docs/compute_v1/instances.rst +++ b/docs/compute_v1/instances.rst @@ -5,7 +5,6 @@ Instances :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.instances.pagers :members: :inherited-members: diff --git a/docs/compute_v1/interconnect_attachments.rst b/docs/compute_v1/interconnect_attachments.rst index 3356e3459..6c6d6e907 100644 --- a/docs/compute_v1/interconnect_attachments.rst +++ b/docs/compute_v1/interconnect_attachments.rst @@ -5,7 +5,6 @@ InterconnectAttachments :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.interconnect_attachments.pagers :members: :inherited-members: diff --git a/docs/compute_v1/interconnect_locations.rst b/docs/compute_v1/interconnect_locations.rst index bfb2d7c87..ed94bf8b0 100644 --- a/docs/compute_v1/interconnect_locations.rst +++ b/docs/compute_v1/interconnect_locations.rst @@ -5,7 +5,6 @@ InterconnectLocations :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.interconnect_locations.pagers :members: :inherited-members: diff --git a/docs/compute_v1/interconnects.rst b/docs/compute_v1/interconnects.rst index d33ff5d3c..810de28ad 100644 --- a/docs/compute_v1/interconnects.rst +++ b/docs/compute_v1/interconnects.rst @@ -5,7 +5,6 @@ Interconnects :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.interconnects.pagers :members: :inherited-members: diff --git a/docs/compute_v1/licenses.rst b/docs/compute_v1/licenses.rst index 4684df852..1782e396a 100644 --- a/docs/compute_v1/licenses.rst +++ b/docs/compute_v1/licenses.rst @@ -5,7 +5,6 @@ Licenses :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.licenses.pagers :members: :inherited-members: diff --git a/docs/compute_v1/machine_types.rst b/docs/compute_v1/machine_types.rst index 768b2d449..9c536e008 100644 --- a/docs/compute_v1/machine_types.rst +++ b/docs/compute_v1/machine_types.rst @@ -5,7 +5,6 @@ MachineTypes :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.machine_types.pagers :members: :inherited-members: diff --git a/docs/compute_v1/network_endpoint_groups.rst b/docs/compute_v1/network_endpoint_groups.rst index 3a1a44dee..0a929be61 100644 --- a/docs/compute_v1/network_endpoint_groups.rst +++ b/docs/compute_v1/network_endpoint_groups.rst @@ -5,7 +5,6 @@ NetworkEndpointGroups :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.network_endpoint_groups.pagers :members: :inherited-members: diff --git a/docs/compute_v1/networks.rst b/docs/compute_v1/networks.rst index 91273a803..2a74f4714 100644 --- a/docs/compute_v1/networks.rst +++ b/docs/compute_v1/networks.rst @@ -5,7 +5,6 @@ Networks :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.networks.pagers :members: :inherited-members: diff --git a/docs/compute_v1/node_groups.rst b/docs/compute_v1/node_groups.rst index 95b5c580b..ee5f0b254 100644 --- a/docs/compute_v1/node_groups.rst +++ b/docs/compute_v1/node_groups.rst @@ -5,7 +5,6 @@ NodeGroups :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.node_groups.pagers :members: :inherited-members: diff --git a/docs/compute_v1/node_templates.rst b/docs/compute_v1/node_templates.rst index d6b5c39db..1cd30fb6c 100644 --- a/docs/compute_v1/node_templates.rst +++ b/docs/compute_v1/node_templates.rst @@ -5,7 +5,6 @@ NodeTemplates :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.node_templates.pagers :members: :inherited-members: diff --git a/docs/compute_v1/node_types.rst b/docs/compute_v1/node_types.rst index f5723f0fc..4e765f36f 100644 --- a/docs/compute_v1/node_types.rst +++ b/docs/compute_v1/node_types.rst @@ -5,7 +5,6 @@ NodeTypes :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.node_types.pagers :members: :inherited-members: diff --git a/docs/compute_v1/packet_mirrorings.rst b/docs/compute_v1/packet_mirrorings.rst index 77d59a217..1fce6caed 100644 --- a/docs/compute_v1/packet_mirrorings.rst +++ b/docs/compute_v1/packet_mirrorings.rst @@ -5,7 +5,6 @@ PacketMirrorings :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.packet_mirrorings.pagers :members: :inherited-members: diff --git a/docs/compute_v1/projects.rst b/docs/compute_v1/projects.rst index deb8641a1..5e076fa50 100644 --- a/docs/compute_v1/projects.rst +++ b/docs/compute_v1/projects.rst @@ -5,7 +5,6 @@ Projects :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.projects.pagers :members: :inherited-members: diff --git a/docs/compute_v1/region_autoscalers.rst b/docs/compute_v1/region_autoscalers.rst index b491e22e2..cb7ace393 100644 --- a/docs/compute_v1/region_autoscalers.rst +++ b/docs/compute_v1/region_autoscalers.rst @@ -5,7 +5,6 @@ RegionAutoscalers :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.region_autoscalers.pagers :members: :inherited-members: diff --git a/docs/compute_v1/region_backend_services.rst b/docs/compute_v1/region_backend_services.rst index bbfda5cf4..1fcbe4028 100644 --- a/docs/compute_v1/region_backend_services.rst +++ b/docs/compute_v1/region_backend_services.rst @@ -5,7 +5,6 @@ RegionBackendServices :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.region_backend_services.pagers :members: :inherited-members: diff --git a/docs/compute_v1/region_commitments.rst b/docs/compute_v1/region_commitments.rst index 141ad66e7..f88e46dc1 100644 --- a/docs/compute_v1/region_commitments.rst +++ b/docs/compute_v1/region_commitments.rst @@ -5,7 +5,6 @@ RegionCommitments :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.region_commitments.pagers :members: :inherited-members: diff --git a/docs/compute_v1/region_disk_types.rst b/docs/compute_v1/region_disk_types.rst index f46e6258e..16a33bc3e 100644 --- a/docs/compute_v1/region_disk_types.rst +++ b/docs/compute_v1/region_disk_types.rst @@ -5,7 +5,6 @@ RegionDiskTypes :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.region_disk_types.pagers :members: :inherited-members: diff --git a/docs/compute_v1/region_disks.rst b/docs/compute_v1/region_disks.rst index 689b917a2..db87ad4b7 100644 --- a/docs/compute_v1/region_disks.rst +++ b/docs/compute_v1/region_disks.rst @@ -5,7 +5,6 @@ RegionDisks :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.region_disks.pagers :members: :inherited-members: diff --git a/docs/compute_v1/region_health_check_services.rst b/docs/compute_v1/region_health_check_services.rst index 8c342c0ad..2d28e52c1 100644 --- a/docs/compute_v1/region_health_check_services.rst +++ b/docs/compute_v1/region_health_check_services.rst @@ -5,7 +5,6 @@ RegionHealthCheckServices :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.region_health_check_services.pagers :members: :inherited-members: diff --git a/docs/compute_v1/region_health_checks.rst b/docs/compute_v1/region_health_checks.rst index 631de0dfc..296eab2c4 100644 --- a/docs/compute_v1/region_health_checks.rst +++ b/docs/compute_v1/region_health_checks.rst @@ -5,7 +5,6 @@ RegionHealthChecks :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.region_health_checks.pagers :members: :inherited-members: diff --git a/docs/compute_v1/region_instance_group_managers.rst b/docs/compute_v1/region_instance_group_managers.rst index fd3af5961..a6caf22fb 100644 --- a/docs/compute_v1/region_instance_group_managers.rst +++ b/docs/compute_v1/region_instance_group_managers.rst @@ -5,7 +5,6 @@ RegionInstanceGroupManagers :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.region_instance_group_managers.pagers :members: :inherited-members: diff --git a/docs/compute_v1/region_instance_groups.rst b/docs/compute_v1/region_instance_groups.rst index 473dc65e9..83ddb95ab 100644 --- a/docs/compute_v1/region_instance_groups.rst +++ b/docs/compute_v1/region_instance_groups.rst @@ -5,7 +5,6 @@ RegionInstanceGroups :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.region_instance_groups.pagers :members: :inherited-members: diff --git a/docs/compute_v1/region_network_endpoint_groups.rst b/docs/compute_v1/region_network_endpoint_groups.rst index d16d391cf..5c386c6fd 100644 --- a/docs/compute_v1/region_network_endpoint_groups.rst +++ b/docs/compute_v1/region_network_endpoint_groups.rst @@ -5,7 +5,6 @@ RegionNetworkEndpointGroups :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.region_network_endpoint_groups.pagers :members: :inherited-members: diff --git a/docs/compute_v1/region_notification_endpoints.rst b/docs/compute_v1/region_notification_endpoints.rst index 4baf0ced5..b69fe5d72 100644 --- a/docs/compute_v1/region_notification_endpoints.rst +++ b/docs/compute_v1/region_notification_endpoints.rst @@ -5,7 +5,6 @@ RegionNotificationEndpoints :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.region_notification_endpoints.pagers :members: :inherited-members: diff --git a/docs/compute_v1/region_operations.rst b/docs/compute_v1/region_operations.rst index be2ef7bf9..df407212c 100644 --- a/docs/compute_v1/region_operations.rst +++ b/docs/compute_v1/region_operations.rst @@ -5,7 +5,6 @@ RegionOperations :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.region_operations.pagers :members: :inherited-members: diff --git a/docs/compute_v1/region_ssl_certificates.rst b/docs/compute_v1/region_ssl_certificates.rst index 6de5c7c4b..e12d89e5d 100644 --- a/docs/compute_v1/region_ssl_certificates.rst +++ b/docs/compute_v1/region_ssl_certificates.rst @@ -5,7 +5,6 @@ RegionSslCertificates :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.region_ssl_certificates.pagers :members: :inherited-members: diff --git a/docs/compute_v1/region_target_http_proxies.rst b/docs/compute_v1/region_target_http_proxies.rst index f157d3bb7..187504997 100644 --- a/docs/compute_v1/region_target_http_proxies.rst +++ b/docs/compute_v1/region_target_http_proxies.rst @@ -5,7 +5,6 @@ RegionTargetHttpProxies :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.region_target_http_proxies.pagers :members: :inherited-members: diff --git a/docs/compute_v1/region_target_https_proxies.rst b/docs/compute_v1/region_target_https_proxies.rst index 3b5c715b4..32ad2918d 100644 --- a/docs/compute_v1/region_target_https_proxies.rst +++ b/docs/compute_v1/region_target_https_proxies.rst @@ -5,7 +5,6 @@ RegionTargetHttpsProxies :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.region_target_https_proxies.pagers :members: :inherited-members: diff --git a/docs/compute_v1/region_url_maps.rst b/docs/compute_v1/region_url_maps.rst index e01a03f0d..204cdf69b 100644 --- a/docs/compute_v1/region_url_maps.rst +++ b/docs/compute_v1/region_url_maps.rst @@ -5,7 +5,6 @@ RegionUrlMaps :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.region_url_maps.pagers :members: :inherited-members: diff --git a/docs/compute_v1/regions.rst b/docs/compute_v1/regions.rst index f1128793b..4beda5440 100644 --- a/docs/compute_v1/regions.rst +++ b/docs/compute_v1/regions.rst @@ -5,7 +5,6 @@ Regions :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.regions.pagers :members: :inherited-members: diff --git a/docs/compute_v1/reservations.rst b/docs/compute_v1/reservations.rst index 14f4dce81..adfa21b2c 100644 --- a/docs/compute_v1/reservations.rst +++ b/docs/compute_v1/reservations.rst @@ -5,7 +5,6 @@ Reservations :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.reservations.pagers :members: :inherited-members: diff --git a/docs/compute_v1/resource_policies.rst b/docs/compute_v1/resource_policies.rst index 6ca37afc2..39e2bab0e 100644 --- a/docs/compute_v1/resource_policies.rst +++ b/docs/compute_v1/resource_policies.rst @@ -5,7 +5,6 @@ ResourcePolicies :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.resource_policies.pagers :members: :inherited-members: diff --git a/docs/compute_v1/routers.rst b/docs/compute_v1/routers.rst index dac1975e4..0a82b2235 100644 --- a/docs/compute_v1/routers.rst +++ b/docs/compute_v1/routers.rst @@ -5,7 +5,6 @@ Routers :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.routers.pagers :members: :inherited-members: diff --git a/docs/compute_v1/routes.rst b/docs/compute_v1/routes.rst index 8a14f50e6..d03cd7e37 100644 --- a/docs/compute_v1/routes.rst +++ b/docs/compute_v1/routes.rst @@ -5,7 +5,6 @@ Routes :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.routes.pagers :members: :inherited-members: diff --git a/docs/compute_v1/security_policies.rst b/docs/compute_v1/security_policies.rst index c4bc38690..a2893695b 100644 --- a/docs/compute_v1/security_policies.rst +++ b/docs/compute_v1/security_policies.rst @@ -5,7 +5,6 @@ SecurityPolicies :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.security_policies.pagers :members: :inherited-members: diff --git a/docs/compute_v1/snapshots.rst b/docs/compute_v1/snapshots.rst index 1af9eed27..a29a1aa93 100644 --- a/docs/compute_v1/snapshots.rst +++ b/docs/compute_v1/snapshots.rst @@ -5,7 +5,6 @@ Snapshots :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.snapshots.pagers :members: :inherited-members: diff --git a/docs/compute_v1/ssl_certificates.rst b/docs/compute_v1/ssl_certificates.rst index c63ade587..e90c34ddd 100644 --- a/docs/compute_v1/ssl_certificates.rst +++ b/docs/compute_v1/ssl_certificates.rst @@ -5,7 +5,6 @@ SslCertificates :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.ssl_certificates.pagers :members: :inherited-members: diff --git a/docs/compute_v1/ssl_policies.rst b/docs/compute_v1/ssl_policies.rst index ddb6a78b6..d07c8b443 100644 --- a/docs/compute_v1/ssl_policies.rst +++ b/docs/compute_v1/ssl_policies.rst @@ -5,7 +5,6 @@ SslPolicies :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.ssl_policies.pagers :members: :inherited-members: diff --git a/docs/compute_v1/subnetworks.rst b/docs/compute_v1/subnetworks.rst index c99a21d05..cd20e0933 100644 --- a/docs/compute_v1/subnetworks.rst +++ b/docs/compute_v1/subnetworks.rst @@ -5,7 +5,6 @@ Subnetworks :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.subnetworks.pagers :members: :inherited-members: diff --git a/docs/compute_v1/target_grpc_proxies.rst b/docs/compute_v1/target_grpc_proxies.rst index 302c72398..4ddd96105 100644 --- a/docs/compute_v1/target_grpc_proxies.rst +++ b/docs/compute_v1/target_grpc_proxies.rst @@ -5,7 +5,6 @@ TargetGrpcProxies :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.target_grpc_proxies.pagers :members: :inherited-members: diff --git a/docs/compute_v1/target_http_proxies.rst b/docs/compute_v1/target_http_proxies.rst index ce0cd5a42..8fe97fe26 100644 --- a/docs/compute_v1/target_http_proxies.rst +++ b/docs/compute_v1/target_http_proxies.rst @@ -5,7 +5,6 @@ TargetHttpProxies :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.target_http_proxies.pagers :members: :inherited-members: diff --git a/docs/compute_v1/target_https_proxies.rst b/docs/compute_v1/target_https_proxies.rst index 0331656fa..d3cd4242d 100644 --- a/docs/compute_v1/target_https_proxies.rst +++ b/docs/compute_v1/target_https_proxies.rst @@ -5,7 +5,6 @@ TargetHttpsProxies :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.target_https_proxies.pagers :members: :inherited-members: diff --git a/docs/compute_v1/target_instances.rst b/docs/compute_v1/target_instances.rst index 840d1903e..9ab124ef9 100644 --- a/docs/compute_v1/target_instances.rst +++ b/docs/compute_v1/target_instances.rst @@ -5,7 +5,6 @@ TargetInstances :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.target_instances.pagers :members: :inherited-members: diff --git a/docs/compute_v1/target_pools.rst b/docs/compute_v1/target_pools.rst index 3898ef46d..7be339431 100644 --- a/docs/compute_v1/target_pools.rst +++ b/docs/compute_v1/target_pools.rst @@ -5,7 +5,6 @@ TargetPools :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.target_pools.pagers :members: :inherited-members: diff --git a/docs/compute_v1/target_ssl_proxies.rst b/docs/compute_v1/target_ssl_proxies.rst index f7a2d95ce..5c39bcf67 100644 --- a/docs/compute_v1/target_ssl_proxies.rst +++ b/docs/compute_v1/target_ssl_proxies.rst @@ -5,7 +5,6 @@ TargetSslProxies :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.target_ssl_proxies.pagers :members: :inherited-members: diff --git a/docs/compute_v1/target_tcp_proxies.rst b/docs/compute_v1/target_tcp_proxies.rst index 66b3d186f..940978c3f 100644 --- a/docs/compute_v1/target_tcp_proxies.rst +++ b/docs/compute_v1/target_tcp_proxies.rst @@ -5,7 +5,6 @@ TargetTcpProxies :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.target_tcp_proxies.pagers :members: :inherited-members: diff --git a/docs/compute_v1/target_vpn_gateways.rst b/docs/compute_v1/target_vpn_gateways.rst index f1f42c8ad..0fb0f169c 100644 --- a/docs/compute_v1/target_vpn_gateways.rst +++ b/docs/compute_v1/target_vpn_gateways.rst @@ -5,7 +5,6 @@ TargetVpnGateways :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.target_vpn_gateways.pagers :members: :inherited-members: diff --git a/docs/compute_v1/url_maps.rst b/docs/compute_v1/url_maps.rst index 4c82c849c..c0494fe72 100644 --- a/docs/compute_v1/url_maps.rst +++ b/docs/compute_v1/url_maps.rst @@ -5,7 +5,6 @@ UrlMaps :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.url_maps.pagers :members: :inherited-members: diff --git a/docs/compute_v1/vpn_gateways.rst b/docs/compute_v1/vpn_gateways.rst index d08ca6794..4313fd9b8 100644 --- a/docs/compute_v1/vpn_gateways.rst +++ b/docs/compute_v1/vpn_gateways.rst @@ -5,7 +5,6 @@ VpnGateways :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.vpn_gateways.pagers :members: :inherited-members: diff --git a/docs/compute_v1/vpn_tunnels.rst b/docs/compute_v1/vpn_tunnels.rst index 91549354b..ba0faf8ba 100644 --- a/docs/compute_v1/vpn_tunnels.rst +++ b/docs/compute_v1/vpn_tunnels.rst @@ -5,7 +5,6 @@ VpnTunnels :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.vpn_tunnels.pagers :members: :inherited-members: diff --git a/docs/compute_v1/zone_operations.rst b/docs/compute_v1/zone_operations.rst index 1b966fd77..3ad84fbc8 100644 --- a/docs/compute_v1/zone_operations.rst +++ b/docs/compute_v1/zone_operations.rst @@ -5,7 +5,6 @@ ZoneOperations :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.zone_operations.pagers :members: :inherited-members: diff --git a/docs/compute_v1/zones.rst b/docs/compute_v1/zones.rst index 55af2eafc..f34131bf8 100644 --- a/docs/compute_v1/zones.rst +++ b/docs/compute_v1/zones.rst @@ -5,7 +5,6 @@ Zones :members: :inherited-members: - .. automodule:: google.cloud.compute_v1.services.zones.pagers :members: :inherited-members: diff --git a/google/cloud/compute/__init__.py b/google/cloud/compute/__init__.py index 8e741a1b4..4be256c29 100644 --- a/google/cloud/compute/__init__.py +++ b/google/cloud/compute/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -24,8 +23,8 @@ from google.cloud.compute_v1.services.backend_services.client import ( BackendServicesClient, ) -from google.cloud.compute_v1.services.disk_types.client import DiskTypesClient from google.cloud.compute_v1.services.disks.client import DisksClient +from google.cloud.compute_v1.services.disk_types.client import DiskTypesClient from google.cloud.compute_v1.services.external_vpn_gateways.client import ( ExternalVpnGatewaysClient, ) @@ -54,10 +53,10 @@ InstanceGroupManagersClient, ) from google.cloud.compute_v1.services.instance_groups.client import InstanceGroupsClient +from google.cloud.compute_v1.services.instances.client import InstancesClient from google.cloud.compute_v1.services.instance_templates.client import ( InstanceTemplatesClient, ) -from google.cloud.compute_v1.services.instances.client import InstancesClient from google.cloud.compute_v1.services.interconnect_attachments.client import ( InterconnectAttachmentsClient, ) @@ -88,16 +87,16 @@ from google.cloud.compute_v1.services.region_commitments.client import ( RegionCommitmentsClient, ) +from google.cloud.compute_v1.services.region_disks.client import RegionDisksClient from google.cloud.compute_v1.services.region_disk_types.client import ( RegionDiskTypesClient, ) -from google.cloud.compute_v1.services.region_disks.client import RegionDisksClient -from google.cloud.compute_v1.services.region_health_check_services.client import ( - RegionHealthCheckServicesClient, -) from google.cloud.compute_v1.services.region_health_checks.client import ( RegionHealthChecksClient, ) +from google.cloud.compute_v1.services.region_health_check_services.client import ( + RegionHealthCheckServicesClient, +) from google.cloud.compute_v1.services.region_instance_group_managers.client import ( RegionInstanceGroupManagersClient, ) @@ -113,6 +112,7 @@ from google.cloud.compute_v1.services.region_operations.client import ( RegionOperationsClient, ) +from google.cloud.compute_v1.services.regions.client import RegionsClient from google.cloud.compute_v1.services.region_ssl_certificates.client import ( RegionSslCertificatesClient, ) @@ -123,7 +123,6 @@ RegionTargetHttpsProxiesClient, ) from google.cloud.compute_v1.services.region_url_maps.client import RegionUrlMapsClient -from google.cloud.compute_v1.services.regions.client import RegionsClient from google.cloud.compute_v1.services.reservations.client import ReservationsClient from google.cloud.compute_v1.services.resource_policies.client import ( ResourcePoliciesClient, @@ -166,6 +165,7 @@ from google.cloud.compute_v1.services.vpn_tunnels.client import VpnTunnelsClient from google.cloud.compute_v1.services.zone_operations.client import ZoneOperationsClient from google.cloud.compute_v1.services.zones.client import ZonesClient + from google.cloud.compute_v1.types.compute import ( AbandonInstancesInstanceGroupManagerRequest, ) @@ -173,34 +173,34 @@ AbandonInstancesRegionInstanceGroupManagerRequest, ) from google.cloud.compute_v1.types.compute import AcceleratorConfig +from google.cloud.compute_v1.types.compute import Accelerators from google.cloud.compute_v1.types.compute import AcceleratorType from google.cloud.compute_v1.types.compute import AcceleratorTypeAggregatedList from google.cloud.compute_v1.types.compute import AcceleratorTypeList from google.cloud.compute_v1.types.compute import AcceleratorTypesScopedList -from google.cloud.compute_v1.types.compute import Accelerators 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 AddHealthCheckTargetPoolRequest -from google.cloud.compute_v1.types.compute import AddInstanceTargetPoolRequest from google.cloud.compute_v1.types.compute import AddInstancesInstanceGroupRequest +from google.cloud.compute_v1.types.compute import AddInstanceTargetPoolRequest from google.cloud.compute_v1.types.compute import AddNodesNodeGroupRequest from google.cloud.compute_v1.types.compute import AddPeeringNetworkRequest from google.cloud.compute_v1.types.compute import AddResourcePoliciesDiskRequest from google.cloud.compute_v1.types.compute import AddResourcePoliciesInstanceRequest from google.cloud.compute_v1.types.compute import AddResourcePoliciesRegionDiskRequest -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 Address from google.cloud.compute_v1.types.compute import AddressAggregatedList -from google.cloud.compute_v1.types.compute import AddressList 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 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 AggregatedListAcceleratorTypesRequest from google.cloud.compute_v1.types.compute import AggregatedListAddressesRequest from google.cloud.compute_v1.types.compute import AggregatedListAutoscalersRequest from google.cloud.compute_v1.types.compute import AggregatedListBackendServicesRequest -from google.cloud.compute_v1.types.compute import AggregatedListDiskTypesRequest from google.cloud.compute_v1.types.compute import AggregatedListDisksRequest +from google.cloud.compute_v1.types.compute import AggregatedListDiskTypesRequest from google.cloud.compute_v1.types.compute import AggregatedListForwardingRulesRequest from google.cloud.compute_v1.types.compute import AggregatedListGlobalOperationsRequest from google.cloud.compute_v1.types.compute import AggregatedListHealthChecksRequest @@ -252,22 +252,22 @@ ApplyUpdatesToInstancesRegionInstanceGroupManagerRequest, ) from google.cloud.compute_v1.types.compute import AttachDiskInstanceRequest +from google.cloud.compute_v1.types.compute import AttachedDisk +from google.cloud.compute_v1.types.compute import AttachedDiskInitializeParams from google.cloud.compute_v1.types.compute import ( AttachNetworkEndpointsGlobalNetworkEndpointGroupRequest, ) from google.cloud.compute_v1.types.compute import ( AttachNetworkEndpointsNetworkEndpointGroupRequest, ) -from google.cloud.compute_v1.types.compute import AttachedDisk -from google.cloud.compute_v1.types.compute import AttachedDiskInitializeParams from google.cloud.compute_v1.types.compute import AuditConfig from google.cloud.compute_v1.types.compute import AuditLogConfig from google.cloud.compute_v1.types.compute import AuthorizationLoggingOptions from google.cloud.compute_v1.types.compute import Autoscaler from google.cloud.compute_v1.types.compute import AutoscalerAggregatedList from google.cloud.compute_v1.types.compute import AutoscalerList -from google.cloud.compute_v1.types.compute import AutoscalerStatusDetails from google.cloud.compute_v1.types.compute import AutoscalersScopedList +from google.cloud.compute_v1.types.compute import AutoscalerStatusDetails from google.cloud.compute_v1.types.compute import AutoscalingPolicy from google.cloud.compute_v1.types.compute import AutoscalingPolicyCpuUtilization from google.cloud.compute_v1.types.compute import ( @@ -345,21 +345,21 @@ from google.cloud.compute_v1.types.compute import DeleteInstanceGroupManagerRequest from google.cloud.compute_v1.types.compute import DeleteInstanceGroupRequest from google.cloud.compute_v1.types.compute import DeleteInstanceRequest -from google.cloud.compute_v1.types.compute import DeleteInstanceTemplateRequest from google.cloud.compute_v1.types.compute import ( DeleteInstancesInstanceGroupManagerRequest, ) from google.cloud.compute_v1.types.compute import ( DeleteInstancesRegionInstanceGroupManagerRequest, ) +from google.cloud.compute_v1.types.compute import DeleteInstanceTemplateRequest from google.cloud.compute_v1.types.compute import DeleteInterconnectAttachmentRequest from google.cloud.compute_v1.types.compute import DeleteInterconnectRequest from google.cloud.compute_v1.types.compute import DeleteLicenseRequest from google.cloud.compute_v1.types.compute import DeleteNetworkEndpointGroupRequest from google.cloud.compute_v1.types.compute import DeleteNetworkRequest from google.cloud.compute_v1.types.compute import DeleteNodeGroupRequest -from google.cloud.compute_v1.types.compute import DeleteNodeTemplateRequest from google.cloud.compute_v1.types.compute import DeleteNodesNodeGroupRequest +from google.cloud.compute_v1.types.compute import DeleteNodeTemplateRequest from google.cloud.compute_v1.types.compute import DeletePacketMirroringRequest from google.cloud.compute_v1.types.compute import ( DeletePerInstanceConfigsInstanceGroupManagerRequest, @@ -430,14 +430,14 @@ from google.cloud.compute_v1.types.compute import DiskInstantiationConfig from google.cloud.compute_v1.types.compute import DiskList from google.cloud.compute_v1.types.compute import DiskMoveRequest -from google.cloud.compute_v1.types.compute import DiskType -from google.cloud.compute_v1.types.compute import DiskTypeAggregatedList -from google.cloud.compute_v1.types.compute import DiskTypeList -from google.cloud.compute_v1.types.compute import DiskTypesScopedList from google.cloud.compute_v1.types.compute import DisksAddResourcePoliciesRequest from google.cloud.compute_v1.types.compute import DisksRemoveResourcePoliciesRequest from google.cloud.compute_v1.types.compute import DisksResizeRequest from google.cloud.compute_v1.types.compute import DisksScopedList +from google.cloud.compute_v1.types.compute import DiskType +from google.cloud.compute_v1.types.compute import DiskTypeAggregatedList +from google.cloud.compute_v1.types.compute import DiskTypeList +from google.cloud.compute_v1.types.compute import DiskTypesScopedList from google.cloud.compute_v1.types.compute import DisplayDevice from google.cloud.compute_v1.types.compute import DistributionPolicy from google.cloud.compute_v1.types.compute import DistributionPolicyZoneConfiguration @@ -463,7 +463,6 @@ 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 ForwardingRulesScopedList -from google.cloud.compute_v1.types.compute import GRPCHealthCheck 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 GetAutoscalerRequest @@ -574,37 +573,38 @@ ) 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 from google.cloud.compute_v1.types.compute import GuestAttributes from google.cloud.compute_v1.types.compute import GuestAttributesEntry from google.cloud.compute_v1.types.compute import GuestAttributesValue from google.cloud.compute_v1.types.compute import GuestOsFeature -from google.cloud.compute_v1.types.compute import HTTP2HealthCheck -from google.cloud.compute_v1.types.compute import HTTPHealthCheck -from google.cloud.compute_v1.types.compute import HTTPSHealthCheck from google.cloud.compute_v1.types.compute import HealthCheck from google.cloud.compute_v1.types.compute import HealthCheckList from google.cloud.compute_v1.types.compute import HealthCheckLogConfig from google.cloud.compute_v1.types.compute import HealthCheckReference +from google.cloud.compute_v1.types.compute import HealthChecksAggregatedList from google.cloud.compute_v1.types.compute import HealthCheckService from google.cloud.compute_v1.types.compute import HealthCheckServiceReference from google.cloud.compute_v1.types.compute import HealthCheckServicesList -from google.cloud.compute_v1.types.compute import HealthChecksAggregatedList from google.cloud.compute_v1.types.compute import HealthChecksScopedList from google.cloud.compute_v1.types.compute import HealthStatus from google.cloud.compute_v1.types.compute import HealthStatusForNetworkEndpoint from google.cloud.compute_v1.types.compute import HostRule +from google.cloud.compute_v1.types.compute import HTTP2HealthCheck from google.cloud.compute_v1.types.compute import HttpFaultAbort from google.cloud.compute_v1.types.compute import HttpFaultDelay from google.cloud.compute_v1.types.compute import HttpFaultInjection from google.cloud.compute_v1.types.compute import HttpHeaderAction from google.cloud.compute_v1.types.compute import HttpHeaderMatch from google.cloud.compute_v1.types.compute import HttpHeaderOption +from google.cloud.compute_v1.types.compute import HTTPHealthCheck from google.cloud.compute_v1.types.compute import HttpQueryParameterMatch from google.cloud.compute_v1.types.compute import HttpRedirectAction from google.cloud.compute_v1.types.compute import HttpRetryPolicy from google.cloud.compute_v1.types.compute import HttpRouteAction from google.cloud.compute_v1.types.compute import HttpRouteRule from google.cloud.compute_v1.types.compute import HttpRouteRuleMatch +from google.cloud.compute_v1.types.compute import HTTPSHealthCheck from google.cloud.compute_v1.types.compute import Image from google.cloud.compute_v1.types.compute import ImageList from google.cloud.compute_v1.types.compute import InitialStateConfig @@ -683,16 +683,6 @@ from google.cloud.compute_v1.types.compute import InstanceGroupManagerAggregatedList from google.cloud.compute_v1.types.compute import InstanceGroupManagerAutoHealingPolicy from google.cloud.compute_v1.types.compute import InstanceGroupManagerList -from google.cloud.compute_v1.types.compute import InstanceGroupManagerStatus -from google.cloud.compute_v1.types.compute import InstanceGroupManagerStatusStateful -from google.cloud.compute_v1.types.compute import ( - InstanceGroupManagerStatusStatefulPerInstanceConfigs, -) -from google.cloud.compute_v1.types.compute import ( - InstanceGroupManagerStatusVersionTarget, -) -from google.cloud.compute_v1.types.compute import InstanceGroupManagerUpdatePolicy -from google.cloud.compute_v1.types.compute import InstanceGroupManagerVersion from google.cloud.compute_v1.types.compute import ( InstanceGroupManagersAbandonInstancesRequest, ) @@ -730,9 +720,19 @@ from google.cloud.compute_v1.types.compute import ( InstanceGroupManagersSetTargetPoolsRequest, ) +from google.cloud.compute_v1.types.compute import InstanceGroupManagerStatus +from google.cloud.compute_v1.types.compute import InstanceGroupManagerStatusStateful +from google.cloud.compute_v1.types.compute import ( + InstanceGroupManagerStatusStatefulPerInstanceConfigs, +) +from google.cloud.compute_v1.types.compute import ( + InstanceGroupManagerStatusVersionTarget, +) from google.cloud.compute_v1.types.compute import ( InstanceGroupManagersUpdatePerInstanceConfigsReq, ) +from google.cloud.compute_v1.types.compute import InstanceGroupManagerUpdatePolicy +from google.cloud.compute_v1.types.compute import InstanceGroupManagerVersion from google.cloud.compute_v1.types.compute import InstanceGroupsAddInstancesRequest from google.cloud.compute_v1.types.compute import InstanceGroupsListInstances from google.cloud.compute_v1.types.compute import InstanceGroupsListInstancesRequest @@ -751,9 +751,6 @@ from google.cloud.compute_v1.types.compute import InstanceMoveRequest 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 InstanceTemplate -from google.cloud.compute_v1.types.compute import InstanceTemplateList -from google.cloud.compute_v1.types.compute import InstanceWithNamedPorts from google.cloud.compute_v1.types.compute import InstancesAddResourcePoliciesRequest from google.cloud.compute_v1.types.compute import InstancesRemoveResourcePoliciesRequest from google.cloud.compute_v1.types.compute import InstancesScopedList @@ -763,6 +760,9 @@ from google.cloud.compute_v1.types.compute import InstancesSetMinCpuPlatformRequest from google.cloud.compute_v1.types.compute import InstancesSetServiceAccountRequest from google.cloud.compute_v1.types.compute import InstancesStartWithEncryptionKeyRequest +from google.cloud.compute_v1.types.compute import InstanceTemplate +from google.cloud.compute_v1.types.compute import InstanceTemplateList +from google.cloud.compute_v1.types.compute import InstanceWithNamedPorts from google.cloud.compute_v1.types.compute import Int64RangeMatch from google.cloud.compute_v1.types.compute import Interconnect from google.cloud.compute_v1.types.compute import InterconnectAttachment @@ -801,8 +801,8 @@ ) from google.cloud.compute_v1.types.compute import ListBackendBucketsRequest from google.cloud.compute_v1.types.compute import ListBackendServicesRequest -from google.cloud.compute_v1.types.compute import ListDiskTypesRequest from google.cloud.compute_v1.types.compute import ListDisksRequest +from google.cloud.compute_v1.types.compute import ListDiskTypesRequest from google.cloud.compute_v1.types.compute import ListErrorsInstanceGroupManagersRequest from google.cloud.compute_v1.types.compute import ( ListErrorsRegionInstanceGroupManagersRequest, @@ -821,12 +821,12 @@ from google.cloud.compute_v1.types.compute import ListImagesRequest from google.cloud.compute_v1.types.compute import ListInstanceGroupManagersRequest from google.cloud.compute_v1.types.compute import ListInstanceGroupsRequest -from google.cloud.compute_v1.types.compute import ListInstanceTemplatesRequest from google.cloud.compute_v1.types.compute import ListInstancesInstanceGroupsRequest from google.cloud.compute_v1.types.compute import ( ListInstancesRegionInstanceGroupsRequest, ) from google.cloud.compute_v1.types.compute import ListInstancesRequest +from google.cloud.compute_v1.types.compute import ListInstanceTemplatesRequest from google.cloud.compute_v1.types.compute import ListInterconnectAttachmentsRequest from google.cloud.compute_v1.types.compute import ListInterconnectLocationsRequest from google.cloud.compute_v1.types.compute import ListInterconnectsRequest @@ -847,9 +847,9 @@ ) from google.cloud.compute_v1.types.compute import ListNetworksRequest from google.cloud.compute_v1.types.compute import ListNodeGroupsRequest +from google.cloud.compute_v1.types.compute import ListNodesNodeGroupsRequest from google.cloud.compute_v1.types.compute import ListNodeTemplatesRequest from google.cloud.compute_v1.types.compute import ListNodeTypesRequest -from google.cloud.compute_v1.types.compute import ListNodesNodeGroupsRequest from google.cloud.compute_v1.types.compute import ListPacketMirroringsRequest from google.cloud.compute_v1.types.compute import ListPeeringRoutesNetworksRequest from google.cloud.compute_v1.types.compute import ( @@ -865,8 +865,8 @@ from google.cloud.compute_v1.types.compute import ListRegionAutoscalersRequest from google.cloud.compute_v1.types.compute import ListRegionBackendServicesRequest from google.cloud.compute_v1.types.compute import ListRegionCommitmentsRequest -from google.cloud.compute_v1.types.compute import ListRegionDiskTypesRequest from google.cloud.compute_v1.types.compute import ListRegionDisksRequest +from google.cloud.compute_v1.types.compute import ListRegionDiskTypesRequest from google.cloud.compute_v1.types.compute import ListRegionHealthCheckServicesRequest from google.cloud.compute_v1.types.compute import ListRegionHealthChecksRequest from google.cloud.compute_v1.types.compute import ListRegionInstanceGroupManagersRequest @@ -874,11 +874,11 @@ from google.cloud.compute_v1.types.compute import ListRegionNetworkEndpointGroupsRequest from google.cloud.compute_v1.types.compute import ListRegionNotificationEndpointsRequest from google.cloud.compute_v1.types.compute import ListRegionOperationsRequest +from google.cloud.compute_v1.types.compute import ListRegionsRequest from google.cloud.compute_v1.types.compute import ListRegionSslCertificatesRequest from google.cloud.compute_v1.types.compute import ListRegionTargetHttpProxiesRequest from google.cloud.compute_v1.types.compute import ListRegionTargetHttpsProxiesRequest from google.cloud.compute_v1.types.compute import ListRegionUrlMapsRequest -from google.cloud.compute_v1.types.compute import ListRegionsRequest from google.cloud.compute_v1.types.compute import ListReservationsRequest from google.cloud.compute_v1.types.compute import ListResourcePoliciesRequest from google.cloud.compute_v1.types.compute import ListRoutersRequest @@ -1053,12 +1053,12 @@ from google.cloud.compute_v1.types.compute import Reference from google.cloud.compute_v1.types.compute import Region from google.cloud.compute_v1.types.compute import RegionAutoscalerList -from google.cloud.compute_v1.types.compute import RegionDiskTypeList from google.cloud.compute_v1.types.compute import RegionDisksAddResourcePoliciesRequest from google.cloud.compute_v1.types.compute import ( RegionDisksRemoveResourcePoliciesRequest, ) from google.cloud.compute_v1.types.compute import RegionDisksResizeRequest +from google.cloud.compute_v1.types.compute import RegionDiskTypeList from google.cloud.compute_v1.types.compute import RegionInstanceGroupList from google.cloud.compute_v1.types.compute import ( RegionInstanceGroupManagerDeleteInstanceConfigReq, @@ -1067,9 +1067,6 @@ from google.cloud.compute_v1.types.compute import ( RegionInstanceGroupManagerPatchInstanceConfigReq, ) -from google.cloud.compute_v1.types.compute import ( - RegionInstanceGroupManagerUpdateInstanceConfigReq, -) from google.cloud.compute_v1.types.compute import ( RegionInstanceGroupManagersAbandonInstancesRequest, ) @@ -1100,6 +1097,9 @@ from google.cloud.compute_v1.types.compute import ( RegionInstanceGroupManagersSetTemplateRequest, ) +from google.cloud.compute_v1.types.compute import ( + RegionInstanceGroupManagerUpdateInstanceConfigReq, +) from google.cloud.compute_v1.types.compute import RegionInstanceGroupsListInstances from google.cloud.compute_v1.types.compute import ( RegionInstanceGroupsListInstancesRequest, @@ -1115,8 +1115,8 @@ ) from google.cloud.compute_v1.types.compute import RegionUrlMapsValidateRequest from google.cloud.compute_v1.types.compute import RemoveHealthCheckTargetPoolRequest -from google.cloud.compute_v1.types.compute import RemoveInstanceTargetPoolRequest from google.cloud.compute_v1.types.compute import RemoveInstancesInstanceGroupRequest +from google.cloud.compute_v1.types.compute import RemoveInstanceTargetPoolRequest from google.cloud.compute_v1.types.compute import RemovePeeringNetworkRequest from google.cloud.compute_v1.types.compute import RemoveResourcePoliciesDiskRequest from google.cloud.compute_v1.types.compute import RemoveResourcePoliciesInstanceRequest @@ -1172,14 +1172,13 @@ from google.cloud.compute_v1.types.compute import RouterNat from google.cloud.compute_v1.types.compute import RouterNatLogConfig from google.cloud.compute_v1.types.compute import RouterNatSubnetworkToNat +from google.cloud.compute_v1.types.compute import RoutersPreviewResponse +from google.cloud.compute_v1.types.compute import RoutersScopedList from google.cloud.compute_v1.types.compute import RouterStatus from google.cloud.compute_v1.types.compute import RouterStatusBgpPeerStatus 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 RoutersPreviewResponse -from google.cloud.compute_v1.types.compute import RoutersScopedList from google.cloud.compute_v1.types.compute import Rule -from google.cloud.compute_v1.types.compute import SSLHealthCheck 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 @@ -1297,6 +1296,7 @@ SslCertificateSelfManagedSslCertificate, ) from google.cloud.compute_v1.types.compute import SslCertificatesScopedList +from google.cloud.compute_v1.types.compute import SSLHealthCheck from google.cloud.compute_v1.types.compute import SslPoliciesList from google.cloud.compute_v1.types.compute import ( SslPoliciesListAvailableFeaturesResponse, @@ -1320,7 +1320,6 @@ SubnetworksSetPrivateIpGoogleAccessRequest, ) from google.cloud.compute_v1.types.compute import SwitchToCustomModeNetworkRequest -from google.cloud.compute_v1.types.compute import TCPHealthCheck from google.cloud.compute_v1.types.compute import Tags from google.cloud.compute_v1.types.compute import TargetGrpcProxy from google.cloud.compute_v1.types.compute import TargetGrpcProxyList @@ -1371,6 +1370,7 @@ from google.cloud.compute_v1.types.compute import TargetVpnGatewayAggregatedList from google.cloud.compute_v1.types.compute import TargetVpnGatewayList from google.cloud.compute_v1.types.compute import TargetVpnGatewaysScopedList +from google.cloud.compute_v1.types.compute import TCPHealthCheck from google.cloud.compute_v1.types.compute import TestFailure from google.cloud.compute_v1.types.compute import TestIamPermissionsDiskRequest from google.cloud.compute_v1.types.compute import ( @@ -1429,16 +1429,16 @@ from google.cloud.compute_v1.types.compute import UrlMap from google.cloud.compute_v1.types.compute import UrlMapList from google.cloud.compute_v1.types.compute import UrlMapReference -from google.cloud.compute_v1.types.compute import UrlMapTest -from google.cloud.compute_v1.types.compute import UrlMapValidationResult from google.cloud.compute_v1.types.compute import UrlMapsAggregatedList from google.cloud.compute_v1.types.compute import UrlMapsScopedList 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 UrlMapValidationResult from google.cloud.compute_v1.types.compute import UrlRewrite from google.cloud.compute_v1.types.compute import UsableSubnetwork -from google.cloud.compute_v1.types.compute import UsableSubnetworkSecondaryRange from google.cloud.compute_v1.types.compute import UsableSubnetworksAggregatedList +from google.cloud.compute_v1.types.compute import UsableSubnetworkSecondaryRange from google.cloud.compute_v1.types.compute import UsageExportLocation from google.cloud.compute_v1.types.compute import ValidateRegionUrlMapRequest from google.cloud.compute_v1.types.compute import ValidateUrlMapRequest @@ -1450,6 +1450,8 @@ from google.cloud.compute_v1.types.compute import VpnGateway from google.cloud.compute_v1.types.compute import VpnGatewayAggregatedList from google.cloud.compute_v1.types.compute import VpnGatewayList +from google.cloud.compute_v1.types.compute import VpnGatewaysGetStatusResponse +from google.cloud.compute_v1.types.compute import VpnGatewaysScopedList from google.cloud.compute_v1.types.compute import VpnGatewayStatus from google.cloud.compute_v1.types.compute import ( VpnGatewayStatusHighAvailabilityRequirementState, @@ -1457,8 +1459,6 @@ from google.cloud.compute_v1.types.compute import VpnGatewayStatusTunnel from google.cloud.compute_v1.types.compute import VpnGatewayStatusVpnConnection from google.cloud.compute_v1.types.compute import VpnGatewayVpnGatewayInterface -from google.cloud.compute_v1.types.compute import VpnGatewaysGetStatusResponse -from google.cloud.compute_v1.types.compute import VpnGatewaysScopedList from google.cloud.compute_v1.types.compute import VpnTunnel from google.cloud.compute_v1.types.compute import VpnTunnelAggregatedList from google.cloud.compute_v1.types.compute import VpnTunnelList @@ -1479,39 +1479,110 @@ from google.cloud.compute_v1.types.compute import ZoneSetPolicyRequest __all__ = ( + "AcceleratorTypesClient", + "AddressesClient", + "AutoscalersClient", + "BackendBucketsClient", + "BackendServicesClient", + "DisksClient", + "DiskTypesClient", + "ExternalVpnGatewaysClient", + "FirewallsClient", + "ForwardingRulesClient", + "GlobalAddressesClient", + "GlobalForwardingRulesClient", + "GlobalNetworkEndpointGroupsClient", + "GlobalOperationsClient", + "GlobalOrganizationOperationsClient", + "HealthChecksClient", + "ImagesClient", + "InstanceGroupManagersClient", + "InstanceGroupsClient", + "InstancesClient", + "InstanceTemplatesClient", + "InterconnectAttachmentsClient", + "InterconnectLocationsClient", + "InterconnectsClient", + "LicenseCodesClient", + "LicensesClient", + "MachineTypesClient", + "NetworkEndpointGroupsClient", + "NetworksClient", + "NodeGroupsClient", + "NodeTemplatesClient", + "NodeTypesClient", + "PacketMirroringsClient", + "ProjectsClient", + "RegionAutoscalersClient", + "RegionBackendServicesClient", + "RegionCommitmentsClient", + "RegionDisksClient", + "RegionDiskTypesClient", + "RegionHealthChecksClient", + "RegionHealthCheckServicesClient", + "RegionInstanceGroupManagersClient", + "RegionInstanceGroupsClient", + "RegionNetworkEndpointGroupsClient", + "RegionNotificationEndpointsClient", + "RegionOperationsClient", + "RegionsClient", + "RegionSslCertificatesClient", + "RegionTargetHttpProxiesClient", + "RegionTargetHttpsProxiesClient", + "RegionUrlMapsClient", + "ReservationsClient", + "ResourcePoliciesClient", + "RoutersClient", + "RoutesClient", + "SecurityPoliciesClient", + "SnapshotsClient", + "SslCertificatesClient", + "SslPoliciesClient", + "SubnetworksClient", + "TargetGrpcProxiesClient", + "TargetHttpProxiesClient", + "TargetHttpsProxiesClient", + "TargetInstancesClient", + "TargetPoolsClient", + "TargetSslProxiesClient", + "TargetTcpProxiesClient", + "TargetVpnGatewaysClient", + "UrlMapsClient", + "VpnGatewaysClient", + "VpnTunnelsClient", + "ZoneOperationsClient", + "ZonesClient", "AbandonInstancesInstanceGroupManagerRequest", "AbandonInstancesRegionInstanceGroupManagerRequest", "AcceleratorConfig", + "Accelerators", "AcceleratorType", "AcceleratorTypeAggregatedList", "AcceleratorTypeList", - "AcceleratorTypesClient", "AcceleratorTypesScopedList", - "Accelerators", "AccessConfig", "AddAccessConfigInstanceRequest", "AddHealthCheckTargetPoolRequest", - "AddInstanceTargetPoolRequest", "AddInstancesInstanceGroupRequest", + "AddInstanceTargetPoolRequest", "AddNodesNodeGroupRequest", "AddPeeringNetworkRequest", "AddResourcePoliciesDiskRequest", "AddResourcePoliciesInstanceRequest", "AddResourcePoliciesRegionDiskRequest", - "AddRuleSecurityPolicyRequest", - "AddSignedUrlKeyBackendBucketRequest", - "AddSignedUrlKeyBackendServiceRequest", "Address", "AddressAggregatedList", - "AddressList", - "AddressesClient", "AddressesScopedList", + "AddressList", + "AddRuleSecurityPolicyRequest", + "AddSignedUrlKeyBackendBucketRequest", + "AddSignedUrlKeyBackendServiceRequest", "AggregatedListAcceleratorTypesRequest", "AggregatedListAddressesRequest", "AggregatedListAutoscalersRequest", "AggregatedListBackendServicesRequest", - "AggregatedListDiskTypesRequest", "AggregatedListDisksRequest", + "AggregatedListDiskTypesRequest", "AggregatedListForwardingRulesRequest", "AggregatedListGlobalOperationsRequest", "AggregatedListHealthChecksRequest", @@ -1547,19 +1618,18 @@ "ApplyUpdatesToInstancesInstanceGroupManagerRequest", "ApplyUpdatesToInstancesRegionInstanceGroupManagerRequest", "AttachDiskInstanceRequest", - "AttachNetworkEndpointsGlobalNetworkEndpointGroupRequest", - "AttachNetworkEndpointsNetworkEndpointGroupRequest", "AttachedDisk", "AttachedDiskInitializeParams", + "AttachNetworkEndpointsGlobalNetworkEndpointGroupRequest", + "AttachNetworkEndpointsNetworkEndpointGroupRequest", "AuditConfig", "AuditLogConfig", "AuthorizationLoggingOptions", "Autoscaler", "AutoscalerAggregatedList", "AutoscalerList", - "AutoscalerStatusDetails", - "AutoscalersClient", "AutoscalersScopedList", + "AutoscalerStatusDetails", "AutoscalingPolicy", "AutoscalingPolicyCpuUtilization", "AutoscalingPolicyCustomMetricUtilization", @@ -1569,7 +1639,6 @@ "BackendBucket", "BackendBucketCdnPolicy", "BackendBucketList", - "BackendBucketsClient", "BackendService", "BackendServiceAggregatedList", "BackendServiceCdnPolicy", @@ -1579,7 +1648,6 @@ "BackendServiceList", "BackendServiceLogConfig", "BackendServiceReference", - "BackendServicesClient", "BackendServicesScopedList", "Binding", "CacheInvalidationRule", @@ -1623,17 +1691,17 @@ "DeleteInstanceGroupManagerRequest", "DeleteInstanceGroupRequest", "DeleteInstanceRequest", - "DeleteInstanceTemplateRequest", "DeleteInstancesInstanceGroupManagerRequest", "DeleteInstancesRegionInstanceGroupManagerRequest", + "DeleteInstanceTemplateRequest", "DeleteInterconnectAttachmentRequest", "DeleteInterconnectRequest", "DeleteLicenseRequest", "DeleteNetworkEndpointGroupRequest", "DeleteNetworkRequest", "DeleteNodeGroupRequest", - "DeleteNodeTemplateRequest", "DeleteNodesNodeGroupRequest", + "DeleteNodeTemplateRequest", "DeletePacketMirroringRequest", "DeletePerInstanceConfigsInstanceGroupManagerRequest", "DeletePerInstanceConfigsRegionInstanceGroupManagerRequest", @@ -1688,16 +1756,14 @@ "DiskInstantiationConfig", "DiskList", "DiskMoveRequest", - "DiskType", - "DiskTypeAggregatedList", - "DiskTypeList", - "DiskTypesClient", - "DiskTypesScopedList", "DisksAddResourcePoliciesRequest", - "DisksClient", "DisksRemoveResourcePoliciesRequest", "DisksResizeRequest", "DisksScopedList", + "DiskType", + "DiskTypeAggregatedList", + "DiskTypeList", + "DiskTypesScopedList", "DisplayDevice", "DistributionPolicy", "DistributionPolicyZoneConfiguration", @@ -1713,20 +1779,16 @@ "ExternalVpnGateway", "ExternalVpnGatewayInterface", "ExternalVpnGatewayList", - "ExternalVpnGatewaysClient", "FileContentBuffer", "Firewall", "FirewallList", "FirewallLogConfig", - "FirewallsClient", "FixedOrPercent", "ForwardingRule", "ForwardingRuleAggregatedList", "ForwardingRuleList", "ForwardingRuleReference", - "ForwardingRulesClient", "ForwardingRulesScopedList", - "GRPCHealthCheck", "GetAcceleratorTypeRequest", "GetAddressRequest", "GetAutoscalerRequest", @@ -1827,50 +1889,44 @@ "GetXpnResourcesProjectsRequest", "GetZoneOperationRequest", "GetZoneRequest", - "GlobalAddressesClient", - "GlobalForwardingRulesClient", "GlobalNetworkEndpointGroupsAttachEndpointsRequest", - "GlobalNetworkEndpointGroupsClient", "GlobalNetworkEndpointGroupsDetachEndpointsRequest", - "GlobalOperationsClient", - "GlobalOrganizationOperationsClient", "GlobalSetLabelsRequest", "GlobalSetPolicyRequest", + "GRPCHealthCheck", "GuestAttributes", "GuestAttributesEntry", "GuestAttributesValue", "GuestOsFeature", - "HTTP2HealthCheck", - "HTTPHealthCheck", - "HTTPSHealthCheck", "HealthCheck", "HealthCheckList", "HealthCheckLogConfig", "HealthCheckReference", + "HealthChecksAggregatedList", "HealthCheckService", "HealthCheckServiceReference", "HealthCheckServicesList", - "HealthChecksAggregatedList", - "HealthChecksClient", "HealthChecksScopedList", "HealthStatus", "HealthStatusForNetworkEndpoint", "HostRule", + "HTTP2HealthCheck", "HttpFaultAbort", "HttpFaultDelay", "HttpFaultInjection", "HttpHeaderAction", "HttpHeaderMatch", "HttpHeaderOption", + "HTTPHealthCheck", "HttpQueryParameterMatch", "HttpRedirectAction", "HttpRetryPolicy", "HttpRouteAction", "HttpRouteRule", "HttpRouteRuleMatch", + "HTTPSHealthCheck", "Image", "ImageList", - "ImagesClient", "InitialStateConfig", "InsertAddressRequest", "InsertAutoscalerRequest", @@ -1939,15 +1995,8 @@ "InstanceGroupManagerAggregatedList", "InstanceGroupManagerAutoHealingPolicy", "InstanceGroupManagerList", - "InstanceGroupManagerStatus", - "InstanceGroupManagerStatusStateful", - "InstanceGroupManagerStatusStatefulPerInstanceConfigs", - "InstanceGroupManagerStatusVersionTarget", - "InstanceGroupManagerUpdatePolicy", - "InstanceGroupManagerVersion", "InstanceGroupManagersAbandonInstancesRequest", "InstanceGroupManagersApplyUpdatesRequest", - "InstanceGroupManagersClient", "InstanceGroupManagersCreateInstancesRequest", "InstanceGroupManagersDeleteInstancesRequest", "InstanceGroupManagersDeletePerInstanceConfigsReq", @@ -1959,9 +2008,14 @@ "InstanceGroupManagersScopedList", "InstanceGroupManagersSetInstanceTemplateRequest", "InstanceGroupManagersSetTargetPoolsRequest", + "InstanceGroupManagerStatus", + "InstanceGroupManagerStatusStateful", + "InstanceGroupManagerStatusStatefulPerInstanceConfigs", + "InstanceGroupManagerStatusVersionTarget", "InstanceGroupManagersUpdatePerInstanceConfigsReq", + "InstanceGroupManagerUpdatePolicy", + "InstanceGroupManagerVersion", "InstanceGroupsAddInstancesRequest", - "InstanceGroupsClient", "InstanceGroupsListInstances", "InstanceGroupsListInstancesRequest", "InstanceGroupsRemoveInstancesRequest", @@ -1975,12 +2029,7 @@ "InstanceMoveRequest", "InstanceProperties", "InstanceReference", - "InstanceTemplate", - "InstanceTemplateList", - "InstanceTemplatesClient", - "InstanceWithNamedPorts", "InstancesAddResourcePoliciesRequest", - "InstancesClient", "InstancesRemoveResourcePoliciesRequest", "InstancesScopedList", "InstancesSetLabelsRequest", @@ -1989,6 +2038,9 @@ "InstancesSetMinCpuPlatformRequest", "InstancesSetServiceAccountRequest", "InstancesStartWithEncryptionKeyRequest", + "InstanceTemplate", + "InstanceTemplateList", + "InstanceWithNamedPorts", "Int64RangeMatch", "Interconnect", "InterconnectAttachment", @@ -1996,7 +2048,6 @@ "InterconnectAttachmentList", "InterconnectAttachmentPartnerMetadata", "InterconnectAttachmentPrivateInfo", - "InterconnectAttachmentsClient", "InterconnectAttachmentsScopedList", "InterconnectCircuitInfo", "InterconnectDiagnostics", @@ -2008,19 +2059,15 @@ "InterconnectLocation", "InterconnectLocationList", "InterconnectLocationRegionInfo", - "InterconnectLocationsClient", "InterconnectOutageNotification", - "InterconnectsClient", "InterconnectsGetDiagnosticsResponse", "InvalidateCacheUrlMapRequest", "Items", "License", "LicenseCode", "LicenseCodeLicenseAlias", - "LicenseCodesClient", "LicenseResourceCommitment", "LicenseResourceRequirements", - "LicensesClient", "LicensesListResponse", "ListAcceleratorTypesRequest", "ListAddressesRequest", @@ -2028,8 +2075,8 @@ "ListAvailableFeaturesSslPoliciesRequest", "ListBackendBucketsRequest", "ListBackendServicesRequest", - "ListDiskTypesRequest", "ListDisksRequest", + "ListDiskTypesRequest", "ListErrorsInstanceGroupManagersRequest", "ListErrorsRegionInstanceGroupManagersRequest", "ListExternalVpnGatewaysRequest", @@ -2044,10 +2091,10 @@ "ListImagesRequest", "ListInstanceGroupManagersRequest", "ListInstanceGroupsRequest", - "ListInstanceTemplatesRequest", "ListInstancesInstanceGroupsRequest", "ListInstancesRegionInstanceGroupsRequest", "ListInstancesRequest", + "ListInstanceTemplatesRequest", "ListInterconnectAttachmentsRequest", "ListInterconnectLocationsRequest", "ListInterconnectsRequest", @@ -2060,9 +2107,9 @@ "ListNetworkEndpointsNetworkEndpointGroupsRequest", "ListNetworksRequest", "ListNodeGroupsRequest", + "ListNodesNodeGroupsRequest", "ListNodeTemplatesRequest", "ListNodeTypesRequest", - "ListNodesNodeGroupsRequest", "ListPacketMirroringsRequest", "ListPeeringRoutesNetworksRequest", "ListPerInstanceConfigsInstanceGroupManagersRequest", @@ -2072,8 +2119,8 @@ "ListRegionAutoscalersRequest", "ListRegionBackendServicesRequest", "ListRegionCommitmentsRequest", - "ListRegionDiskTypesRequest", "ListRegionDisksRequest", + "ListRegionDiskTypesRequest", "ListRegionHealthCheckServicesRequest", "ListRegionHealthChecksRequest", "ListRegionInstanceGroupManagersRequest", @@ -2081,11 +2128,11 @@ "ListRegionNetworkEndpointGroupsRequest", "ListRegionNotificationEndpointsRequest", "ListRegionOperationsRequest", + "ListRegionsRequest", "ListRegionSslCertificatesRequest", "ListRegionTargetHttpProxiesRequest", "ListRegionTargetHttpsProxiesRequest", "ListRegionUrlMapsRequest", - "ListRegionsRequest", "ListReservationsRequest", "ListResourcePoliciesRequest", "ListRoutersRequest", @@ -2119,7 +2166,6 @@ "MachineType", "MachineTypeAggregatedList", "MachineTypeList", - "MachineTypesClient", "MachineTypesScopedList", "ManagedInstance", "ManagedInstanceInstanceHealth", @@ -2140,7 +2186,6 @@ "NetworkEndpointGroupCloudRun", "NetworkEndpointGroupList", "NetworkEndpointGroupsAttachEndpointsRequest", - "NetworkEndpointGroupsClient", "NetworkEndpointGroupsDetachEndpointsRequest", "NetworkEndpointGroupsListEndpointsRequest", "NetworkEndpointGroupsListNetworkEndpoints", @@ -2151,7 +2196,6 @@ "NetworkPeering", "NetworkRoutingConfig", "NetworksAddPeeringRequest", - "NetworksClient", "NetworksRemovePeeringRequest", "NetworksUpdatePeeringRequest", "NodeGroup", @@ -2161,7 +2205,6 @@ "NodeGroupMaintenanceWindow", "NodeGroupNode", "NodeGroupsAddNodesRequest", - "NodeGroupsClient", "NodeGroupsDeleteNodesRequest", "NodeGroupsListNodes", "NodeGroupsScopedList", @@ -2170,12 +2213,10 @@ "NodeTemplateAggregatedList", "NodeTemplateList", "NodeTemplateNodeTypeFlexibility", - "NodeTemplatesClient", "NodeTemplatesScopedList", "NodeType", "NodeTypeAggregatedList", "NodeTypeList", - "NodeTypesClient", "NodeTypesScopedList", "NotificationEndpoint", "NotificationEndpointGrpcSettings", @@ -2194,7 +2235,6 @@ "PacketMirroringMirroredResourceInfoInstanceInfo", "PacketMirroringMirroredResourceInfoSubnetInfo", "PacketMirroringNetworkInfo", - "PacketMirroringsClient", "PacketMirroringsScopedList", "PatchAutoscalerRequest", "PatchBackendBucketRequest", @@ -2235,7 +2275,6 @@ "PreservedStatePreservedDisk", "PreviewRouterRequest", "Project", - "ProjectsClient", "ProjectsDisableXpnResourceRequest", "ProjectsEnableXpnResourceRequest", "ProjectsGetXpnResources", @@ -2248,25 +2287,16 @@ "Reference", "Region", "RegionAutoscalerList", - "RegionAutoscalersClient", - "RegionBackendServicesClient", - "RegionCommitmentsClient", - "RegionDiskTypeList", - "RegionDiskTypesClient", "RegionDisksAddResourcePoliciesRequest", - "RegionDisksClient", "RegionDisksRemoveResourcePoliciesRequest", "RegionDisksResizeRequest", - "RegionHealthCheckServicesClient", - "RegionHealthChecksClient", + "RegionDiskTypeList", "RegionInstanceGroupList", "RegionInstanceGroupManagerDeleteInstanceConfigReq", "RegionInstanceGroupManagerList", "RegionInstanceGroupManagerPatchInstanceConfigReq", - "RegionInstanceGroupManagerUpdateInstanceConfigReq", "RegionInstanceGroupManagersAbandonInstancesRequest", "RegionInstanceGroupManagersApplyUpdatesRequest", - "RegionInstanceGroupManagersClient", "RegionInstanceGroupManagersCreateInstancesRequest", "RegionInstanceGroupManagersDeleteInstancesRequest", "RegionInstanceGroupManagersListErrorsResponse", @@ -2275,26 +2305,18 @@ "RegionInstanceGroupManagersRecreateRequest", "RegionInstanceGroupManagersSetTargetPoolsRequest", "RegionInstanceGroupManagersSetTemplateRequest", - "RegionInstanceGroupsClient", + "RegionInstanceGroupManagerUpdateInstanceConfigReq", "RegionInstanceGroupsListInstances", "RegionInstanceGroupsListInstancesRequest", "RegionInstanceGroupsSetNamedPortsRequest", "RegionList", - "RegionNetworkEndpointGroupsClient", - "RegionNotificationEndpointsClient", - "RegionOperationsClient", "RegionSetLabelsRequest", "RegionSetPolicyRequest", - "RegionSslCertificatesClient", - "RegionTargetHttpProxiesClient", - "RegionTargetHttpsProxiesClient", "RegionTargetHttpsProxiesSetSslCertificatesRequest", - "RegionUrlMapsClient", "RegionUrlMapsValidateRequest", - "RegionsClient", "RemoveHealthCheckTargetPoolRequest", - "RemoveInstanceTargetPoolRequest", "RemoveInstancesInstanceGroupRequest", + "RemoveInstanceTargetPoolRequest", "RemovePeeringNetworkRequest", "RemoveResourcePoliciesDiskRequest", "RemoveResourcePoliciesInstanceRequest", @@ -2305,7 +2327,6 @@ "ReservationAffinity", "ReservationAggregatedList", "ReservationList", - "ReservationsClient", "ReservationsResizeRequest", "ReservationsScopedList", "ResetInstanceRequest", @@ -2316,7 +2337,6 @@ "ResizeReservationRequest", "ResourceCommitment", "ResourceGroupReference", - "ResourcePoliciesClient", "ResourcePoliciesScopedList", "ResourcePolicy", "ResourcePolicyAggregatedList", @@ -2342,21 +2362,17 @@ "RouterNat", "RouterNatLogConfig", "RouterNatSubnetworkToNat", + "RoutersPreviewResponse", + "RoutersScopedList", "RouterStatus", "RouterStatusBgpPeerStatus", "RouterStatusNatStatus", "RouterStatusResponse", - "RoutersClient", - "RoutersPreviewResponse", - "RoutersScopedList", - "RoutesClient", "Rule", - "SSLHealthCheck", "Scheduling", "SchedulingNodeAffinity", "ScratchDisks", "Screenshot", - "SecurityPoliciesClient", "SecurityPoliciesListPreconfiguredExpressionSetsResponse", "SecurityPoliciesWafConfig", "SecurityPolicy", @@ -2435,16 +2451,14 @@ "SimulateMaintenanceEventInstanceRequest", "Snapshot", "SnapshotList", - "SnapshotsClient", "SourceInstanceParams", "SslCertificate", "SslCertificateAggregatedList", "SslCertificateList", "SslCertificateManagedSslCertificate", "SslCertificateSelfManagedSslCertificate", - "SslCertificatesClient", "SslCertificatesScopedList", - "SslPoliciesClient", + "SSLHealthCheck", "SslPoliciesList", "SslPoliciesListAvailableFeaturesResponse", "SslPolicy", @@ -2460,22 +2474,17 @@ "SubnetworkList", "SubnetworkLogConfig", "SubnetworkSecondaryRange", - "SubnetworksClient", "SubnetworksExpandIpCidrRangeRequest", "SubnetworksScopedList", "SubnetworksSetPrivateIpGoogleAccessRequest", "SwitchToCustomModeNetworkRequest", - "TCPHealthCheck", "Tags", - "TargetGrpcProxiesClient", "TargetGrpcProxy", "TargetGrpcProxyList", - "TargetHttpProxiesClient", "TargetHttpProxiesScopedList", "TargetHttpProxy", "TargetHttpProxyAggregatedList", "TargetHttpProxyList", - "TargetHttpsProxiesClient", "TargetHttpsProxiesScopedList", "TargetHttpsProxiesSetQuicOverrideRequest", "TargetHttpsProxiesSetSslCertificatesRequest", @@ -2485,7 +2494,6 @@ "TargetInstance", "TargetInstanceAggregatedList", "TargetInstanceList", - "TargetInstancesClient", "TargetInstancesScopedList", "TargetPool", "TargetPoolAggregatedList", @@ -2493,18 +2501,15 @@ "TargetPoolList", "TargetPoolsAddHealthCheckRequest", "TargetPoolsAddInstanceRequest", - "TargetPoolsClient", "TargetPoolsRemoveHealthCheckRequest", "TargetPoolsRemoveInstanceRequest", "TargetPoolsScopedList", "TargetReference", - "TargetSslProxiesClient", "TargetSslProxiesSetBackendServiceRequest", "TargetSslProxiesSetProxyHeaderRequest", "TargetSslProxiesSetSslCertificatesRequest", "TargetSslProxy", "TargetSslProxyList", - "TargetTcpProxiesClient", "TargetTcpProxiesSetBackendServiceRequest", "TargetTcpProxiesSetProxyHeaderRequest", "TargetTcpProxy", @@ -2512,8 +2517,8 @@ "TargetVpnGateway", "TargetVpnGatewayAggregatedList", "TargetVpnGatewayList", - "TargetVpnGatewaysClient", "TargetVpnGatewaysScopedList", + "TCPHealthCheck", "TestFailure", "TestIamPermissionsDiskRequest", "TestIamPermissionsExternalVpnGatewayRequest", @@ -2556,17 +2561,16 @@ "UrlMap", "UrlMapList", "UrlMapReference", - "UrlMapTest", - "UrlMapValidationResult", "UrlMapsAggregatedList", - "UrlMapsClient", "UrlMapsScopedList", "UrlMapsValidateRequest", "UrlMapsValidateResponse", + "UrlMapTest", + "UrlMapValidationResult", "UrlRewrite", "UsableSubnetwork", - "UsableSubnetworkSecondaryRange", "UsableSubnetworksAggregatedList", + "UsableSubnetworkSecondaryRange", "UsageExportLocation", "ValidateRegionUrlMapRequest", "ValidateUrlMapRequest", @@ -2576,18 +2580,16 @@ "VpnGateway", "VpnGatewayAggregatedList", "VpnGatewayList", + "VpnGatewaysGetStatusResponse", + "VpnGatewaysScopedList", "VpnGatewayStatus", "VpnGatewayStatusHighAvailabilityRequirementState", "VpnGatewayStatusTunnel", "VpnGatewayStatusVpnConnection", "VpnGatewayVpnGatewayInterface", - "VpnGatewaysClient", - "VpnGatewaysGetStatusResponse", - "VpnGatewaysScopedList", "VpnTunnel", "VpnTunnelAggregatedList", "VpnTunnelList", - "VpnTunnelsClient", "VpnTunnelsScopedList", "WafExpressionSet", "WafExpressionSetExpression", @@ -2601,8 +2603,6 @@ "XpnResourceId", "Zone", "ZoneList", - "ZoneOperationsClient", "ZoneSetLabelsRequest", "ZoneSetPolicyRequest", - "ZonesClient", ) diff --git a/google/cloud/compute_v1/__init__.py b/google/cloud/compute_v1/__init__.py index 6dc538398..57a5c4771 100644 --- a/google/cloud/compute_v1/__init__.py +++ b/google/cloud/compute_v1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -20,8 +19,8 @@ from .services.autoscalers import AutoscalersClient from .services.backend_buckets import BackendBucketsClient from .services.backend_services import BackendServicesClient -from .services.disk_types import DiskTypesClient from .services.disks import DisksClient +from .services.disk_types import DiskTypesClient from .services.external_vpn_gateways import ExternalVpnGatewaysClient from .services.firewalls import FirewallsClient from .services.forwarding_rules import ForwardingRulesClient @@ -34,8 +33,8 @@ from .services.images import ImagesClient from .services.instance_group_managers import InstanceGroupManagersClient from .services.instance_groups import InstanceGroupsClient -from .services.instance_templates import InstanceTemplatesClient from .services.instances import InstancesClient +from .services.instance_templates import InstanceTemplatesClient from .services.interconnect_attachments import InterconnectAttachmentsClient from .services.interconnect_locations import InterconnectLocationsClient from .services.interconnects import InterconnectsClient @@ -52,20 +51,20 @@ from .services.region_autoscalers import RegionAutoscalersClient from .services.region_backend_services import RegionBackendServicesClient from .services.region_commitments import RegionCommitmentsClient -from .services.region_disk_types import RegionDiskTypesClient from .services.region_disks import RegionDisksClient -from .services.region_health_check_services import RegionHealthCheckServicesClient +from .services.region_disk_types import RegionDiskTypesClient from .services.region_health_checks import RegionHealthChecksClient +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_network_endpoint_groups import RegionNetworkEndpointGroupsClient from .services.region_notification_endpoints import RegionNotificationEndpointsClient from .services.region_operations import RegionOperationsClient +from .services.regions import RegionsClient from .services.region_ssl_certificates import RegionSslCertificatesClient from .services.region_target_http_proxies import RegionTargetHttpProxiesClient from .services.region_target_https_proxies import RegionTargetHttpsProxiesClient from .services.region_url_maps import RegionUrlMapsClient -from .services.regions import RegionsClient from .services.reservations import ReservationsClient from .services.resource_policies import ResourcePoliciesClient from .services.routers import RoutersClient @@ -88,37 +87,38 @@ from .services.vpn_tunnels import VpnTunnelsClient from .services.zone_operations import ZoneOperationsClient from .services.zones import ZonesClient + from .types.compute import AbandonInstancesInstanceGroupManagerRequest from .types.compute import AbandonInstancesRegionInstanceGroupManagerRequest from .types.compute import AcceleratorConfig +from .types.compute import Accelerators from .types.compute import AcceleratorType from .types.compute import AcceleratorTypeAggregatedList from .types.compute import AcceleratorTypeList from .types.compute import AcceleratorTypesScopedList -from .types.compute import Accelerators from .types.compute import AccessConfig from .types.compute import AddAccessConfigInstanceRequest from .types.compute import AddHealthCheckTargetPoolRequest -from .types.compute import AddInstanceTargetPoolRequest from .types.compute import AddInstancesInstanceGroupRequest +from .types.compute import AddInstanceTargetPoolRequest from .types.compute import AddNodesNodeGroupRequest from .types.compute import AddPeeringNetworkRequest from .types.compute import AddResourcePoliciesDiskRequest from .types.compute import AddResourcePoliciesInstanceRequest from .types.compute import AddResourcePoliciesRegionDiskRequest -from .types.compute import AddRuleSecurityPolicyRequest -from .types.compute import AddSignedUrlKeyBackendBucketRequest -from .types.compute import AddSignedUrlKeyBackendServiceRequest from .types.compute import Address from .types.compute import AddressAggregatedList -from .types.compute import AddressList from .types.compute import AddressesScopedList +from .types.compute import AddressList +from .types.compute import AddRuleSecurityPolicyRequest +from .types.compute import AddSignedUrlKeyBackendBucketRequest +from .types.compute import AddSignedUrlKeyBackendServiceRequest from .types.compute import AggregatedListAcceleratorTypesRequest from .types.compute import AggregatedListAddressesRequest from .types.compute import AggregatedListAutoscalersRequest from .types.compute import AggregatedListBackendServicesRequest -from .types.compute import AggregatedListDiskTypesRequest from .types.compute import AggregatedListDisksRequest +from .types.compute import AggregatedListDiskTypesRequest from .types.compute import AggregatedListForwardingRulesRequest from .types.compute import AggregatedListGlobalOperationsRequest from .types.compute import AggregatedListHealthChecksRequest @@ -156,18 +156,18 @@ from .types.compute import ApplyUpdatesToInstancesInstanceGroupManagerRequest from .types.compute import ApplyUpdatesToInstancesRegionInstanceGroupManagerRequest from .types.compute import AttachDiskInstanceRequest -from .types.compute import AttachNetworkEndpointsGlobalNetworkEndpointGroupRequest -from .types.compute import AttachNetworkEndpointsNetworkEndpointGroupRequest from .types.compute import AttachedDisk from .types.compute import AttachedDiskInitializeParams +from .types.compute import AttachNetworkEndpointsGlobalNetworkEndpointGroupRequest +from .types.compute import AttachNetworkEndpointsNetworkEndpointGroupRequest from .types.compute import AuditConfig from .types.compute import AuditLogConfig from .types.compute import AuthorizationLoggingOptions from .types.compute import Autoscaler from .types.compute import AutoscalerAggregatedList from .types.compute import AutoscalerList -from .types.compute import AutoscalerStatusDetails from .types.compute import AutoscalersScopedList +from .types.compute import AutoscalerStatusDetails from .types.compute import AutoscalingPolicy from .types.compute import AutoscalingPolicyCpuUtilization from .types.compute import AutoscalingPolicyCustomMetricUtilization @@ -229,17 +229,17 @@ from .types.compute import DeleteInstanceGroupManagerRequest from .types.compute import DeleteInstanceGroupRequest from .types.compute import DeleteInstanceRequest -from .types.compute import DeleteInstanceTemplateRequest from .types.compute import DeleteInstancesInstanceGroupManagerRequest from .types.compute import DeleteInstancesRegionInstanceGroupManagerRequest +from .types.compute import DeleteInstanceTemplateRequest from .types.compute import DeleteInterconnectAttachmentRequest from .types.compute import DeleteInterconnectRequest from .types.compute import DeleteLicenseRequest from .types.compute import DeleteNetworkEndpointGroupRequest from .types.compute import DeleteNetworkRequest from .types.compute import DeleteNodeGroupRequest -from .types.compute import DeleteNodeTemplateRequest from .types.compute import DeleteNodesNodeGroupRequest +from .types.compute import DeleteNodeTemplateRequest from .types.compute import DeletePacketMirroringRequest from .types.compute import DeletePerInstanceConfigsInstanceGroupManagerRequest from .types.compute import DeletePerInstanceConfigsRegionInstanceGroupManagerRequest @@ -294,14 +294,14 @@ from .types.compute import DiskInstantiationConfig from .types.compute import DiskList from .types.compute import DiskMoveRequest -from .types.compute import DiskType -from .types.compute import DiskTypeAggregatedList -from .types.compute import DiskTypeList -from .types.compute import DiskTypesScopedList from .types.compute import DisksAddResourcePoliciesRequest from .types.compute import DisksRemoveResourcePoliciesRequest from .types.compute import DisksResizeRequest from .types.compute import DisksScopedList +from .types.compute import DiskType +from .types.compute import DiskTypeAggregatedList +from .types.compute import DiskTypeList +from .types.compute import DiskTypesScopedList from .types.compute import DisplayDevice from .types.compute import DistributionPolicy from .types.compute import DistributionPolicyZoneConfiguration @@ -327,7 +327,6 @@ from .types.compute import ForwardingRuleList from .types.compute import ForwardingRuleReference from .types.compute import ForwardingRulesScopedList -from .types.compute import GRPCHealthCheck from .types.compute import GetAcceleratorTypeRequest from .types.compute import GetAddressRequest from .types.compute import GetAutoscalerRequest @@ -432,37 +431,38 @@ from .types.compute import GlobalNetworkEndpointGroupsDetachEndpointsRequest from .types.compute import GlobalSetLabelsRequest from .types.compute import GlobalSetPolicyRequest +from .types.compute import GRPCHealthCheck from .types.compute import GuestAttributes from .types.compute import GuestAttributesEntry from .types.compute import GuestAttributesValue from .types.compute import GuestOsFeature -from .types.compute import HTTP2HealthCheck -from .types.compute import HTTPHealthCheck -from .types.compute import HTTPSHealthCheck from .types.compute import HealthCheck from .types.compute import HealthCheckList from .types.compute import HealthCheckLogConfig from .types.compute import HealthCheckReference +from .types.compute import HealthChecksAggregatedList from .types.compute import HealthCheckService from .types.compute import HealthCheckServiceReference from .types.compute import HealthCheckServicesList -from .types.compute import HealthChecksAggregatedList from .types.compute import HealthChecksScopedList from .types.compute import HealthStatus from .types.compute import HealthStatusForNetworkEndpoint from .types.compute import HostRule +from .types.compute import HTTP2HealthCheck from .types.compute import HttpFaultAbort from .types.compute import HttpFaultDelay from .types.compute import HttpFaultInjection from .types.compute import HttpHeaderAction from .types.compute import HttpHeaderMatch from .types.compute import HttpHeaderOption +from .types.compute import HTTPHealthCheck from .types.compute import HttpQueryParameterMatch from .types.compute import HttpRedirectAction from .types.compute import HttpRetryPolicy from .types.compute import HttpRouteAction from .types.compute import HttpRouteRule from .types.compute import HttpRouteRuleMatch +from .types.compute import HTTPSHealthCheck from .types.compute import Image from .types.compute import ImageList from .types.compute import InitialStateConfig @@ -533,12 +533,6 @@ from .types.compute import InstanceGroupManagerAggregatedList from .types.compute import InstanceGroupManagerAutoHealingPolicy from .types.compute import InstanceGroupManagerList -from .types.compute import InstanceGroupManagerStatus -from .types.compute import InstanceGroupManagerStatusStateful -from .types.compute import InstanceGroupManagerStatusStatefulPerInstanceConfigs -from .types.compute import InstanceGroupManagerStatusVersionTarget -from .types.compute import InstanceGroupManagerUpdatePolicy -from .types.compute import InstanceGroupManagerVersion from .types.compute import InstanceGroupManagersAbandonInstancesRequest from .types.compute import InstanceGroupManagersApplyUpdatesRequest from .types.compute import InstanceGroupManagersCreateInstancesRequest @@ -552,7 +546,13 @@ from .types.compute import InstanceGroupManagersScopedList from .types.compute import InstanceGroupManagersSetInstanceTemplateRequest from .types.compute import InstanceGroupManagersSetTargetPoolsRequest +from .types.compute import InstanceGroupManagerStatus +from .types.compute import InstanceGroupManagerStatusStateful +from .types.compute import InstanceGroupManagerStatusStatefulPerInstanceConfigs +from .types.compute import InstanceGroupManagerStatusVersionTarget from .types.compute import InstanceGroupManagersUpdatePerInstanceConfigsReq +from .types.compute import InstanceGroupManagerUpdatePolicy +from .types.compute import InstanceGroupManagerVersion from .types.compute import InstanceGroupsAddInstancesRequest from .types.compute import InstanceGroupsListInstances from .types.compute import InstanceGroupsListInstancesRequest @@ -567,9 +567,6 @@ from .types.compute import InstanceMoveRequest from .types.compute import InstanceProperties from .types.compute import InstanceReference -from .types.compute import InstanceTemplate -from .types.compute import InstanceTemplateList -from .types.compute import InstanceWithNamedPorts from .types.compute import InstancesAddResourcePoliciesRequest from .types.compute import InstancesRemoveResourcePoliciesRequest from .types.compute import InstancesScopedList @@ -579,6 +576,9 @@ from .types.compute import InstancesSetMinCpuPlatformRequest from .types.compute import InstancesSetServiceAccountRequest from .types.compute import InstancesStartWithEncryptionKeyRequest +from .types.compute import InstanceTemplate +from .types.compute import InstanceTemplateList +from .types.compute import InstanceWithNamedPorts from .types.compute import Int64RangeMatch from .types.compute import Interconnect from .types.compute import InterconnectAttachment @@ -613,8 +613,8 @@ from .types.compute import ListAvailableFeaturesSslPoliciesRequest from .types.compute import ListBackendBucketsRequest from .types.compute import ListBackendServicesRequest -from .types.compute import ListDiskTypesRequest from .types.compute import ListDisksRequest +from .types.compute import ListDiskTypesRequest from .types.compute import ListErrorsInstanceGroupManagersRequest from .types.compute import ListErrorsRegionInstanceGroupManagersRequest from .types.compute import ListExternalVpnGatewaysRequest @@ -629,10 +629,10 @@ from .types.compute import ListImagesRequest from .types.compute import ListInstanceGroupManagersRequest from .types.compute import ListInstanceGroupsRequest -from .types.compute import ListInstanceTemplatesRequest from .types.compute import ListInstancesInstanceGroupsRequest from .types.compute import ListInstancesRegionInstanceGroupsRequest from .types.compute import ListInstancesRequest +from .types.compute import ListInstanceTemplatesRequest from .types.compute import ListInterconnectAttachmentsRequest from .types.compute import ListInterconnectLocationsRequest from .types.compute import ListInterconnectsRequest @@ -645,9 +645,9 @@ from .types.compute import ListNetworkEndpointsNetworkEndpointGroupsRequest from .types.compute import ListNetworksRequest from .types.compute import ListNodeGroupsRequest +from .types.compute import ListNodesNodeGroupsRequest from .types.compute import ListNodeTemplatesRequest from .types.compute import ListNodeTypesRequest -from .types.compute import ListNodesNodeGroupsRequest from .types.compute import ListPacketMirroringsRequest from .types.compute import ListPeeringRoutesNetworksRequest from .types.compute import ListPerInstanceConfigsInstanceGroupManagersRequest @@ -657,8 +657,8 @@ from .types.compute import ListRegionAutoscalersRequest from .types.compute import ListRegionBackendServicesRequest from .types.compute import ListRegionCommitmentsRequest -from .types.compute import ListRegionDiskTypesRequest from .types.compute import ListRegionDisksRequest +from .types.compute import ListRegionDiskTypesRequest from .types.compute import ListRegionHealthCheckServicesRequest from .types.compute import ListRegionHealthChecksRequest from .types.compute import ListRegionInstanceGroupManagersRequest @@ -666,11 +666,11 @@ from .types.compute import ListRegionNetworkEndpointGroupsRequest from .types.compute import ListRegionNotificationEndpointsRequest from .types.compute import ListRegionOperationsRequest +from .types.compute import ListRegionsRequest from .types.compute import ListRegionSslCertificatesRequest from .types.compute import ListRegionTargetHttpProxiesRequest from .types.compute import ListRegionTargetHttpsProxiesRequest from .types.compute import ListRegionUrlMapsRequest -from .types.compute import ListRegionsRequest from .types.compute import ListReservationsRequest from .types.compute import ListResourcePoliciesRequest from .types.compute import ListRoutersRequest @@ -825,15 +825,14 @@ from .types.compute import Reference from .types.compute import Region from .types.compute import RegionAutoscalerList -from .types.compute import RegionDiskTypeList from .types.compute import RegionDisksAddResourcePoliciesRequest from .types.compute import RegionDisksRemoveResourcePoliciesRequest from .types.compute import RegionDisksResizeRequest +from .types.compute import RegionDiskTypeList from .types.compute import RegionInstanceGroupList from .types.compute import RegionInstanceGroupManagerDeleteInstanceConfigReq from .types.compute import RegionInstanceGroupManagerList from .types.compute import RegionInstanceGroupManagerPatchInstanceConfigReq -from .types.compute import RegionInstanceGroupManagerUpdateInstanceConfigReq from .types.compute import RegionInstanceGroupManagersAbandonInstancesRequest from .types.compute import RegionInstanceGroupManagersApplyUpdatesRequest from .types.compute import RegionInstanceGroupManagersCreateInstancesRequest @@ -844,6 +843,7 @@ from .types.compute import RegionInstanceGroupManagersRecreateRequest from .types.compute import RegionInstanceGroupManagersSetTargetPoolsRequest from .types.compute import RegionInstanceGroupManagersSetTemplateRequest +from .types.compute import RegionInstanceGroupManagerUpdateInstanceConfigReq from .types.compute import RegionInstanceGroupsListInstances from .types.compute import RegionInstanceGroupsListInstancesRequest from .types.compute import RegionInstanceGroupsSetNamedPortsRequest @@ -853,8 +853,8 @@ from .types.compute import RegionTargetHttpsProxiesSetSslCertificatesRequest from .types.compute import RegionUrlMapsValidateRequest from .types.compute import RemoveHealthCheckTargetPoolRequest -from .types.compute import RemoveInstanceTargetPoolRequest from .types.compute import RemoveInstancesInstanceGroupRequest +from .types.compute import RemoveInstanceTargetPoolRequest from .types.compute import RemovePeeringNetworkRequest from .types.compute import RemoveResourcePoliciesDiskRequest from .types.compute import RemoveResourcePoliciesInstanceRequest @@ -900,14 +900,13 @@ from .types.compute import RouterNat from .types.compute import RouterNatLogConfig from .types.compute import RouterNatSubnetworkToNat +from .types.compute import RoutersPreviewResponse +from .types.compute import RoutersScopedList from .types.compute import RouterStatus from .types.compute import RouterStatusBgpPeerStatus from .types.compute import RouterStatusNatStatus from .types.compute import RouterStatusResponse -from .types.compute import RoutersPreviewResponse -from .types.compute import RoutersScopedList from .types.compute import Rule -from .types.compute import SSLHealthCheck from .types.compute import Scheduling from .types.compute import SchedulingNodeAffinity from .types.compute import ScratchDisks @@ -997,6 +996,7 @@ from .types.compute import SslCertificateManagedSslCertificate from .types.compute import SslCertificateSelfManagedSslCertificate from .types.compute import SslCertificatesScopedList +from .types.compute import SSLHealthCheck from .types.compute import SslPoliciesList from .types.compute import SslPoliciesListAvailableFeaturesResponse from .types.compute import SslPolicy @@ -1016,7 +1016,6 @@ from .types.compute import SubnetworksScopedList from .types.compute import SubnetworksSetPrivateIpGoogleAccessRequest from .types.compute import SwitchToCustomModeNetworkRequest -from .types.compute import TCPHealthCheck from .types.compute import Tags from .types.compute import TargetGrpcProxy from .types.compute import TargetGrpcProxyList @@ -1057,6 +1056,7 @@ from .types.compute import TargetVpnGatewayAggregatedList from .types.compute import TargetVpnGatewayList from .types.compute import TargetVpnGatewaysScopedList +from .types.compute import TCPHealthCheck from .types.compute import TestFailure from .types.compute import TestIamPermissionsDiskRequest from .types.compute import TestIamPermissionsExternalVpnGatewayRequest @@ -1099,16 +1099,16 @@ from .types.compute import UrlMap from .types.compute import UrlMapList from .types.compute import UrlMapReference -from .types.compute import UrlMapTest -from .types.compute import UrlMapValidationResult from .types.compute import UrlMapsAggregatedList from .types.compute import UrlMapsScopedList from .types.compute import UrlMapsValidateRequest from .types.compute import UrlMapsValidateResponse +from .types.compute import UrlMapTest +from .types.compute import UrlMapValidationResult from .types.compute import UrlRewrite from .types.compute import UsableSubnetwork -from .types.compute import UsableSubnetworkSecondaryRange from .types.compute import UsableSubnetworksAggregatedList +from .types.compute import UsableSubnetworkSecondaryRange from .types.compute import UsageExportLocation from .types.compute import ValidateRegionUrlMapRequest from .types.compute import ValidateUrlMapRequest @@ -1118,13 +1118,13 @@ from .types.compute import VpnGateway from .types.compute import VpnGatewayAggregatedList from .types.compute import VpnGatewayList +from .types.compute import VpnGatewaysGetStatusResponse +from .types.compute import VpnGatewaysScopedList from .types.compute import VpnGatewayStatus from .types.compute import VpnGatewayStatusHighAvailabilityRequirementState from .types.compute import VpnGatewayStatusTunnel from .types.compute import VpnGatewayStatusVpnConnection from .types.compute import VpnGatewayVpnGatewayInterface -from .types.compute import VpnGatewaysGetStatusResponse -from .types.compute import VpnGatewaysScopedList from .types.compute import VpnTunnel from .types.compute import VpnTunnelAggregatedList from .types.compute import VpnTunnelList @@ -1144,7 +1144,6 @@ from .types.compute import ZoneSetLabelsRequest from .types.compute import ZoneSetPolicyRequest - __all__ = ( "AbandonInstancesInstanceGroupManagerRequest", "AbandonInstancesRegionInstanceGroupManagerRequest", @@ -1497,6 +1496,7 @@ "GlobalAddressesClient", "GlobalForwardingRulesClient", "GlobalNetworkEndpointGroupsAttachEndpointsRequest", + "GlobalNetworkEndpointGroupsClient", "GlobalNetworkEndpointGroupsDetachEndpointsRequest", "GlobalOperationsClient", "GlobalOrganizationOperationsClient", @@ -2271,5 +2271,4 @@ "ZoneSetLabelsRequest", "ZoneSetPolicyRequest", "ZonesClient", - "GlobalNetworkEndpointGroupsClient", ) diff --git a/google/cloud/compute_v1/gapic_metadata.json b/google/cloud/compute_v1/gapic_metadata.json new file mode 100644 index 000000000..debcc74b0 --- /dev/null +++ b/google/cloud/compute_v1/gapic_metadata.json @@ -0,0 +1,3331 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.compute_v1", + "protoPackage": "google.cloud.compute.v1", + "schema": "1.0", + "services": { + "AcceleratorTypes": { + "clients": { + "rest": { + "libraryClient": "AcceleratorTypesClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "List": { + "methods": [ + "list" + ] + } + } + } + } + }, + "Addresses": { + "clients": { + "rest": { + "libraryClient": "AddressesClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + } + } + } + } + }, + "Autoscalers": { + "clients": { + "rest": { + "libraryClient": "AutoscalersClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + }, + "Update": { + "methods": [ + "update" + ] + } + } + } + } + }, + "BackendBuckets": { + "clients": { + "rest": { + "libraryClient": "BackendBucketsClient", + "rpcs": { + "AddSignedUrlKey": { + "methods": [ + "add_signed_url_key" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "DeleteSignedUrlKey": { + "methods": [ + "delete_signed_url_key" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + }, + "Update": { + "methods": [ + "update" + ] + } + } + } + } + }, + "BackendServices": { + "clients": { + "rest": { + "libraryClient": "BackendServicesClient", + "rpcs": { + "AddSignedUrlKey": { + "methods": [ + "add_signed_url_key" + ] + }, + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "DeleteSignedUrlKey": { + "methods": [ + "delete_signed_url_key" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetHealth": { + "methods": [ + "get_health" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + }, + "SetSecurityPolicy": { + "methods": [ + "set_security_policy" + ] + }, + "Update": { + "methods": [ + "update" + ] + } + } + } + } + }, + "DiskTypes": { + "clients": { + "rest": { + "libraryClient": "DiskTypesClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "List": { + "methods": [ + "list" + ] + } + } + } + } + }, + "Disks": { + "clients": { + "rest": { + "libraryClient": "DisksClient", + "rpcs": { + "AddResourcePolicies": { + "methods": [ + "add_resource_policies" + ] + }, + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "CreateSnapshot": { + "methods": [ + "create_snapshot" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "RemoveResourcePolicies": { + "methods": [ + "remove_resource_policies" + ] + }, + "Resize": { + "methods": [ + "resize" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "SetLabels": { + "methods": [ + "set_labels" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + } + } + } + } + }, + "ExternalVpnGateways": { + "clients": { + "rest": { + "libraryClient": "ExternalVpnGatewaysClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "SetLabels": { + "methods": [ + "set_labels" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + } + } + } + } + }, + "Firewalls": { + "clients": { + "rest": { + "libraryClient": "FirewallsClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + }, + "Update": { + "methods": [ + "update" + ] + } + } + } + } + }, + "ForwardingRules": { + "clients": { + "rest": { + "libraryClient": "ForwardingRulesClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + }, + "SetTarget": { + "methods": [ + "set_target" + ] + } + } + } + } + }, + "GlobalAddresses": { + "clients": { + "rest": { + "libraryClient": "GlobalAddressesClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + } + } + } + } + }, + "GlobalForwardingRules": { + "clients": { + "rest": { + "libraryClient": "GlobalForwardingRulesClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + }, + "SetTarget": { + "methods": [ + "set_target" + ] + } + } + } + } + }, + "GlobalNetworkEndpointGroups": { + "clients": { + "rest": { + "libraryClient": "GlobalNetworkEndpointGroupsClient", + "rpcs": { + "AttachNetworkEndpoints": { + "methods": [ + "attach_network_endpoints" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "DetachNetworkEndpoints": { + "methods": [ + "detach_network_endpoints" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "ListNetworkEndpoints": { + "methods": [ + "list_network_endpoints" + ] + } + } + } + } + }, + "GlobalOperations": { + "clients": { + "rest": { + "libraryClient": "GlobalOperationsClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Wait": { + "methods": [ + "wait" + ] + } + } + } + } + }, + "GlobalOrganizationOperations": { + "clients": { + "rest": { + "libraryClient": "GlobalOrganizationOperationsClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "List": { + "methods": [ + "list" + ] + } + } + } + } + }, + "HealthChecks": { + "clients": { + "rest": { + "libraryClient": "HealthChecksClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + }, + "Update": { + "methods": [ + "update" + ] + } + } + } + } + }, + "Images": { + "clients": { + "rest": { + "libraryClient": "ImagesClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Deprecate": { + "methods": [ + "deprecate" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetFromFamily": { + "methods": [ + "get_from_family" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "SetLabels": { + "methods": [ + "set_labels" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + } + } + } + } + }, + "InstanceGroupManagers": { + "clients": { + "rest": { + "libraryClient": "InstanceGroupManagersClient", + "rpcs": { + "AbandonInstances": { + "methods": [ + "abandon_instances" + ] + }, + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "ApplyUpdatesToInstances": { + "methods": [ + "apply_updates_to_instances" + ] + }, + "CreateInstances": { + "methods": [ + "create_instances" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "DeleteInstances": { + "methods": [ + "delete_instances" + ] + }, + "DeletePerInstanceConfigs": { + "methods": [ + "delete_per_instance_configs" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "ListErrors": { + "methods": [ + "list_errors" + ] + }, + "ListManagedInstances": { + "methods": [ + "list_managed_instances" + ] + }, + "ListPerInstanceConfigs": { + "methods": [ + "list_per_instance_configs" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + }, + "PatchPerInstanceConfigs": { + "methods": [ + "patch_per_instance_configs" + ] + }, + "RecreateInstances": { + "methods": [ + "recreate_instances" + ] + }, + "Resize": { + "methods": [ + "resize" + ] + }, + "SetInstanceTemplate": { + "methods": [ + "set_instance_template" + ] + }, + "SetTargetPools": { + "methods": [ + "set_target_pools" + ] + }, + "UpdatePerInstanceConfigs": { + "methods": [ + "update_per_instance_configs" + ] + } + } + } + } + }, + "InstanceGroups": { + "clients": { + "rest": { + "libraryClient": "InstanceGroupsClient", + "rpcs": { + "AddInstances": { + "methods": [ + "add_instances" + ] + }, + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + }, + "RemoveInstances": { + "methods": [ + "remove_instances" + ] + }, + "SetNamedPorts": { + "methods": [ + "set_named_ports" + ] + } + } + } + } + }, + "InstanceTemplates": { + "clients": { + "rest": { + "libraryClient": "InstanceTemplatesClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + } + } + } + } + }, + "Instances": { + "clients": { + "rest": { + "libraryClient": "InstancesClient", + "rpcs": { + "AddAccessConfig": { + "methods": [ + "add_access_config" + ] + }, + "AddResourcePolicies": { + "methods": [ + "add_resource_policies" + ] + }, + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "AttachDisk": { + "methods": [ + "attach_disk" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "DeleteAccessConfig": { + "methods": [ + "delete_access_config" + ] + }, + "DetachDisk": { + "methods": [ + "detach_disk" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetGuestAttributes": { + "methods": [ + "get_guest_attributes" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetScreenshot": { + "methods": [ + "get_screenshot" + ] + }, + "GetSerialPortOutput": { + "methods": [ + "get_serial_port_output" + ] + }, + "GetShieldedInstanceIdentity": { + "methods": [ + "get_shielded_instance_identity" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "ListReferrers": { + "methods": [ + "list_referrers" + ] + }, + "RemoveResourcePolicies": { + "methods": [ + "remove_resource_policies" + ] + }, + "Reset": { + "methods": [ + "reset" + ] + }, + "SetDeletionProtection": { + "methods": [ + "set_deletion_protection" + ] + }, + "SetDiskAutoDelete": { + "methods": [ + "set_disk_auto_delete" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "SetLabels": { + "methods": [ + "set_labels" + ] + }, + "SetMachineResources": { + "methods": [ + "set_machine_resources" + ] + }, + "SetMachineType": { + "methods": [ + "set_machine_type" + ] + }, + "SetMetadata": { + "methods": [ + "set_metadata" + ] + }, + "SetMinCpuPlatform": { + "methods": [ + "set_min_cpu_platform" + ] + }, + "SetScheduling": { + "methods": [ + "set_scheduling" + ] + }, + "SetServiceAccount": { + "methods": [ + "set_service_account" + ] + }, + "SetShieldedInstanceIntegrityPolicy": { + "methods": [ + "set_shielded_instance_integrity_policy" + ] + }, + "SetTags": { + "methods": [ + "set_tags" + ] + }, + "SimulateMaintenanceEvent": { + "methods": [ + "simulate_maintenance_event" + ] + }, + "Start": { + "methods": [ + "start" + ] + }, + "StartWithEncryptionKey": { + "methods": [ + "start_with_encryption_key" + ] + }, + "Stop": { + "methods": [ + "stop" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "Update": { + "methods": [ + "update" + ] + }, + "UpdateAccessConfig": { + "methods": [ + "update_access_config" + ] + }, + "UpdateDisplayDevice": { + "methods": [ + "update_display_device" + ] + }, + "UpdateNetworkInterface": { + "methods": [ + "update_network_interface" + ] + }, + "UpdateShieldedInstanceConfig": { + "methods": [ + "update_shielded_instance_config" + ] + } + } + } + } + }, + "InterconnectAttachments": { + "clients": { + "rest": { + "libraryClient": "InterconnectAttachmentsClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + } + } + } + } + }, + "InterconnectLocations": { + "clients": { + "rest": { + "libraryClient": "InterconnectLocationsClient", + "rpcs": { + "Get": { + "methods": [ + "get" + ] + }, + "List": { + "methods": [ + "list" + ] + } + } + } + } + }, + "Interconnects": { + "clients": { + "rest": { + "libraryClient": "InterconnectsClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetDiagnostics": { + "methods": [ + "get_diagnostics" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + } + } + } + } + }, + "LicenseCodes": { + "clients": { + "rest": { + "libraryClient": "LicenseCodesClient", + "rpcs": { + "Get": { + "methods": [ + "get" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + } + } + } + } + }, + "Licenses": { + "clients": { + "rest": { + "libraryClient": "LicensesClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + } + } + } + } + }, + "MachineTypes": { + "clients": { + "rest": { + "libraryClient": "MachineTypesClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "List": { + "methods": [ + "list" + ] + } + } + } + } + }, + "NetworkEndpointGroups": { + "clients": { + "rest": { + "libraryClient": "NetworkEndpointGroupsClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "AttachNetworkEndpoints": { + "methods": [ + "attach_network_endpoints" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "DetachNetworkEndpoints": { + "methods": [ + "detach_network_endpoints" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "ListNetworkEndpoints": { + "methods": [ + "list_network_endpoints" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + } + } + } + } + }, + "Networks": { + "clients": { + "rest": { + "libraryClient": "NetworksClient", + "rpcs": { + "AddPeering": { + "methods": [ + "add_peering" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "ListPeeringRoutes": { + "methods": [ + "list_peering_routes" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + }, + "RemovePeering": { + "methods": [ + "remove_peering" + ] + }, + "SwitchToCustomMode": { + "methods": [ + "switch_to_custom_mode" + ] + }, + "UpdatePeering": { + "methods": [ + "update_peering" + ] + } + } + } + } + }, + "NodeGroups": { + "clients": { + "rest": { + "libraryClient": "NodeGroupsClient", + "rpcs": { + "AddNodes": { + "methods": [ + "add_nodes" + ] + }, + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "DeleteNodes": { + "methods": [ + "delete_nodes" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "ListNodes": { + "methods": [ + "list_nodes" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "SetNodeTemplate": { + "methods": [ + "set_node_template" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + } + } + } + } + }, + "NodeTemplates": { + "clients": { + "rest": { + "libraryClient": "NodeTemplatesClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + } + } + } + } + }, + "NodeTypes": { + "clients": { + "rest": { + "libraryClient": "NodeTypesClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "List": { + "methods": [ + "list" + ] + } + } + } + } + }, + "PacketMirrorings": { + "clients": { + "rest": { + "libraryClient": "PacketMirroringsClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + } + } + } + } + }, + "Projects": { + "clients": { + "rest": { + "libraryClient": "ProjectsClient", + "rpcs": { + "DisableXpnHost": { + "methods": [ + "disable_xpn_host" + ] + }, + "DisableXpnResource": { + "methods": [ + "disable_xpn_resource" + ] + }, + "EnableXpnHost": { + "methods": [ + "enable_xpn_host" + ] + }, + "EnableXpnResource": { + "methods": [ + "enable_xpn_resource" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetXpnHost": { + "methods": [ + "get_xpn_host" + ] + }, + "GetXpnResources": { + "methods": [ + "get_xpn_resources" + ] + }, + "ListXpnHosts": { + "methods": [ + "list_xpn_hosts" + ] + }, + "MoveDisk": { + "methods": [ + "move_disk" + ] + }, + "MoveInstance": { + "methods": [ + "move_instance" + ] + }, + "SetCommonInstanceMetadata": { + "methods": [ + "set_common_instance_metadata" + ] + }, + "SetDefaultNetworkTier": { + "methods": [ + "set_default_network_tier" + ] + }, + "SetUsageExportBucket": { + "methods": [ + "set_usage_export_bucket" + ] + } + } + } + } + }, + "RegionAutoscalers": { + "clients": { + "rest": { + "libraryClient": "RegionAutoscalersClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + }, + "Update": { + "methods": [ + "update" + ] + } + } + } + } + }, + "RegionBackendServices": { + "clients": { + "rest": { + "libraryClient": "RegionBackendServicesClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetHealth": { + "methods": [ + "get_health" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + }, + "Update": { + "methods": [ + "update" + ] + } + } + } + } + }, + "RegionCommitments": { + "clients": { + "rest": { + "libraryClient": "RegionCommitmentsClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + } + } + } + } + }, + "RegionDiskTypes": { + "clients": { + "rest": { + "libraryClient": "RegionDiskTypesClient", + "rpcs": { + "Get": { + "methods": [ + "get" + ] + }, + "List": { + "methods": [ + "list" + ] + } + } + } + } + }, + "RegionDisks": { + "clients": { + "rest": { + "libraryClient": "RegionDisksClient", + "rpcs": { + "AddResourcePolicies": { + "methods": [ + "add_resource_policies" + ] + }, + "CreateSnapshot": { + "methods": [ + "create_snapshot" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "RemoveResourcePolicies": { + "methods": [ + "remove_resource_policies" + ] + }, + "Resize": { + "methods": [ + "resize" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "SetLabels": { + "methods": [ + "set_labels" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + } + } + } + } + }, + "RegionHealthCheckServices": { + "clients": { + "rest": { + "libraryClient": "RegionHealthCheckServicesClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + } + } + } + } + }, + "RegionHealthChecks": { + "clients": { + "rest": { + "libraryClient": "RegionHealthChecksClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + }, + "Update": { + "methods": [ + "update" + ] + } + } + } + } + }, + "RegionInstanceGroupManagers": { + "clients": { + "rest": { + "libraryClient": "RegionInstanceGroupManagersClient", + "rpcs": { + "AbandonInstances": { + "methods": [ + "abandon_instances" + ] + }, + "ApplyUpdatesToInstances": { + "methods": [ + "apply_updates_to_instances" + ] + }, + "CreateInstances": { + "methods": [ + "create_instances" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "DeleteInstances": { + "methods": [ + "delete_instances" + ] + }, + "DeletePerInstanceConfigs": { + "methods": [ + "delete_per_instance_configs" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "ListErrors": { + "methods": [ + "list_errors" + ] + }, + "ListManagedInstances": { + "methods": [ + "list_managed_instances" + ] + }, + "ListPerInstanceConfigs": { + "methods": [ + "list_per_instance_configs" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + }, + "PatchPerInstanceConfigs": { + "methods": [ + "patch_per_instance_configs" + ] + }, + "RecreateInstances": { + "methods": [ + "recreate_instances" + ] + }, + "Resize": { + "methods": [ + "resize" + ] + }, + "SetInstanceTemplate": { + "methods": [ + "set_instance_template" + ] + }, + "SetTargetPools": { + "methods": [ + "set_target_pools" + ] + }, + "UpdatePerInstanceConfigs": { + "methods": [ + "update_per_instance_configs" + ] + } + } + } + } + }, + "RegionInstanceGroups": { + "clients": { + "rest": { + "libraryClient": "RegionInstanceGroupsClient", + "rpcs": { + "Get": { + "methods": [ + "get" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + }, + "SetNamedPorts": { + "methods": [ + "set_named_ports" + ] + } + } + } + } + }, + "RegionNetworkEndpointGroups": { + "clients": { + "rest": { + "libraryClient": "RegionNetworkEndpointGroupsClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + } + } + } + } + }, + "RegionNotificationEndpoints": { + "clients": { + "rest": { + "libraryClient": "RegionNotificationEndpointsClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + } + } + } + } + }, + "RegionOperations": { + "clients": { + "rest": { + "libraryClient": "RegionOperationsClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Wait": { + "methods": [ + "wait" + ] + } + } + } + } + }, + "RegionSslCertificates": { + "clients": { + "rest": { + "libraryClient": "RegionSslCertificatesClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + } + } + } + } + }, + "RegionTargetHttpProxies": { + "clients": { + "rest": { + "libraryClient": "RegionTargetHttpProxiesClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "SetUrlMap": { + "methods": [ + "set_url_map" + ] + } + } + } + } + }, + "RegionTargetHttpsProxies": { + "clients": { + "rest": { + "libraryClient": "RegionTargetHttpsProxiesClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "SetSslCertificates": { + "methods": [ + "set_ssl_certificates" + ] + }, + "SetUrlMap": { + "methods": [ + "set_url_map" + ] + } + } + } + } + }, + "RegionUrlMaps": { + "clients": { + "rest": { + "libraryClient": "RegionUrlMapsClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + }, + "Update": { + "methods": [ + "update" + ] + }, + "Validate": { + "methods": [ + "validate" + ] + } + } + } + } + }, + "Regions": { + "clients": { + "rest": { + "libraryClient": "RegionsClient", + "rpcs": { + "Get": { + "methods": [ + "get" + ] + }, + "List": { + "methods": [ + "list" + ] + } + } + } + } + }, + "Reservations": { + "clients": { + "rest": { + "libraryClient": "ReservationsClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Resize": { + "methods": [ + "resize" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + } + } + } + } + }, + "ResourcePolicies": { + "clients": { + "rest": { + "libraryClient": "ResourcePoliciesClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + } + } + } + } + }, + "Routers": { + "clients": { + "rest": { + "libraryClient": "RoutersClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetNatMappingInfo": { + "methods": [ + "get_nat_mapping_info" + ] + }, + "GetRouterStatus": { + "methods": [ + "get_router_status" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + }, + "Preview": { + "methods": [ + "preview" + ] + }, + "Update": { + "methods": [ + "update" + ] + } + } + } + } + }, + "Routes": { + "clients": { + "rest": { + "libraryClient": "RoutesClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + } + } + } + } + }, + "SecurityPolicies": { + "clients": { + "rest": { + "libraryClient": "SecurityPoliciesClient", + "rpcs": { + "AddRule": { + "methods": [ + "add_rule" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetRule": { + "methods": [ + "get_rule" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "ListPreconfiguredExpressionSets": { + "methods": [ + "list_preconfigured_expression_sets" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + }, + "PatchRule": { + "methods": [ + "patch_rule" + ] + }, + "RemoveRule": { + "methods": [ + "remove_rule" + ] + } + } + } + } + }, + "Snapshots": { + "clients": { + "rest": { + "libraryClient": "SnapshotsClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "SetLabels": { + "methods": [ + "set_labels" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + } + } + } + } + }, + "SslCertificates": { + "clients": { + "rest": { + "libraryClient": "SslCertificatesClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + } + } + } + } + }, + "SslPolicies": { + "clients": { + "rest": { + "libraryClient": "SslPoliciesClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "ListAvailableFeatures": { + "methods": [ + "list_available_features" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + } + } + } + } + }, + "Subnetworks": { + "clients": { + "rest": { + "libraryClient": "SubnetworksClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "ExpandIpCidrRange": { + "methods": [ + "expand_ip_cidr_range" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "ListUsable": { + "methods": [ + "list_usable" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "SetPrivateIpGoogleAccess": { + "methods": [ + "set_private_ip_google_access" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + } + } + } + } + }, + "TargetGrpcProxies": { + "clients": { + "rest": { + "libraryClient": "TargetGrpcProxiesClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + } + } + } + } + }, + "TargetHttpProxies": { + "clients": { + "rest": { + "libraryClient": "TargetHttpProxiesClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + }, + "SetUrlMap": { + "methods": [ + "set_url_map" + ] + } + } + } + } + }, + "TargetHttpsProxies": { + "clients": { + "rest": { + "libraryClient": "TargetHttpsProxiesClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "SetQuicOverride": { + "methods": [ + "set_quic_override" + ] + }, + "SetSslCertificates": { + "methods": [ + "set_ssl_certificates" + ] + }, + "SetSslPolicy": { + "methods": [ + "set_ssl_policy" + ] + }, + "SetUrlMap": { + "methods": [ + "set_url_map" + ] + } + } + } + } + }, + "TargetInstances": { + "clients": { + "rest": { + "libraryClient": "TargetInstancesClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + } + } + } + } + }, + "TargetPools": { + "clients": { + "rest": { + "libraryClient": "TargetPoolsClient", + "rpcs": { + "AddHealthCheck": { + "methods": [ + "add_health_check" + ] + }, + "AddInstance": { + "methods": [ + "add_instance" + ] + }, + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetHealth": { + "methods": [ + "get_health" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "RemoveHealthCheck": { + "methods": [ + "remove_health_check" + ] + }, + "RemoveInstance": { + "methods": [ + "remove_instance" + ] + }, + "SetBackup": { + "methods": [ + "set_backup" + ] + } + } + } + } + }, + "TargetSslProxies": { + "clients": { + "rest": { + "libraryClient": "TargetSslProxiesClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "SetBackendService": { + "methods": [ + "set_backend_service" + ] + }, + "SetProxyHeader": { + "methods": [ + "set_proxy_header" + ] + }, + "SetSslCertificates": { + "methods": [ + "set_ssl_certificates" + ] + }, + "SetSslPolicy": { + "methods": [ + "set_ssl_policy" + ] + } + } + } + } + }, + "TargetTcpProxies": { + "clients": { + "rest": { + "libraryClient": "TargetTcpProxiesClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "SetBackendService": { + "methods": [ + "set_backend_service" + ] + }, + "SetProxyHeader": { + "methods": [ + "set_proxy_header" + ] + } + } + } + } + }, + "TargetVpnGateways": { + "clients": { + "rest": { + "libraryClient": "TargetVpnGatewaysClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + } + } + } + } + }, + "UrlMaps": { + "clients": { + "rest": { + "libraryClient": "UrlMapsClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "InvalidateCache": { + "methods": [ + "invalidate_cache" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + }, + "Update": { + "methods": [ + "update" + ] + }, + "Validate": { + "methods": [ + "validate" + ] + } + } + } + } + }, + "VpnGateways": { + "clients": { + "rest": { + "libraryClient": "VpnGatewaysClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetStatus": { + "methods": [ + "get_status" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "SetLabels": { + "methods": [ + "set_labels" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + } + } + } + } + }, + "VpnTunnels": { + "clients": { + "rest": { + "libraryClient": "VpnTunnelsClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + } + } + } + } + }, + "ZoneOperations": { + "clients": { + "rest": { + "libraryClient": "ZoneOperationsClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Wait": { + "methods": [ + "wait" + ] + } + } + } + } + }, + "Zones": { + "clients": { + "rest": { + "libraryClient": "ZonesClient", + "rpcs": { + "Get": { + "methods": [ + "get" + ] + }, + "List": { + "methods": [ + "list" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/compute_v1/services/__init__.py b/google/cloud/compute_v1/services/__init__.py index 42ffdf2bc..4de65971c 100644 --- a/google/cloud/compute_v1/services/__init__.py +++ b/google/cloud/compute_v1/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/cloud/compute_v1/services/accelerator_types/__init__.py b/google/cloud/compute_v1/services/accelerator_types/__init__.py index 8cafd7447..1c8844d91 100644 --- a/google/cloud/compute_v1/services/accelerator_types/__init__.py +++ b/google/cloud/compute_v1/services/accelerator_types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import AcceleratorTypesClient __all__ = ("AcceleratorTypesClient",) diff --git a/google/cloud/compute_v1/services/accelerator_types/client.py b/google/cloud/compute_v1/services/accelerator_types/client.py index b55bab926..a60b4e926 100644 --- a/google/cloud/compute_v1/services/accelerator_types/client.py +++ b/google/cloud/compute_v1/services/accelerator_types/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.accelerator_types import pagers from google.cloud.compute_v1.types import compute - from .transports.base import AcceleratorTypesTransport, DEFAULT_CLIENT_INFO from .transports.rest import AcceleratorTypesRestTransport @@ -217,7 +214,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, AcceleratorTypesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -348,7 +345,6 @@ def aggregated_list( 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. @@ -378,10 +374,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListAcceleratorTypesRequest): request = compute.AggregatedListAcceleratorTypesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -438,7 +432,6 @@ def get( This corresponds to the ``accelerator_type`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -473,10 +466,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetAcceleratorTypeRequest): request = compute.GetAcceleratorTypeRequest(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: @@ -524,7 +515,6 @@ def list( This corresponds to the ``zone`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -555,10 +545,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListAcceleratorTypesRequest): request = compute.ListAcceleratorTypesRequest(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: diff --git a/google/cloud/compute_v1/services/accelerator_types/pagers.py b/google/cloud/compute_v1/services/accelerator_types/pagers.py index 284b35519..d2fc460ae 100644 --- a/google/cloud/compute_v1/services/accelerator_types/pagers.py +++ b/google/cloud/compute_v1/services/accelerator_types/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/accelerator_types/transports/__init__.py b/google/cloud/compute_v1/services/accelerator_types/transports/__init__.py index 56b60d095..4cc4207f0 100644 --- a/google/cloud/compute_v1/services/accelerator_types/transports/__init__.py +++ b/google/cloud/compute_v1/services/accelerator_types/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/accelerator_types/transports/base.py b/google/cloud/compute_v1/services/accelerator_types/transports/base.py index 748d6bbcd..baad37c5f 100644 --- a/google/cloud/compute_v1/services/accelerator_types/transports/base.py +++ b/google/cloud/compute_v1/services/accelerator_types/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class AcceleratorTypesTransport(abc.ABC): """Abstract transport class for AcceleratorTypes.""" @@ -45,21 +55,24 @@ class AcceleratorTypesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -68,13 +81,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -82,28 +95,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -122,11 +182,11 @@ def _prep_wrapped_messages(self, client_info): @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListAcceleratorTypesRequest], - typing.Union[ + Union[ compute.AcceleratorTypeAggregatedList, - typing.Awaitable[compute.AcceleratorTypeAggregatedList], + Awaitable[compute.AcceleratorTypeAggregatedList], ], ]: raise NotImplementedError() @@ -134,22 +194,18 @@ def aggregated_list( @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetAcceleratorTypeRequest], - typing.Union[ - compute.AcceleratorType, typing.Awaitable[compute.AcceleratorType] - ], + Union[compute.AcceleratorType, Awaitable[compute.AcceleratorType]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListAcceleratorTypesRequest], - typing.Union[ - compute.AcceleratorTypeList, typing.Awaitable[compute.AcceleratorTypeList] - ], + Union[compute.AcceleratorTypeList, Awaitable[compute.AcceleratorTypeList]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/accelerator_types/transports/rest.py b/google/cloud/compute_v1/services/accelerator_types/transports/rest.py index 07d2e5f42..7588fe91e 100644 --- a/google/cloud/compute_v1/services/accelerator_types/transports/rest.py +++ b/google/cloud/compute_v1/services/accelerator_types/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 AcceleratorTypesTransport, DEFAULT_CLIENT_INFO @@ -52,7 +46,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -62,7 +56,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -79,20 +74,25 @@ def __init__( 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 + 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) + 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, @@ -104,8 +104,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListAcceleratorTypesRequest): - The request object. - A request message for + The request object. A request message for AcceleratorTypes.AggregatedList. See the method description for details. @@ -125,24 +124,31 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListAcceleratorTypesRequest.filter in request: + query_params["filter"] = request.filter + if compute.AggregatedListAcceleratorTypesRequest.include_all_scopes in request: + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListAcceleratorTypesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListAcceleratorTypesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListAcceleratorTypesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if ( + compute.AggregatedListAcceleratorTypesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -162,8 +168,7 @@ def get( Args: request (~.compute.GetAcceleratorTypeRequest): - The request object. - A request message for + The request object. A request message for AcceleratorTypes.Get. See the method description for details. @@ -195,16 +200,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -224,8 +228,7 @@ def list( Args: request (~.compute.ListAcceleratorTypesRequest): - The request object. - A request message for + The request object. A request message for AcceleratorTypes.List. See the method description for details. @@ -245,23 +248,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListAcceleratorTypesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListAcceleratorTypesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListAcceleratorTypesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListAcceleratorTypesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListAcceleratorTypesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() diff --git a/google/cloud/compute_v1/services/addresses/__init__.py b/google/cloud/compute_v1/services/addresses/__init__.py index 5a81b47be..dc970a745 100644 --- a/google/cloud/compute_v1/services/addresses/__init__.py +++ b/google/cloud/compute_v1/services/addresses/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import AddressesClient __all__ = ("AddressesClient",) diff --git a/google/cloud/compute_v1/services/addresses/client.py b/google/cloud/compute_v1/services/addresses/client.py index fd38a15d3..edb032372 100644 --- a/google/cloud/compute_v1/services/addresses/client.py +++ b/google/cloud/compute_v1/services/addresses/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.addresses import pagers from google.cloud.compute_v1.types import compute - from .transports.base import AddressesTransport, DEFAULT_CLIENT_INFO from .transports.rest import AddressesRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, AddressesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -344,7 +341,6 @@ def aggregated_list( 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. @@ -374,10 +370,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListAddressesRequest): request = compute.AggregatedListAddressesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -432,7 +426,6 @@ def delete( This corresponds to the ``address`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -484,10 +477,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteAddressRequest): request = compute.DeleteAddressRequest(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: @@ -539,7 +530,6 @@ def get( This corresponds to the ``address`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -595,10 +585,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetAddressRequest): request = compute.GetAddressRequest(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: @@ -650,7 +638,6 @@ def insert( This corresponds to the ``address_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. @@ -702,10 +689,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertAddressRequest): request = compute.InsertAddressRequest(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: @@ -750,7 +735,6 @@ def list( 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. @@ -781,10 +765,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListAddressesRequest): request = compute.ListAddressesRequest(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: diff --git a/google/cloud/compute_v1/services/addresses/pagers.py b/google/cloud/compute_v1/services/addresses/pagers.py index 53c4a0b49..1d877028a 100644 --- a/google/cloud/compute_v1/services/addresses/pagers.py +++ b/google/cloud/compute_v1/services/addresses/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/addresses/transports/__init__.py b/google/cloud/compute_v1/services/addresses/transports/__init__.py index 8f511b4a5..38b843e9b 100644 --- a/google/cloud/compute_v1/services/addresses/transports/__init__.py +++ b/google/cloud/compute_v1/services/addresses/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/addresses/transports/base.py b/google/cloud/compute_v1/services/addresses/transports/base.py index 7916ab8ce..4cdde8968 100644 --- a/google/cloud/compute_v1/services/addresses/transports/base.py +++ b/google/cloud/compute_v1/services/addresses/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class AddressesTransport(abc.ABC): """Abstract transport class for Addresses.""" @@ -44,21 +54,24 @@ class AddressesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -127,48 +187,44 @@ def _prep_wrapped_messages(self, client_info): @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListAddressesRequest], - typing.Union[ - compute.AddressAggregatedList, - typing.Awaitable[compute.AddressAggregatedList], - ], + Union[compute.AddressAggregatedList, Awaitable[compute.AddressAggregatedList]], ]: raise NotImplementedError() @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteAddressRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ - [compute.GetAddressRequest], - typing.Union[compute.Address, typing.Awaitable[compute.Address]], + ) -> Callable[ + [compute.GetAddressRequest], Union[compute.Address, Awaitable[compute.Address]] ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertAddressRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListAddressesRequest], - typing.Union[compute.AddressList, typing.Awaitable[compute.AddressList]], + Union[compute.AddressList, Awaitable[compute.AddressList]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/addresses/transports/rest.py b/google/cloud/compute_v1/services/addresses/transports/rest.py index 9de0c94e5..deba72fde 100644 --- a/google/cloud/compute_v1/services/addresses/transports/rest.py +++ b/google/cloud/compute_v1/services/addresses/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 AddressesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListAddressesRequest): - The request object. - A request message for + The request object. A request message for Addresses.AggregatedList. See the method description for details. @@ -124,24 +123,28 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListAddressesRequest.filter in request: + query_params["filter"] = request.filter + if compute.AggregatedListAddressesRequest.include_all_scopes in request: + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListAddressesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListAddressesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListAddressesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.AggregatedListAddressesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -161,8 +164,7 @@ def delete( Args: request (~.compute.DeleteAddressRequest): - The request object. - A request message for + The request object. A request message for Addresses.Delete. See the method description for details. @@ -213,19 +215,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteAddressRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -243,8 +244,7 @@ def get( Args: request (~.compute.GetAddressRequest): - The request object. - A request message for Addresses.Get. + The request object. A request message for Addresses.Get. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -295,16 +295,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -322,8 +321,7 @@ def insert( Args: request (~.compute.InsertAddressRequest): - The request object. - A request message for + The request object. A request message for Addresses.Insert. See the method description for details. @@ -378,15 +376,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertAddressRequest.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() if v - ] + 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 @@ -408,8 +405,7 @@ def list( Args: request (~.compute.ListAddressesRequest): - The request object. - A request message for Addresses.List. + The request object. A request message for Addresses.List. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -428,23 +424,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListAddressesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListAddressesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListAddressesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListAddressesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListAddressesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() diff --git a/google/cloud/compute_v1/services/autoscalers/__init__.py b/google/cloud/compute_v1/services/autoscalers/__init__.py index 1996ab92e..f6e95b668 100644 --- a/google/cloud/compute_v1/services/autoscalers/__init__.py +++ b/google/cloud/compute_v1/services/autoscalers/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import AutoscalersClient __all__ = ("AutoscalersClient",) diff --git a/google/cloud/compute_v1/services/autoscalers/client.py b/google/cloud/compute_v1/services/autoscalers/client.py index a110b9dbd..3400b462e 100644 --- a/google/cloud/compute_v1/services/autoscalers/client.py +++ b/google/cloud/compute_v1/services/autoscalers/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.autoscalers import pagers from google.cloud.compute_v1.types import compute - from .transports.base import AutoscalersTransport, DEFAULT_CLIENT_INFO from .transports.rest import AutoscalersRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, AutoscalersTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -344,7 +341,6 @@ def aggregated_list( 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. @@ -374,10 +370,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListAutoscalersRequest): request = compute.AggregatedListAutoscalersRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -430,7 +424,6 @@ def delete( This corresponds to the ``autoscaler`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -482,10 +475,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteAutoscalerRequest): request = compute.DeleteAutoscalerRequest(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: @@ -537,7 +528,6 @@ def get( This corresponds to the ``autoscaler`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -584,10 +574,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetAutoscalerRequest): request = compute.GetAutoscalerRequest(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: @@ -639,7 +627,6 @@ def insert( This corresponds to the ``autoscaler_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. @@ -691,10 +678,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertAutoscalerRequest): request = compute.InsertAutoscalerRequest(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: @@ -740,7 +725,6 @@ def list( This corresponds to the ``zone`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -772,10 +756,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListAutoscalersRequest): request = compute.ListAutoscalersRequest(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: @@ -833,7 +815,6 @@ def patch( This corresponds to the ``autoscaler_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. @@ -885,10 +866,8 @@ def patch( # there are no flattened fields. if not isinstance(request, compute.PatchAutoscalerRequest): request = compute.PatchAutoscalerRequest(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: @@ -940,7 +919,6 @@ def update( This corresponds to the ``autoscaler_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. @@ -992,10 +970,8 @@ def update( # there are no flattened fields. if not isinstance(request, compute.UpdateAutoscalerRequest): request = compute.UpdateAutoscalerRequest(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: diff --git a/google/cloud/compute_v1/services/autoscalers/pagers.py b/google/cloud/compute_v1/services/autoscalers/pagers.py index 7fab36d45..17c841915 100644 --- a/google/cloud/compute_v1/services/autoscalers/pagers.py +++ b/google/cloud/compute_v1/services/autoscalers/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/autoscalers/transports/__init__.py b/google/cloud/compute_v1/services/autoscalers/transports/__init__.py index 5e9d51a1a..0c093d546 100644 --- a/google/cloud/compute_v1/services/autoscalers/transports/__init__.py +++ b/google/cloud/compute_v1/services/autoscalers/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/autoscalers/transports/base.py b/google/cloud/compute_v1/services/autoscalers/transports/base.py index 20f94f4e6..74a744424 100644 --- a/google/cloud/compute_v1/services/autoscalers/transports/base.py +++ b/google/cloud/compute_v1/services/autoscalers/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class AutoscalersTransport(abc.ABC): """Abstract transport class for Autoscalers.""" @@ -44,21 +54,24 @@ class AutoscalersTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -133,11 +193,11 @@ def _prep_wrapped_messages(self, client_info): @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListAutoscalersRequest], - typing.Union[ + Union[ compute.AutoscalerAggregatedList, - typing.Awaitable[compute.AutoscalerAggregatedList], + Awaitable[compute.AutoscalerAggregatedList], ], ]: raise NotImplementedError() @@ -145,54 +205,54 @@ def aggregated_list( @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteAutoscalerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetAutoscalerRequest], - typing.Union[compute.Autoscaler, typing.Awaitable[compute.Autoscaler]], + Union[compute.Autoscaler, Awaitable[compute.Autoscaler]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertAutoscalerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListAutoscalersRequest], - typing.Union[compute.AutoscalerList, typing.Awaitable[compute.AutoscalerList]], + Union[compute.AutoscalerList, Awaitable[compute.AutoscalerList]], ]: raise NotImplementedError() @property def patch( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchAutoscalerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def update( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.UpdateAutoscalerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/autoscalers/transports/rest.py b/google/cloud/compute_v1/services/autoscalers/transports/rest.py index c04a4c620..846584898 100644 --- a/google/cloud/compute_v1/services/autoscalers/transports/rest.py +++ b/google/cloud/compute_v1/services/autoscalers/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 AutoscalersTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListAutoscalersRequest): - The request object. - A request message for + The request object. A request message for Autoscalers.AggregatedList. See the method description for details. @@ -124,24 +123,28 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListAutoscalersRequest.filter in request: + query_params["filter"] = request.filter + if compute.AggregatedListAutoscalersRequest.include_all_scopes in request: + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListAutoscalersRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListAutoscalersRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListAutoscalersRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.AggregatedListAutoscalersRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -161,8 +164,7 @@ def delete( Args: request (~.compute.DeleteAutoscalerRequest): - The request object. - A request message for + The request object. A request message for Autoscalers.Delete. See the method description for details. @@ -213,19 +215,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteAutoscalerRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -243,8 +244,7 @@ def get( Args: request (~.compute.GetAutoscalerRequest): - The request object. - A request message for + The request object. A request message for Autoscalers.Get. See the method description for details. @@ -288,16 +288,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -317,8 +316,7 @@ def insert( Args: request (~.compute.InsertAutoscalerRequest): - The request object. - A request message for + The request object. A request message for Autoscalers.Insert. See the method description for details. @@ -373,15 +371,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertAutoscalerRequest.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() if v - ] + 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 @@ -403,8 +400,7 @@ def list( Args: request (~.compute.ListAutoscalersRequest): - The request object. - A request message for + The request object. A request message for Autoscalers.List. See the method description for details. @@ -426,23 +422,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListAutoscalersRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListAutoscalersRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListAutoscalersRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListAutoscalersRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListAutoscalersRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -462,8 +461,7 @@ def patch( Args: request (~.compute.PatchAutoscalerRequest): - The request object. - A request message for + The request object. A request message for Autoscalers.Patch. See the method description for details. @@ -518,16 +516,16 @@ def patch( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "autoscaler": request.autoscaler, - "requestId": request.request_id, - } + query_params = {} + if compute.PatchAutoscalerRequest.autoscaler in request: + query_params["autoscaler"] = request.autoscaler + if compute.PatchAutoscalerRequest.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() if v - ] + 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 @@ -549,8 +547,7 @@ def update( Args: request (~.compute.UpdateAutoscalerRequest): - The request object. - A request message for + The request object. A request message for Autoscalers.Update. See the method description for details. @@ -605,16 +602,16 @@ def update( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "autoscaler": request.autoscaler, - "requestId": request.request_id, - } + query_params = {} + if compute.UpdateAutoscalerRequest.autoscaler in request: + query_params["autoscaler"] = request.autoscaler + if compute.UpdateAutoscalerRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/backend_buckets/__init__.py b/google/cloud/compute_v1/services/backend_buckets/__init__.py index 13e02db89..3d74d9a17 100644 --- a/google/cloud/compute_v1/services/backend_buckets/__init__.py +++ b/google/cloud/compute_v1/services/backend_buckets/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import BackendBucketsClient __all__ = ("BackendBucketsClient",) diff --git a/google/cloud/compute_v1/services/backend_buckets/client.py b/google/cloud/compute_v1/services/backend_buckets/client.py index bafee1faf..0e5af912f 100644 --- a/google/cloud/compute_v1/services/backend_buckets/client.py +++ b/google/cloud/compute_v1/services/backend_buckets/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.backend_buckets import pagers from google.cloud.compute_v1.types import compute - from .transports.base import BackendBucketsTransport, DEFAULT_CLIENT_INFO from .transports.rest import BackendBucketsRestTransport @@ -215,7 +212,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, BackendBucketsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -363,7 +360,6 @@ def add_signed_url_key( This corresponds to the ``signed_url_key_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. @@ -415,10 +411,8 @@ def add_signed_url_key( # there are no flattened fields. if not isinstance(request, compute.AddSignedUrlKeyBackendBucketRequest): request = compute.AddSignedUrlKeyBackendBucketRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if backend_bucket is not None: @@ -465,7 +459,6 @@ def delete( This corresponds to the ``backend_bucket`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -517,10 +510,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteBackendBucketRequest): request = compute.DeleteBackendBucketRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if backend_bucket is not None: @@ -576,7 +567,6 @@ def delete_signed_url_key( This corresponds to the ``key_name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -628,10 +618,8 @@ def delete_signed_url_key( # there are no flattened fields. if not isinstance(request, compute.DeleteSignedUrlKeyBackendBucketRequest): request = compute.DeleteSignedUrlKeyBackendBucketRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if backend_bucket is not None: @@ -680,7 +668,6 @@ def get( This corresponds to the ``backend_bucket`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -713,10 +700,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetBackendBucketRequest): request = compute.GetBackendBucketRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if backend_bucket is not None: @@ -760,7 +745,6 @@ def insert( This corresponds to the ``backend_bucket_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. @@ -812,10 +796,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertBackendBucketRequest): request = compute.InsertBackendBucketRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if backend_bucket_resource is not None: @@ -853,7 +835,6 @@ def list( 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. @@ -885,10 +866,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListBackendBucketsRequest): request = compute.ListBackendBucketsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -946,7 +925,6 @@ def patch( This corresponds to the ``backend_bucket_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. @@ -998,10 +976,8 @@ def patch( # there are no flattened fields. if not isinstance(request, compute.PatchBackendBucketRequest): request = compute.PatchBackendBucketRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if backend_bucket is not None: @@ -1055,7 +1031,6 @@ def update( This corresponds to the ``backend_bucket_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. @@ -1107,10 +1082,8 @@ def update( # there are no flattened fields. if not isinstance(request, compute.UpdateBackendBucketRequest): request = compute.UpdateBackendBucketRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if backend_bucket is not None: diff --git a/google/cloud/compute_v1/services/backend_buckets/pagers.py b/google/cloud/compute_v1/services/backend_buckets/pagers.py index a71b74ff8..fccc5dad5 100644 --- a/google/cloud/compute_v1/services/backend_buckets/pagers.py +++ b/google/cloud/compute_v1/services/backend_buckets/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/backend_buckets/transports/__init__.py b/google/cloud/compute_v1/services/backend_buckets/transports/__init__.py index 1921705e9..c9c6d64ff 100644 --- a/google/cloud/compute_v1/services/backend_buckets/transports/__init__.py +++ b/google/cloud/compute_v1/services/backend_buckets/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/backend_buckets/transports/base.py b/google/cloud/compute_v1/services/backend_buckets/transports/base.py index 97c87f61f..ce72e11b5 100644 --- a/google/cloud/compute_v1/services/backend_buckets/transports/base.py +++ b/google/cloud/compute_v1/services/backend_buckets/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class BackendBucketsTransport(abc.ABC): """Abstract transport class for BackendBuckets.""" @@ -44,21 +54,24 @@ class BackendBucketsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -138,74 +198,72 @@ def _prep_wrapped_messages(self, client_info): @property def add_signed_url_key( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AddSignedUrlKeyBackendBucketRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteBackendBucketRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def delete_signed_url_key( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteSignedUrlKeyBackendBucketRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetBackendBucketRequest], - typing.Union[compute.BackendBucket, typing.Awaitable[compute.BackendBucket]], + Union[compute.BackendBucket, Awaitable[compute.BackendBucket]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertBackendBucketRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListBackendBucketsRequest], - typing.Union[ - compute.BackendBucketList, typing.Awaitable[compute.BackendBucketList] - ], + Union[compute.BackendBucketList, Awaitable[compute.BackendBucketList]], ]: raise NotImplementedError() @property def patch( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchBackendBucketRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def update( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.UpdateBackendBucketRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/backend_buckets/transports/rest.py b/google/cloud/compute_v1/services/backend_buckets/transports/rest.py index 9bcbfb4f7..213c19657 100644 --- a/google/cloud/compute_v1/services/backend_buckets/transports/rest.py +++ b/google/cloud/compute_v1/services/backend_buckets/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 BackendBucketsTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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_signed_url_key( self, @@ -103,8 +103,7 @@ def add_signed_url_key( Args: request (~.compute.AddSignedUrlKeyBackendBucketRequest): - The request object. - A request message for + The request object. A request message for BackendBuckets.AddSignedUrlKey. See the method description for details. @@ -161,15 +160,14 @@ def add_signed_url_key( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.AddSignedUrlKeyBackendBucketRequest.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() if v - ] + 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 @@ -191,8 +189,7 @@ def delete( Args: request (~.compute.DeleteBackendBucketRequest): - The request object. - A request message for + The request object. A request message for BackendBuckets.Delete. See the method description for details. @@ -242,19 +239,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteBackendBucketRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -272,8 +268,7 @@ def delete_signed_url_key( Args: request (~.compute.DeleteSignedUrlKeyBackendBucketRequest): - The request object. - A request message for + The request object. A request message for BackendBuckets.DeleteSignedUrlKey. See the method description for details. @@ -323,20 +318,20 @@ def delete_signed_url_key( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "keyName": request.key_name, - "requestId": request.request_id, - } + query_params = {} + if request.key_name: + query_params["keyName"] = request.key_name + if compute.DeleteSignedUrlKeyBackendBucketRequest.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() if v - ] + 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 - response = self._session.post(url) + response = self._session.post(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -354,8 +349,7 @@ def get( Args: request (~.compute.GetBackendBucketRequest): - The request object. - A request message for + The request object. A request message for BackendBuckets.Get. See the method description for details. @@ -384,16 +378,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -413,8 +406,7 @@ def insert( Args: request (~.compute.InsertBackendBucketRequest): - The request object. - A request message for + The request object. A request message for BackendBuckets.Insert. See the method description for details. @@ -469,15 +461,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertBackendBucketRequest.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() if v - ] + 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 @@ -499,8 +490,7 @@ def list( Args: request (~.compute.ListBackendBucketsRequest): - The request object. - A request message for + The request object. A request message for BackendBuckets.List. See the method description for details. @@ -522,23 +512,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListBackendBucketsRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListBackendBucketsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListBackendBucketsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListBackendBucketsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListBackendBucketsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -558,8 +551,7 @@ def patch( Args: request (~.compute.PatchBackendBucketRequest): - The request object. - A request message for + The request object. A request message for BackendBuckets.Patch. See the method description for details. @@ -616,15 +608,14 @@ def patch( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.PatchBackendBucketRequest.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() if v - ] + 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 @@ -646,8 +637,7 @@ def update( Args: request (~.compute.UpdateBackendBucketRequest): - The request object. - A request message for + The request object. A request message for BackendBuckets.Update. See the method description for details. @@ -704,15 +694,14 @@ def update( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.UpdateBackendBucketRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/backend_services/__init__.py b/google/cloud/compute_v1/services/backend_services/__init__.py index a745941f2..de8dab4d0 100644 --- a/google/cloud/compute_v1/services/backend_services/__init__.py +++ b/google/cloud/compute_v1/services/backend_services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import BackendServicesClient __all__ = ("BackendServicesClient",) diff --git a/google/cloud/compute_v1/services/backend_services/client.py b/google/cloud/compute_v1/services/backend_services/client.py index 01c186923..103a137f6 100644 --- a/google/cloud/compute_v1/services/backend_services/client.py +++ b/google/cloud/compute_v1/services/backend_services/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.backend_services import pagers from google.cloud.compute_v1.types import compute - from .transports.base import BackendServicesTransport, DEFAULT_CLIENT_INFO from .transports.rest import BackendServicesRestTransport @@ -215,7 +212,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, BackendServicesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -363,7 +360,6 @@ def add_signed_url_key( This corresponds to the ``signed_url_key_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. @@ -415,10 +411,8 @@ def add_signed_url_key( # there are no flattened fields. if not isinstance(request, compute.AddSignedUrlKeyBackendServiceRequest): request = compute.AddSignedUrlKeyBackendServiceRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if backend_service is not None: @@ -460,7 +454,6 @@ def aggregated_list( 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. @@ -492,10 +485,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListBackendServicesRequest): request = compute.AggregatedListBackendServicesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -544,7 +535,6 @@ def delete( This corresponds to the ``backend_service`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -596,10 +586,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteBackendServiceRequest): request = compute.DeleteBackendServiceRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if backend_service is not None: @@ -655,7 +643,6 @@ def delete_signed_url_key( This corresponds to the ``key_name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -707,10 +694,8 @@ def delete_signed_url_key( # there are no flattened fields. if not isinstance(request, compute.DeleteSignedUrlKeyBackendServiceRequest): request = compute.DeleteSignedUrlKeyBackendServiceRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if backend_service is not None: @@ -758,7 +743,6 @@ def get( This corresponds to the ``backend_service`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -807,10 +791,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetBackendServiceRequest): request = compute.GetBackendServiceRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if backend_service is not None: @@ -866,7 +848,6 @@ def get_health( This corresponds to the ``resource_group_reference_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. @@ -895,10 +876,8 @@ def get_health( # there are no flattened fields. if not isinstance(request, compute.GetHealthBackendServiceRequest): request = compute.GetHealthBackendServiceRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if backend_service is not None: @@ -947,7 +926,6 @@ def insert( This corresponds to the ``backend_service_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. @@ -999,10 +977,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertBackendServiceRequest): request = compute.InsertBackendServiceRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if backend_service_resource is not None: @@ -1040,7 +1016,6 @@ def list( 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. @@ -1072,10 +1047,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListBackendServicesRequest): request = compute.ListBackendServicesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -1134,7 +1107,6 @@ def patch( This corresponds to the ``backend_service_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. @@ -1186,10 +1158,8 @@ def patch( # there are no flattened fields. if not isinstance(request, compute.PatchBackendServiceRequest): request = compute.PatchBackendServiceRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if backend_service is not None: @@ -1244,7 +1214,6 @@ def set_security_policy( This corresponds to the ``security_policy_reference_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. @@ -1298,10 +1267,8 @@ def set_security_policy( # there are no flattened fields. if not isinstance(request, compute.SetSecurityPolicyBackendServiceRequest): request = compute.SetSecurityPolicyBackendServiceRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if backend_service is not None: @@ -1358,7 +1325,6 @@ def update( This corresponds to the ``backend_service_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. @@ -1410,10 +1376,8 @@ def update( # there are no flattened fields. if not isinstance(request, compute.UpdateBackendServiceRequest): request = compute.UpdateBackendServiceRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if backend_service is not None: diff --git a/google/cloud/compute_v1/services/backend_services/pagers.py b/google/cloud/compute_v1/services/backend_services/pagers.py index 5b3c487f8..57c42ca86 100644 --- a/google/cloud/compute_v1/services/backend_services/pagers.py +++ b/google/cloud/compute_v1/services/backend_services/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/backend_services/transports/__init__.py b/google/cloud/compute_v1/services/backend_services/transports/__init__.py index c13acc6d3..cb66d8369 100644 --- a/google/cloud/compute_v1/services/backend_services/transports/__init__.py +++ b/google/cloud/compute_v1/services/backend_services/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/backend_services/transports/base.py b/google/cloud/compute_v1/services/backend_services/transports/base.py index 3daf2596e..7e58fefa4 100644 --- a/google/cloud/compute_v1/services/backend_services/transports/base.py +++ b/google/cloud/compute_v1/services/backend_services/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class BackendServicesTransport(abc.ABC): """Abstract transport class for BackendServices.""" @@ -44,21 +54,24 @@ class BackendServicesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -147,20 +207,20 @@ def _prep_wrapped_messages(self, client_info): @property def add_signed_url_key( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AddSignedUrlKeyBackendServiceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListBackendServicesRequest], - typing.Union[ + Union[ compute.BackendServiceAggregatedList, - typing.Awaitable[compute.BackendServiceAggregatedList], + Awaitable[compute.BackendServiceAggregatedList], ], ]: raise NotImplementedError() @@ -168,38 +228,38 @@ def aggregated_list( @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteBackendServiceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def delete_signed_url_key( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteSignedUrlKeyBackendServiceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetBackendServiceRequest], - typing.Union[compute.BackendService, typing.Awaitable[compute.BackendService]], + Union[compute.BackendService, Awaitable[compute.BackendService]], ]: raise NotImplementedError() @property def get_health( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetHealthBackendServiceRequest], - typing.Union[ + Union[ compute.BackendServiceGroupHealth, - typing.Awaitable[compute.BackendServiceGroupHealth], + Awaitable[compute.BackendServiceGroupHealth], ], ]: raise NotImplementedError() @@ -207,47 +267,45 @@ def get_health( @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertBackendServiceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListBackendServicesRequest], - typing.Union[ - compute.BackendServiceList, typing.Awaitable[compute.BackendServiceList] - ], + Union[compute.BackendServiceList, Awaitable[compute.BackendServiceList]], ]: raise NotImplementedError() @property def patch( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchBackendServiceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_security_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetSecurityPolicyBackendServiceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def update( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.UpdateBackendServiceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/backend_services/transports/rest.py b/google/cloud/compute_v1/services/backend_services/transports/rest.py index fabca78af..09afa47fc 100644 --- a/google/cloud/compute_v1/services/backend_services/transports/rest.py +++ b/google/cloud/compute_v1/services/backend_services/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 BackendServicesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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_signed_url_key( self, @@ -103,8 +103,7 @@ def add_signed_url_key( Args: request (~.compute.AddSignedUrlKeyBackendServiceRequest): - The request object. - A request message for + The request object. A request message for BackendServices.AddSignedUrlKey. See the method description for details. @@ -161,15 +160,14 @@ def add_signed_url_key( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.AddSignedUrlKeyBackendServiceRequest.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() if v - ] + 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 @@ -191,8 +189,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListBackendServicesRequest): - The request object. - A request message for + The request object. A request message for BackendServices.AggregatedList. See the method description for details. @@ -214,24 +211,31 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListBackendServicesRequest.filter in request: + query_params["filter"] = request.filter + if compute.AggregatedListBackendServicesRequest.include_all_scopes in request: + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListBackendServicesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListBackendServicesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListBackendServicesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if ( + compute.AggregatedListBackendServicesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -251,8 +255,7 @@ def delete( Args: request (~.compute.DeleteBackendServiceRequest): - The request object. - A request message for + The request object. A request message for BackendServices.Delete. See the method description for details. @@ -302,19 +305,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteBackendServiceRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -332,8 +334,7 @@ def delete_signed_url_key( Args: request (~.compute.DeleteSignedUrlKeyBackendServiceRequest): - The request object. - A request message for + The request object. A request message for BackendServices.DeleteSignedUrlKey. See the method description for details. @@ -383,20 +384,20 @@ def delete_signed_url_key( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "keyName": request.key_name, - "requestId": request.request_id, - } + query_params = {} + if request.key_name: + query_params["keyName"] = request.key_name + if compute.DeleteSignedUrlKeyBackendServiceRequest.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() if v - ] + 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 - response = self._session.post(url) + response = self._session.post(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -414,8 +415,7 @@ def get( Args: request (~.compute.GetBackendServiceRequest): - The request object. - A request message for + The request object. A request message for BackendServices.Get. See the method description for details. @@ -460,16 +460,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -489,8 +488,7 @@ def get_health( Args: request (~.compute.GetHealthBackendServiceRequest): - The request object. - A request message for + The request object. A request message for BackendServices.GetHealth. See the method description for details. @@ -520,12 +518,11 @@ def get_health( # 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() if v - ] + 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 @@ -549,8 +546,7 @@ def insert( Args: request (~.compute.InsertBackendServiceRequest): - The request object. - A request message for + The request object. A request message for BackendServices.Insert. See the method description for details. @@ -605,15 +601,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertBackendServiceRequest.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() if v - ] + 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 @@ -635,8 +630,7 @@ def list( Args: request (~.compute.ListBackendServicesRequest): - The request object. - A request message for + The request object. A request message for BackendServices.List. See the method description for details. @@ -658,23 +652,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListBackendServicesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListBackendServicesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListBackendServicesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListBackendServicesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListBackendServicesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -694,8 +691,7 @@ def patch( Args: request (~.compute.PatchBackendServiceRequest): - The request object. - A request message for + The request object. A request message for BackendServices.Patch. See the method description for details. @@ -752,15 +748,14 @@ def patch( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.PatchBackendServiceRequest.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() if v - ] + 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 @@ -782,8 +777,7 @@ def set_security_policy( Args: request (~.compute.SetSecurityPolicyBackendServiceRequest): - The request object. - A request message for + The request object. A request message for BackendServices.SetSecurityPolicy. See the method description for details. @@ -840,15 +834,14 @@ def set_security_policy( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetSecurityPolicyBackendServiceRequest.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() if v - ] + 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 @@ -870,8 +863,7 @@ def update( Args: request (~.compute.UpdateBackendServiceRequest): - The request object. - A request message for + The request object. A request message for BackendServices.Update. See the method description for details. @@ -928,15 +920,14 @@ def update( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.UpdateBackendServiceRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/disk_types/__init__.py b/google/cloud/compute_v1/services/disk_types/__init__.py index 83821eac7..dd5c59930 100644 --- a/google/cloud/compute_v1/services/disk_types/__init__.py +++ b/google/cloud/compute_v1/services/disk_types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import DiskTypesClient __all__ = ("DiskTypesClient",) diff --git a/google/cloud/compute_v1/services/disk_types/client.py b/google/cloud/compute_v1/services/disk_types/client.py index 296c597b3..246eedd01 100644 --- a/google/cloud/compute_v1/services/disk_types/client.py +++ b/google/cloud/compute_v1/services/disk_types/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.disk_types import pagers from google.cloud.compute_v1.types import compute - from .transports.base import DiskTypesTransport, DEFAULT_CLIENT_INFO from .transports.rest import DiskTypesRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, DiskTypesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -344,7 +341,6 @@ def aggregated_list( 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. @@ -374,10 +370,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListDiskTypesRequest): request = compute.AggregatedListDiskTypesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -432,7 +426,6 @@ def get( This corresponds to the ``disk_type`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -480,10 +473,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetDiskTypeRequest): request = compute.GetDiskTypeRequest(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: @@ -530,7 +521,6 @@ def list( This corresponds to the ``zone`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -561,10 +551,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListDiskTypesRequest): request = compute.ListDiskTypesRequest(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: diff --git a/google/cloud/compute_v1/services/disk_types/pagers.py b/google/cloud/compute_v1/services/disk_types/pagers.py index 5c0dbb19d..f501b2b3b 100644 --- a/google/cloud/compute_v1/services/disk_types/pagers.py +++ b/google/cloud/compute_v1/services/disk_types/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/disk_types/transports/__init__.py b/google/cloud/compute_v1/services/disk_types/transports/__init__.py index d2c87fc29..aaeb464df 100644 --- a/google/cloud/compute_v1/services/disk_types/transports/__init__.py +++ b/google/cloud/compute_v1/services/disk_types/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/disk_types/transports/base.py b/google/cloud/compute_v1/services/disk_types/transports/base.py index dc34ea061..b330b6cfd 100644 --- a/google/cloud/compute_v1/services/disk_types/transports/base.py +++ b/google/cloud/compute_v1/services/disk_types/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class DiskTypesTransport(abc.ABC): """Abstract transport class for DiskTypes.""" @@ -45,21 +55,24 @@ class DiskTypesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -68,13 +81,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -82,28 +95,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -122,11 +182,10 @@ def _prep_wrapped_messages(self, client_info): @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListDiskTypesRequest], - typing.Union[ - compute.DiskTypeAggregatedList, - typing.Awaitable[compute.DiskTypeAggregatedList], + Union[ + compute.DiskTypeAggregatedList, Awaitable[compute.DiskTypeAggregatedList] ], ]: raise NotImplementedError() @@ -134,18 +193,18 @@ def aggregated_list( @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetDiskTypeRequest], - typing.Union[compute.DiskType, typing.Awaitable[compute.DiskType]], + Union[compute.DiskType, Awaitable[compute.DiskType]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListDiskTypesRequest], - typing.Union[compute.DiskTypeList, typing.Awaitable[compute.DiskTypeList]], + Union[compute.DiskTypeList, Awaitable[compute.DiskTypeList]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/disk_types/transports/rest.py b/google/cloud/compute_v1/services/disk_types/transports/rest.py index 26e9eead2..579796807 100644 --- a/google/cloud/compute_v1/services/disk_types/transports/rest.py +++ b/google/cloud/compute_v1/services/disk_types/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 DiskTypesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListDiskTypesRequest): - The request object. - A request message for + The request object. A request message for DiskTypes.AggregatedList. See the method description for details. @@ -124,24 +123,28 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListDiskTypesRequest.filter in request: + query_params["filter"] = request.filter + if compute.AggregatedListDiskTypesRequest.include_all_scopes in request: + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListDiskTypesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListDiskTypesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListDiskTypesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.AggregatedListDiskTypesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -161,8 +164,7 @@ def get( Args: request (~.compute.GetDiskTypeRequest): - The request object. - A request message for DiskTypes.Get. + The request object. A request message for DiskTypes.Get. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -205,16 +207,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -232,8 +233,7 @@ def list( Args: request (~.compute.ListDiskTypesRequest): - The request object. - A request message for DiskTypes.List. + The request object. A request message for DiskTypes.List. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -252,23 +252,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListDiskTypesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListDiskTypesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListDiskTypesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListDiskTypesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListDiskTypesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() diff --git a/google/cloud/compute_v1/services/disks/__init__.py b/google/cloud/compute_v1/services/disks/__init__.py index 918cc9f98..bd216d409 100644 --- a/google/cloud/compute_v1/services/disks/__init__.py +++ b/google/cloud/compute_v1/services/disks/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import DisksClient __all__ = ("DisksClient",) diff --git a/google/cloud/compute_v1/services/disks/client.py b/google/cloud/compute_v1/services/disks/client.py index c5dad0ae3..f33d75a23 100644 --- a/google/cloud/compute_v1/services/disks/client.py +++ b/google/cloud/compute_v1/services/disks/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.disks import pagers from google.cloud.compute_v1.types import compute - from .transports.base import DisksTransport, DEFAULT_CLIENT_INFO from .transports.rest import DisksRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, DisksTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -366,7 +363,6 @@ def add_resource_policies( This corresponds to the ``disks_add_resource_policies_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. @@ -420,10 +416,8 @@ def add_resource_policies( # there are no flattened fields. if not isinstance(request, compute.AddResourcePoliciesDiskRequest): request = compute.AddResourcePoliciesDiskRequest(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: @@ -466,7 +460,6 @@ def aggregated_list( 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. @@ -496,10 +489,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListDisksRequest): request = compute.AggregatedListDisksRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -562,7 +553,6 @@ def create_snapshot( This corresponds to the ``snapshot_resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -614,10 +604,8 @@ def create_snapshot( # there are no flattened fields. if not isinstance(request, compute.CreateSnapshotDiskRequest): request = compute.CreateSnapshotDiskRequest(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: @@ -677,7 +665,6 @@ def delete( This corresponds to the ``disk`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -729,10 +716,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteDiskRequest): request = compute.DeleteDiskRequest(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: @@ -787,7 +772,6 @@ def get( This corresponds to the ``disk`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -836,10 +820,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetDiskRequest): request = compute.GetDiskRequest(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: @@ -895,7 +877,6 @@ def get_iam_policy( 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. @@ -973,10 +954,8 @@ def get_iam_policy( # there are no flattened fields. if not isinstance(request, compute.GetIamPolicyDiskRequest): request = compute.GetIamPolicyDiskRequest(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: @@ -1034,7 +1013,6 @@ def insert( This corresponds to the ``disk_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. @@ -1086,10 +1064,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertDiskRequest): request = compute.InsertDiskRequest(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: @@ -1136,7 +1112,6 @@ def list( This corresponds to the ``zone`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1167,10 +1142,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListDisksRequest): request = compute.ListDisksRequest(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: @@ -1233,7 +1206,6 @@ def remove_resource_policies( This corresponds to the ``disks_remove_resource_policies_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. @@ -1287,10 +1259,8 @@ def remove_resource_policies( # there are no flattened fields. if not isinstance(request, compute.RemoveResourcePoliciesDiskRequest): request = compute.RemoveResourcePoliciesDiskRequest(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: @@ -1353,7 +1323,6 @@ def resize( This corresponds to the ``disks_resize_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. @@ -1405,10 +1374,8 @@ def resize( # there are no flattened fields. if not isinstance(request, compute.ResizeDiskRequest): request = compute.ResizeDiskRequest(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: @@ -1472,7 +1439,6 @@ def set_iam_policy( This corresponds to the ``zone_set_policy_request_resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1552,10 +1518,8 @@ def set_iam_policy( # there are no flattened fields. if not isinstance(request, compute.SetIamPolicyDiskRequest): request = compute.SetIamPolicyDiskRequest(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: @@ -1620,7 +1584,6 @@ def set_labels( This corresponds to the ``zone_set_labels_request_resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1674,10 +1637,8 @@ def set_labels( # there are no flattened fields. if not isinstance(request, compute.SetLabelsDiskRequest): request = compute.SetLabelsDiskRequest(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: @@ -1743,7 +1704,6 @@ def test_iam_permissions( 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. @@ -1772,10 +1732,8 @@ def test_iam_permissions( # there are no flattened fields. if not isinstance(request, compute.TestIamPermissionsDiskRequest): request = compute.TestIamPermissionsDiskRequest(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: diff --git a/google/cloud/compute_v1/services/disks/pagers.py b/google/cloud/compute_v1/services/disks/pagers.py index 665157ce9..c5c4a11b6 100644 --- a/google/cloud/compute_v1/services/disks/pagers.py +++ b/google/cloud/compute_v1/services/disks/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/disks/transports/__init__.py b/google/cloud/compute_v1/services/disks/transports/__init__.py index af8516438..02378cb8b 100644 --- a/google/cloud/compute_v1/services/disks/transports/__init__.py +++ b/google/cloud/compute_v1/services/disks/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/disks/transports/base.py b/google/cloud/compute_v1/services/disks/transports/base.py index 477c78e2f..d336f3c62 100644 --- a/google/cloud/compute_v1/services/disks/transports/base.py +++ b/google/cloud/compute_v1/services/disks/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class DisksTransport(abc.ABC): """Abstract transport class for Disks.""" @@ -44,21 +54,24 @@ class DisksTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -157,121 +217,116 @@ def _prep_wrapped_messages(self, client_info): @property def add_resource_policies( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AddResourcePoliciesDiskRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListDisksRequest], - typing.Union[ - compute.DiskAggregatedList, typing.Awaitable[compute.DiskAggregatedList] - ], + Union[compute.DiskAggregatedList, Awaitable[compute.DiskAggregatedList]], ]: raise NotImplementedError() @property def create_snapshot( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.CreateSnapshotDiskRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteDiskRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ - [compute.GetDiskRequest], - typing.Union[compute.Disk, typing.Awaitable[compute.Disk]], + ) -> Callable[ + [compute.GetDiskRequest], Union[compute.Disk, Awaitable[compute.Disk]] ]: raise NotImplementedError() @property def get_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetIamPolicyDiskRequest], - typing.Union[compute.Policy, typing.Awaitable[compute.Policy]], + Union[compute.Policy, Awaitable[compute.Policy]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertDiskRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ - [compute.ListDisksRequest], - typing.Union[compute.DiskList, typing.Awaitable[compute.DiskList]], + ) -> Callable[ + [compute.ListDisksRequest], Union[compute.DiskList, Awaitable[compute.DiskList]] ]: raise NotImplementedError() @property def remove_resource_policies( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.RemoveResourcePoliciesDiskRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def resize( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ResizeDiskRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetIamPolicyDiskRequest], - typing.Union[compute.Policy, typing.Awaitable[compute.Policy]], + Union[compute.Policy, Awaitable[compute.Policy]], ]: raise NotImplementedError() @property def set_labels( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetLabelsDiskRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.TestIamPermissionsDiskRequest], - typing.Union[ - compute.TestPermissionsResponse, - typing.Awaitable[compute.TestPermissionsResponse], + Union[ + compute.TestPermissionsResponse, Awaitable[compute.TestPermissionsResponse] ], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/disks/transports/rest.py b/google/cloud/compute_v1/services/disks/transports/rest.py index aeb3c45c0..1a778cda7 100644 --- a/google/cloud/compute_v1/services/disks/transports/rest.py +++ b/google/cloud/compute_v1/services/disks/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 DisksTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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_resource_policies( self, @@ -103,8 +103,7 @@ def add_resource_policies( Args: request (~.compute.AddResourcePoliciesDiskRequest): - The request object. - A request message for + The request object. A request message for Disks.AddResourcePolicies. See the method description for details. @@ -162,15 +161,14 @@ def add_resource_policies( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.AddResourcePoliciesDiskRequest.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() if v - ] + 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 @@ -192,8 +190,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListDisksRequest): - The request object. - A request message for + The request object. A request message for Disks.AggregatedList. See the method description for details. @@ -213,24 +210,28 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListDisksRequest.filter in request: + query_params["filter"] = request.filter + if compute.AggregatedListDisksRequest.include_all_scopes in request: + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListDisksRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListDisksRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListDisksRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.AggregatedListDisksRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -250,8 +251,7 @@ def create_snapshot( Args: request (~.compute.CreateSnapshotDiskRequest): - The request object. - A request message for + The request object. A request message for Disks.CreateSnapshot. See the method description for details. @@ -309,16 +309,16 @@ def create_snapshot( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "guestFlush": request.guest_flush, - "requestId": request.request_id, - } + query_params = {} + if compute.CreateSnapshotDiskRequest.guest_flush in request: + query_params["guestFlush"] = request.guest_flush + if compute.CreateSnapshotDiskRequest.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() if v - ] + 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 @@ -340,8 +340,7 @@ def delete( Args: request (~.compute.DeleteDiskRequest): - The request object. - A request message for Disks.Delete. + The request object. A request message for Disks.Delete. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -391,19 +390,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteDiskRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -421,8 +419,7 @@ def get( Args: request (~.compute.GetDiskRequest): - The request object. - A request message for Disks.Get. See + The request object. A request message for Disks.Get. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -465,16 +462,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -492,8 +488,7 @@ def get_iam_policy( Args: request (~.compute.GetIamPolicyDiskRequest): - The request object. - A request message for + The request object. A request message for Disks.GetIamPolicy. See the method description for details. @@ -566,19 +561,20 @@ def get_iam_policy( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "optionsRequestedPolicyVersion": request.options_requested_policy_version, - } + query_params = {} + if compute.GetIamPolicyDiskRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -596,8 +592,7 @@ def insert( Args: request (~.compute.InsertDiskRequest): - The request object. - A request message for Disks.Insert. + The request object. A request message for Disks.Insert. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -651,16 +646,16 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - "sourceImage": request.source_image, - } + query_params = {} + if compute.InsertDiskRequest.request_id in request: + query_params["requestId"] = request.request_id + if compute.InsertDiskRequest.source_image in request: + query_params["sourceImage"] = request.source_image + # 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() if v - ] + 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 @@ -682,8 +677,7 @@ def list( Args: request (~.compute.ListDisksRequest): - The request object. - A request message for Disks.List. See + The request object. A request message for Disks.List. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -702,23 +696,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListDisksRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListDisksRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListDisksRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListDisksRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListDisksRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -736,8 +733,7 @@ def remove_resource_policies( Args: request (~.compute.RemoveResourcePoliciesDiskRequest): - The request object. - A request message for + The request object. A request message for Disks.RemoveResourcePolicies. See the method description for details. @@ -795,15 +791,14 @@ def remove_resource_policies( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.RemoveResourcePoliciesDiskRequest.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() if v - ] + 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 @@ -825,8 +820,7 @@ def resize( Args: request (~.compute.ResizeDiskRequest): - The request object. - A request message for Disks.Resize. + The request object. A request message for Disks.Resize. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -883,15 +877,14 @@ def resize( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.ResizeDiskRequest.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() if v - ] + 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 @@ -913,8 +906,7 @@ def set_iam_policy( Args: request (~.compute.SetIamPolicyDiskRequest): - The request object. - A request message for + The request object. A request message for Disks.SetIamPolicy. See the method description for details. @@ -995,12 +987,11 @@ def set_iam_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() if v - ] + 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 @@ -1022,8 +1013,7 @@ def set_labels( Args: request (~.compute.SetLabelsDiskRequest): - The request object. - A request message for + The request object. A request message for Disks.SetLabels. See the method description for details. @@ -1081,15 +1071,14 @@ def set_labels( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetLabelsDiskRequest.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() if v - ] + 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 @@ -1111,8 +1100,7 @@ def test_iam_permissions( Args: request (~.compute.TestIamPermissionsDiskRequest): - The request object. - A request message for + The request object. A request message for Disks.TestIamPermissions. See the method description for details. @@ -1143,12 +1131,11 @@ def test_iam_permissions( # 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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/external_vpn_gateways/__init__.py b/google/cloud/compute_v1/services/external_vpn_gateways/__init__.py index 360122e4e..bc53b527e 100644 --- a/google/cloud/compute_v1/services/external_vpn_gateways/__init__.py +++ b/google/cloud/compute_v1/services/external_vpn_gateways/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import ExternalVpnGatewaysClient __all__ = ("ExternalVpnGatewaysClient",) diff --git a/google/cloud/compute_v1/services/external_vpn_gateways/client.py b/google/cloud/compute_v1/services/external_vpn_gateways/client.py index f541a900f..a3860ad70 100644 --- a/google/cloud/compute_v1/services/external_vpn_gateways/client.py +++ b/google/cloud/compute_v1/services/external_vpn_gateways/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.external_vpn_gateways import pagers from google.cloud.compute_v1.types import compute - from .transports.base import ExternalVpnGatewaysTransport, DEFAULT_CLIENT_INFO from .transports.rest import ExternalVpnGatewaysRestTransport @@ -217,7 +214,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ExternalVpnGatewaysTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -356,7 +353,6 @@ def delete( This corresponds to the ``external_vpn_gateway`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -408,10 +404,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteExternalVpnGatewayRequest): request = compute.DeleteExternalVpnGatewayRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if external_vpn_gateway is not None: @@ -458,7 +452,6 @@ def get( This corresponds to the ``external_vpn_gateway`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -501,10 +494,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetExternalVpnGatewayRequest): request = compute.GetExternalVpnGatewayRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if external_vpn_gateway is not None: @@ -548,7 +539,6 @@ def insert( This corresponds to the ``external_vpn_gateway_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. @@ -600,10 +590,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertExternalVpnGatewayRequest): request = compute.InsertExternalVpnGatewayRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if external_vpn_gateway_resource is not None: @@ -641,7 +629,6 @@ def list( 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. @@ -673,10 +660,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListExternalVpnGatewaysRequest): request = compute.ListExternalVpnGatewaysRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -733,7 +718,6 @@ def set_labels( 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. @@ -787,10 +771,8 @@ def set_labels( # there are no flattened fields. if not isinstance(request, compute.SetLabelsExternalVpnGatewayRequest): request = compute.SetLabelsExternalVpnGatewayRequest(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: @@ -846,7 +828,6 @@ def test_iam_permissions( 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. @@ -875,10 +856,8 @@ def test_iam_permissions( # there are no flattened fields. if not isinstance(request, compute.TestIamPermissionsExternalVpnGatewayRequest): request = compute.TestIamPermissionsExternalVpnGatewayRequest(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: diff --git a/google/cloud/compute_v1/services/external_vpn_gateways/pagers.py b/google/cloud/compute_v1/services/external_vpn_gateways/pagers.py index f60ab239f..a3c76c923 100644 --- a/google/cloud/compute_v1/services/external_vpn_gateways/pagers.py +++ b/google/cloud/compute_v1/services/external_vpn_gateways/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/external_vpn_gateways/transports/__init__.py b/google/cloud/compute_v1/services/external_vpn_gateways/transports/__init__.py index f01bf40c1..bf8983c99 100644 --- a/google/cloud/compute_v1/services/external_vpn_gateways/transports/__init__.py +++ b/google/cloud/compute_v1/services/external_vpn_gateways/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/external_vpn_gateways/transports/base.py b/google/cloud/compute_v1/services/external_vpn_gateways/transports/base.py index 3b13ec798..f22510198 100644 --- a/google/cloud/compute_v1/services/external_vpn_gateways/transports/base.py +++ b/google/cloud/compute_v1/services/external_vpn_gateways/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class ExternalVpnGatewaysTransport(abc.ABC): """Abstract transport class for ExternalVpnGateways.""" @@ -44,21 +54,24 @@ class ExternalVpnGatewaysTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -132,40 +192,37 @@ def _prep_wrapped_messages(self, client_info): @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteExternalVpnGatewayRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetExternalVpnGatewayRequest], - typing.Union[ - compute.ExternalVpnGateway, typing.Awaitable[compute.ExternalVpnGateway] - ], + Union[compute.ExternalVpnGateway, Awaitable[compute.ExternalVpnGateway]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertExternalVpnGatewayRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListExternalVpnGatewaysRequest], - typing.Union[ - compute.ExternalVpnGatewayList, - typing.Awaitable[compute.ExternalVpnGatewayList], + Union[ + compute.ExternalVpnGatewayList, Awaitable[compute.ExternalVpnGatewayList] ], ]: raise NotImplementedError() @@ -173,20 +230,19 @@ def list( @property def set_labels( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetLabelsExternalVpnGatewayRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.TestIamPermissionsExternalVpnGatewayRequest], - typing.Union[ - compute.TestPermissionsResponse, - typing.Awaitable[compute.TestPermissionsResponse], + Union[ + compute.TestPermissionsResponse, Awaitable[compute.TestPermissionsResponse] ], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/external_vpn_gateways/transports/rest.py b/google/cloud/compute_v1/services/external_vpn_gateways/transports/rest.py index f05367b43..920eea86a 100644 --- a/google/cloud/compute_v1/services/external_vpn_gateways/transports/rest.py +++ b/google/cloud/compute_v1/services/external_vpn_gateways/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 ExternalVpnGatewaysTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def delete( Args: request (~.compute.DeleteExternalVpnGatewayRequest): - The request object. - A request message for + The request object. A request message for ExternalVpnGateways.Delete. See the method description for details. @@ -154,19 +153,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteExternalVpnGatewayRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -184,8 +182,7 @@ def get( Args: request (~.compute.GetExternalVpnGatewayRequest): - The request object. - A request message for + The request object. A request message for ExternalVpnGateways.Get. See the method description for details. @@ -223,16 +220,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -252,8 +248,7 @@ def insert( Args: request (~.compute.InsertExternalVpnGatewayRequest): - The request object. - A request message for + The request object. A request message for ExternalVpnGateways.Insert. See the method description for details. @@ -308,15 +303,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertExternalVpnGatewayRequest.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() if v - ] + 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 @@ -338,8 +332,7 @@ def list( Args: request (~.compute.ListExternalVpnGatewaysRequest): - The request object. - A request message for + The request object. A request message for ExternalVpnGateways.List. See the method description for details. @@ -361,23 +354,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListExternalVpnGatewaysRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListExternalVpnGatewaysRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListExternalVpnGatewaysRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListExternalVpnGatewaysRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListExternalVpnGatewaysRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -397,8 +393,7 @@ def set_labels( Args: request (~.compute.SetLabelsExternalVpnGatewayRequest): - The request object. - A request message for + The request object. A request message for ExternalVpnGateways.SetLabels. See the method description for details. @@ -454,12 +449,11 @@ def set_labels( # 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() if v - ] + 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 @@ -481,8 +475,7 @@ def test_iam_permissions( Args: request (~.compute.TestIamPermissionsExternalVpnGatewayRequest): - The request object. - A request message for + The request object. A request message for ExternalVpnGateways.TestIamPermissions. See the method description for details. @@ -510,12 +503,11 @@ def test_iam_permissions( # 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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/firewalls/__init__.py b/google/cloud/compute_v1/services/firewalls/__init__.py index 551e86446..a3c66de4f 100644 --- a/google/cloud/compute_v1/services/firewalls/__init__.py +++ b/google/cloud/compute_v1/services/firewalls/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import FirewallsClient __all__ = ("FirewallsClient",) diff --git a/google/cloud/compute_v1/services/firewalls/client.py b/google/cloud/compute_v1/services/firewalls/client.py index c55222076..5195d229c 100644 --- a/google/cloud/compute_v1/services/firewalls/client.py +++ b/google/cloud/compute_v1/services/firewalls/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.firewalls import pagers from google.cloud.compute_v1.types import compute - from .transports.base import FirewallsTransport, DEFAULT_CLIENT_INFO from .transports.rest import FirewallsRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, FirewallsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -350,7 +347,6 @@ def delete( This corresponds to the ``firewall`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -402,10 +398,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteFirewallRequest): request = compute.DeleteFirewallRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if firewall is not None: @@ -447,7 +441,6 @@ def get( This corresponds to the ``firewall`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -479,10 +472,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetFirewallRequest): request = compute.GetFirewallRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if firewall is not None: @@ -526,7 +517,6 @@ def insert( This corresponds to the ``firewall_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. @@ -578,10 +568,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertFirewallRequest): request = compute.InsertFirewallRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if firewall_resource is not None: @@ -618,7 +606,6 @@ def list( 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. @@ -649,10 +636,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListFirewallsRequest): request = compute.ListFirewallsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -707,7 +692,6 @@ def patch( This corresponds to the ``firewall_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. @@ -759,10 +743,8 @@ def patch( # there are no flattened fields. if not isinstance(request, compute.PatchFirewallRequest): request = compute.PatchFirewallRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if firewall is not None: @@ -817,7 +799,6 @@ def update( This corresponds to the ``firewall_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. @@ -869,10 +850,8 @@ def update( # there are no flattened fields. if not isinstance(request, compute.UpdateFirewallRequest): request = compute.UpdateFirewallRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if firewall is not None: diff --git a/google/cloud/compute_v1/services/firewalls/pagers.py b/google/cloud/compute_v1/services/firewalls/pagers.py index ff2937ad2..675df6778 100644 --- a/google/cloud/compute_v1/services/firewalls/pagers.py +++ b/google/cloud/compute_v1/services/firewalls/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/firewalls/transports/__init__.py b/google/cloud/compute_v1/services/firewalls/transports/__init__.py index ac8419a9e..8f13e6e92 100644 --- a/google/cloud/compute_v1/services/firewalls/transports/__init__.py +++ b/google/cloud/compute_v1/services/firewalls/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/firewalls/transports/base.py b/google/cloud/compute_v1/services/firewalls/transports/base.py index db5a51893..9ccefbb43 100644 --- a/google/cloud/compute_v1/services/firewalls/transports/base.py +++ b/google/cloud/compute_v1/services/firewalls/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class FirewallsTransport(abc.ABC): """Abstract transport class for Firewalls.""" @@ -44,21 +54,24 @@ class FirewallsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -130,54 +190,54 @@ def _prep_wrapped_messages(self, client_info): @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteFirewallRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetFirewallRequest], - typing.Union[compute.Firewall, typing.Awaitable[compute.Firewall]], + Union[compute.Firewall, Awaitable[compute.Firewall]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertFirewallRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListFirewallsRequest], - typing.Union[compute.FirewallList, typing.Awaitable[compute.FirewallList]], + Union[compute.FirewallList, Awaitable[compute.FirewallList]], ]: raise NotImplementedError() @property def patch( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchFirewallRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def update( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.UpdateFirewallRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/firewalls/transports/rest.py b/google/cloud/compute_v1/services/firewalls/transports/rest.py index 0dcc9d27f..ba9e66cfd 100644 --- a/google/cloud/compute_v1/services/firewalls/transports/rest.py +++ b/google/cloud/compute_v1/services/firewalls/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 FirewallsTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def delete( Args: request (~.compute.DeleteFirewallRequest): - The request object. - A request message for + The request object. A request message for Firewalls.Delete. See the method description for details. @@ -152,19 +151,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteFirewallRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -182,8 +180,7 @@ def get( Args: request (~.compute.GetFirewallRequest): - The request object. - A request message for Firewalls.Get. + The request object. A request message for Firewalls.Get. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -208,16 +205,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -235,8 +231,7 @@ def insert( Args: request (~.compute.InsertFirewallRequest): - The request object. - A request message for + The request object. A request message for Firewalls.Insert. See the method description for details. @@ -291,15 +286,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertFirewallRequest.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() if v - ] + 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 @@ -321,8 +315,7 @@ def list( Args: request (~.compute.ListFirewallsRequest): - The request object. - A request message for Firewalls.List. + The request object. A request message for Firewalls.List. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -341,23 +334,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListFirewallsRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListFirewallsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListFirewallsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListFirewallsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListFirewallsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -377,8 +373,7 @@ def patch( Args: request (~.compute.PatchFirewallRequest): - The request object. - A request message for + The request object. A request message for Firewalls.Patch. See the method description for details. @@ -433,15 +428,14 @@ def patch( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.PatchFirewallRequest.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() if v - ] + 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 @@ -463,8 +457,7 @@ def update( Args: request (~.compute.UpdateFirewallRequest): - The request object. - A request message for + The request object. A request message for Firewalls.Update. See the method description for details. @@ -519,15 +512,14 @@ def update( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.UpdateFirewallRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/forwarding_rules/__init__.py b/google/cloud/compute_v1/services/forwarding_rules/__init__.py index 0805df2dd..053b4063c 100644 --- a/google/cloud/compute_v1/services/forwarding_rules/__init__.py +++ b/google/cloud/compute_v1/services/forwarding_rules/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import ForwardingRulesClient __all__ = ("ForwardingRulesClient",) diff --git a/google/cloud/compute_v1/services/forwarding_rules/client.py b/google/cloud/compute_v1/services/forwarding_rules/client.py index f8f13b563..20206460a 100644 --- a/google/cloud/compute_v1/services/forwarding_rules/client.py +++ b/google/cloud/compute_v1/services/forwarding_rules/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.forwarding_rules import pagers from google.cloud.compute_v1.types import compute - from .transports.base import ForwardingRulesTransport, DEFAULT_CLIENT_INFO from .transports.rest import ForwardingRulesRestTransport @@ -215,7 +212,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ForwardingRulesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -346,7 +343,6 @@ def aggregated_list( 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. @@ -376,10 +372,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListForwardingRulesRequest): request = compute.AggregatedListForwardingRulesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -436,7 +430,6 @@ def delete( This corresponds to the ``forwarding_rule`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -488,10 +481,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteForwardingRuleRequest): request = compute.DeleteForwardingRuleRequest(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: @@ -546,7 +537,6 @@ def get( This corresponds to the ``forwarding_rule`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -595,10 +585,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetForwardingRuleRequest): request = compute.GetForwardingRuleRequest(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: @@ -653,7 +641,6 @@ def insert( This corresponds to the ``forwarding_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. @@ -705,10 +692,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertForwardingRuleRequest): request = compute.InsertForwardingRuleRequest(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: @@ -756,7 +741,6 @@ def list( 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. @@ -788,10 +772,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListForwardingRulesRequest): request = compute.ListForwardingRulesRequest(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: @@ -859,7 +841,6 @@ def patch( This corresponds to the ``forwarding_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. @@ -913,10 +894,8 @@ def patch( # there are no flattened fields. if not isinstance(request, compute.PatchForwardingRuleRequest): request = compute.PatchForwardingRuleRequest(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: @@ -980,7 +959,6 @@ def set_target( This corresponds to the ``target_reference_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. @@ -1034,10 +1012,8 @@ def set_target( # there are no flattened fields. if not isinstance(request, compute.SetTargetForwardingRuleRequest): request = compute.SetTargetForwardingRuleRequest(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: diff --git a/google/cloud/compute_v1/services/forwarding_rules/pagers.py b/google/cloud/compute_v1/services/forwarding_rules/pagers.py index 0320a5ac5..87af6c676 100644 --- a/google/cloud/compute_v1/services/forwarding_rules/pagers.py +++ b/google/cloud/compute_v1/services/forwarding_rules/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/forwarding_rules/transports/__init__.py b/google/cloud/compute_v1/services/forwarding_rules/transports/__init__.py index 840f258a8..2247c9fa2 100644 --- a/google/cloud/compute_v1/services/forwarding_rules/transports/__init__.py +++ b/google/cloud/compute_v1/services/forwarding_rules/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/forwarding_rules/transports/base.py b/google/cloud/compute_v1/services/forwarding_rules/transports/base.py index b14ed5c4c..bee99777b 100644 --- a/google/cloud/compute_v1/services/forwarding_rules/transports/base.py +++ b/google/cloud/compute_v1/services/forwarding_rules/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class ForwardingRulesTransport(abc.ABC): """Abstract transport class for ForwardingRules.""" @@ -44,21 +54,24 @@ class ForwardingRulesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -133,11 +193,11 @@ def _prep_wrapped_messages(self, client_info): @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListForwardingRulesRequest], - typing.Union[ + Union[ compute.ForwardingRuleAggregatedList, - typing.Awaitable[compute.ForwardingRuleAggregatedList], + Awaitable[compute.ForwardingRuleAggregatedList], ], ]: raise NotImplementedError() @@ -145,56 +205,54 @@ def aggregated_list( @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteForwardingRuleRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetForwardingRuleRequest], - typing.Union[compute.ForwardingRule, typing.Awaitable[compute.ForwardingRule]], + Union[compute.ForwardingRule, Awaitable[compute.ForwardingRule]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertForwardingRuleRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListForwardingRulesRequest], - typing.Union[ - compute.ForwardingRuleList, typing.Awaitable[compute.ForwardingRuleList] - ], + Union[compute.ForwardingRuleList, Awaitable[compute.ForwardingRuleList]], ]: raise NotImplementedError() @property def patch( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchForwardingRuleRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_target( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetTargetForwardingRuleRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/forwarding_rules/transports/rest.py b/google/cloud/compute_v1/services/forwarding_rules/transports/rest.py index 848155634..0a89f355e 100644 --- a/google/cloud/compute_v1/services/forwarding_rules/transports/rest.py +++ b/google/cloud/compute_v1/services/forwarding_rules/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 ForwardingRulesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListForwardingRulesRequest): - The request object. - A request message for + The request object. A request message for ForwardingRules.AggregatedList. See the method description for details. @@ -124,24 +123,31 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListForwardingRulesRequest.filter in request: + query_params["filter"] = request.filter + if compute.AggregatedListForwardingRulesRequest.include_all_scopes in request: + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListForwardingRulesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListForwardingRulesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListForwardingRulesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if ( + compute.AggregatedListForwardingRulesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -161,8 +167,7 @@ def delete( Args: request (~.compute.DeleteForwardingRuleRequest): - The request object. - A request message for + The request object. A request message for ForwardingRules.Delete. See the method description for details. @@ -213,19 +218,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteForwardingRuleRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -243,8 +247,7 @@ def get( Args: request (~.compute.GetForwardingRuleRequest): - The request object. - A request message for + The request object. A request message for ForwardingRules.Get. See the method description for details. @@ -290,16 +293,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -319,8 +321,7 @@ def insert( Args: request (~.compute.InsertForwardingRuleRequest): - The request object. - A request message for + The request object. A request message for ForwardingRules.Insert. See the method description for details. @@ -375,15 +376,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertForwardingRuleRequest.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() if v - ] + 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 @@ -405,8 +405,7 @@ def list( Args: request (~.compute.ListForwardingRulesRequest): - The request object. - A request message for + The request object. A request message for ForwardingRules.List. See the method description for details. @@ -428,23 +427,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListForwardingRulesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListForwardingRulesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListForwardingRulesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListForwardingRulesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListForwardingRulesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -464,8 +466,7 @@ def patch( Args: request (~.compute.PatchForwardingRuleRequest): - The request object. - A request message for + The request object. A request message for ForwardingRules.Patch. See the method description for details. @@ -523,15 +524,14 @@ def patch( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.PatchForwardingRuleRequest.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() if v - ] + 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 @@ -553,8 +553,7 @@ def set_target( Args: request (~.compute.SetTargetForwardingRuleRequest): - The request object. - A request message for + The request object. A request message for ForwardingRules.SetTarget. See the method description for details. @@ -612,15 +611,14 @@ def set_target( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetTargetForwardingRuleRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/global_addresses/__init__.py b/google/cloud/compute_v1/services/global_addresses/__init__.py index cbff17919..ecef70563 100644 --- a/google/cloud/compute_v1/services/global_addresses/__init__.py +++ b/google/cloud/compute_v1/services/global_addresses/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import GlobalAddressesClient __all__ = ("GlobalAddressesClient",) diff --git a/google/cloud/compute_v1/services/global_addresses/client.py b/google/cloud/compute_v1/services/global_addresses/client.py index 618993128..70e8ecc7b 100644 --- a/google/cloud/compute_v1/services/global_addresses/client.py +++ b/google/cloud/compute_v1/services/global_addresses/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.global_addresses import pagers from google.cloud.compute_v1.types import compute - from .transports.base import GlobalAddressesTransport, DEFAULT_CLIENT_INFO from .transports.rest import GlobalAddressesRestTransport @@ -215,7 +212,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, GlobalAddressesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -354,7 +351,6 @@ def delete( This corresponds to the ``address`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -406,10 +402,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteGlobalAddressRequest): request = compute.DeleteGlobalAddressRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if address is not None: @@ -455,7 +449,6 @@ def get( This corresponds to the ``address`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -511,10 +504,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetGlobalAddressRequest): request = compute.GetGlobalAddressRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if address is not None: @@ -558,7 +549,6 @@ def insert( This corresponds to the ``address_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. @@ -610,10 +600,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertGlobalAddressRequest): request = compute.InsertGlobalAddressRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if address_resource is not None: @@ -650,7 +638,6 @@ def list( 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. @@ -681,10 +668,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListGlobalAddressesRequest): request = compute.ListGlobalAddressesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project diff --git a/google/cloud/compute_v1/services/global_addresses/pagers.py b/google/cloud/compute_v1/services/global_addresses/pagers.py index 2428e6bed..b5d65118e 100644 --- a/google/cloud/compute_v1/services/global_addresses/pagers.py +++ b/google/cloud/compute_v1/services/global_addresses/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/global_addresses/transports/__init__.py b/google/cloud/compute_v1/services/global_addresses/transports/__init__.py index 465a473eb..eb9bc0c28 100644 --- a/google/cloud/compute_v1/services/global_addresses/transports/__init__.py +++ b/google/cloud/compute_v1/services/global_addresses/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/global_addresses/transports/base.py b/google/cloud/compute_v1/services/global_addresses/transports/base.py index beb83ab1d..7933a8026 100644 --- a/google/cloud/compute_v1/services/global_addresses/transports/base.py +++ b/google/cloud/compute_v1/services/global_addresses/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class GlobalAddressesTransport(abc.ABC): """Abstract transport class for GlobalAddresses.""" @@ -44,21 +54,24 @@ class GlobalAddressesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -124,36 +184,36 @@ def _prep_wrapped_messages(self, client_info): @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteGlobalAddressRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetGlobalAddressRequest], - typing.Union[compute.Address, typing.Awaitable[compute.Address]], + Union[compute.Address, Awaitable[compute.Address]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertGlobalAddressRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListGlobalAddressesRequest], - typing.Union[compute.AddressList, typing.Awaitable[compute.AddressList]], + Union[compute.AddressList, Awaitable[compute.AddressList]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/global_addresses/transports/rest.py b/google/cloud/compute_v1/services/global_addresses/transports/rest.py index 42b2f9913..443d4516f 100644 --- a/google/cloud/compute_v1/services/global_addresses/transports/rest.py +++ b/google/cloud/compute_v1/services/global_addresses/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 GlobalAddressesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def delete( Args: request (~.compute.DeleteGlobalAddressRequest): - The request object. - A request message for + The request object. A request message for GlobalAddresses.Delete. See the method description for details. @@ -152,19 +151,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteGlobalAddressRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -182,8 +180,7 @@ def get( Args: request (~.compute.GetGlobalAddressRequest): - The request object. - A request message for + The request object. A request message for GlobalAddresses.Get. See the method description for details. @@ -232,16 +229,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -259,8 +255,7 @@ def insert( Args: request (~.compute.InsertGlobalAddressRequest): - The request object. - A request message for + The request object. A request message for GlobalAddresses.Insert. See the method description for details. @@ -315,15 +310,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertGlobalAddressRequest.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() if v - ] + 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 @@ -345,8 +339,7 @@ def list( Args: request (~.compute.ListGlobalAddressesRequest): - The request object. - A request message for + The request object. A request message for GlobalAddresses.List. See the method description for details. @@ -366,23 +359,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListGlobalAddressesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListGlobalAddressesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListGlobalAddressesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListGlobalAddressesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListGlobalAddressesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() diff --git a/google/cloud/compute_v1/services/global_forwarding_rules/__init__.py b/google/cloud/compute_v1/services/global_forwarding_rules/__init__.py index 020e1962d..4ffbec235 100644 --- a/google/cloud/compute_v1/services/global_forwarding_rules/__init__.py +++ b/google/cloud/compute_v1/services/global_forwarding_rules/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import GlobalForwardingRulesClient __all__ = ("GlobalForwardingRulesClient",) diff --git a/google/cloud/compute_v1/services/global_forwarding_rules/client.py b/google/cloud/compute_v1/services/global_forwarding_rules/client.py index a9f7c1a2d..8b435bc85 100644 --- a/google/cloud/compute_v1/services/global_forwarding_rules/client.py +++ b/google/cloud/compute_v1/services/global_forwarding_rules/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.global_forwarding_rules import pagers from google.cloud.compute_v1.types import compute - from .transports.base import GlobalForwardingRulesTransport, DEFAULT_CLIENT_INFO from .transports.rest import GlobalForwardingRulesRestTransport @@ -217,7 +214,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, GlobalForwardingRulesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -356,7 +353,6 @@ def delete( This corresponds to the ``forwarding_rule`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -408,10 +404,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteGlobalForwardingRuleRequest): request = compute.DeleteGlobalForwardingRuleRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if forwarding_rule is not None: @@ -458,7 +452,6 @@ def get( This corresponds to the ``forwarding_rule`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -507,10 +500,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetGlobalForwardingRuleRequest): request = compute.GetGlobalForwardingRuleRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if forwarding_rule is not None: @@ -555,7 +546,6 @@ def insert( This corresponds to the ``forwarding_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. @@ -607,10 +597,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertGlobalForwardingRuleRequest): request = compute.InsertGlobalForwardingRuleRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if forwarding_rule_resource is not None: @@ -648,7 +636,6 @@ def list( 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. @@ -680,10 +667,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListGlobalForwardingRulesRequest): request = compute.ListGlobalForwardingRulesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -741,7 +726,6 @@ def patch( This corresponds to the ``forwarding_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. @@ -793,10 +777,8 @@ def patch( # there are no flattened fields. if not isinstance(request, compute.PatchGlobalForwardingRuleRequest): request = compute.PatchGlobalForwardingRuleRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if forwarding_rule is not None: @@ -851,7 +833,6 @@ def set_target( This corresponds to the ``target_reference_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. @@ -905,10 +886,8 @@ def set_target( # there are no flattened fields. if not isinstance(request, compute.SetTargetGlobalForwardingRuleRequest): request = compute.SetTargetGlobalForwardingRuleRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if forwarding_rule is not None: diff --git a/google/cloud/compute_v1/services/global_forwarding_rules/pagers.py b/google/cloud/compute_v1/services/global_forwarding_rules/pagers.py index f606d1c7e..e5019cd68 100644 --- a/google/cloud/compute_v1/services/global_forwarding_rules/pagers.py +++ b/google/cloud/compute_v1/services/global_forwarding_rules/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/global_forwarding_rules/transports/__init__.py b/google/cloud/compute_v1/services/global_forwarding_rules/transports/__init__.py index a2aeab3f2..bd63078b9 100644 --- a/google/cloud/compute_v1/services/global_forwarding_rules/transports/__init__.py +++ b/google/cloud/compute_v1/services/global_forwarding_rules/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/global_forwarding_rules/transports/base.py b/google/cloud/compute_v1/services/global_forwarding_rules/transports/base.py index 238033251..23a32b6b6 100644 --- a/google/cloud/compute_v1/services/global_forwarding_rules/transports/base.py +++ b/google/cloud/compute_v1/services/global_forwarding_rules/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class GlobalForwardingRulesTransport(abc.ABC): """Abstract transport class for GlobalForwardingRules.""" @@ -44,21 +54,24 @@ class GlobalForwardingRulesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -130,56 +190,54 @@ def _prep_wrapped_messages(self, client_info): @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteGlobalForwardingRuleRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetGlobalForwardingRuleRequest], - typing.Union[compute.ForwardingRule, typing.Awaitable[compute.ForwardingRule]], + Union[compute.ForwardingRule, Awaitable[compute.ForwardingRule]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertGlobalForwardingRuleRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListGlobalForwardingRulesRequest], - typing.Union[ - compute.ForwardingRuleList, typing.Awaitable[compute.ForwardingRuleList] - ], + Union[compute.ForwardingRuleList, Awaitable[compute.ForwardingRuleList]], ]: raise NotImplementedError() @property def patch( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchGlobalForwardingRuleRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_target( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetTargetGlobalForwardingRuleRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/global_forwarding_rules/transports/rest.py b/google/cloud/compute_v1/services/global_forwarding_rules/transports/rest.py index 63e5c2364..d07e82db7 100644 --- a/google/cloud/compute_v1/services/global_forwarding_rules/transports/rest.py +++ b/google/cloud/compute_v1/services/global_forwarding_rules/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 GlobalForwardingRulesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def delete( Args: request (~.compute.DeleteGlobalForwardingRuleRequest): - The request object. - A request message for + The request object. A request message for GlobalForwardingRules.Delete. See the method description for details. @@ -154,19 +153,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteGlobalForwardingRuleRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -184,8 +182,7 @@ def get( Args: request (~.compute.GetGlobalForwardingRuleRequest): - The request object. - A request message for + The request object. A request message for GlobalForwardingRules.Get. See the method description for details. @@ -230,16 +227,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -259,8 +255,7 @@ def insert( Args: request (~.compute.InsertGlobalForwardingRuleRequest): - The request object. - A request message for + The request object. A request message for GlobalForwardingRules.Insert. See the method description for details. @@ -315,15 +310,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertGlobalForwardingRuleRequest.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() if v - ] + 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 @@ -345,8 +339,7 @@ def list( Args: request (~.compute.ListGlobalForwardingRulesRequest): - The request object. - A request message for + The request object. A request message for GlobalForwardingRules.List. See the method description for details. @@ -368,23 +361,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListGlobalForwardingRulesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListGlobalForwardingRulesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListGlobalForwardingRulesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListGlobalForwardingRulesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListGlobalForwardingRulesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -404,8 +400,7 @@ def patch( Args: request (~.compute.PatchGlobalForwardingRuleRequest): - The request object. - A request message for + The request object. A request message for GlobalForwardingRules.Patch. See the method description for details. @@ -462,15 +457,14 @@ def patch( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.PatchGlobalForwardingRuleRequest.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() if v - ] + 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 @@ -492,8 +486,7 @@ def set_target( Args: request (~.compute.SetTargetGlobalForwardingRuleRequest): - The request object. - A request message for + The request object. A request message for GlobalForwardingRules.SetTarget. See the method description for details. @@ -550,15 +543,14 @@ def set_target( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetTargetGlobalForwardingRuleRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/global_network_endpoint_groups/__init__.py b/google/cloud/compute_v1/services/global_network_endpoint_groups/__init__.py index d9492f77d..b75ce6ae3 100644 --- a/google/cloud/compute_v1/services/global_network_endpoint_groups/__init__.py +++ b/google/cloud/compute_v1/services/global_network_endpoint_groups/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import GlobalNetworkEndpointGroupsClient __all__ = ("GlobalNetworkEndpointGroupsClient",) diff --git a/google/cloud/compute_v1/services/global_network_endpoint_groups/client.py b/google/cloud/compute_v1/services/global_network_endpoint_groups/client.py index d4a70db19..89dfd12cf 100644 --- a/google/cloud/compute_v1/services/global_network_endpoint_groups/client.py +++ b/google/cloud/compute_v1/services/global_network_endpoint_groups/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.global_network_endpoint_groups import pagers from google.cloud.compute_v1.types import compute - from .transports.base import GlobalNetworkEndpointGroupsTransport, DEFAULT_CLIENT_INFO from .transports.rest import GlobalNetworkEndpointGroupsRestTransport @@ -219,7 +216,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, GlobalNetworkEndpointGroupsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -367,7 +364,6 @@ def attach_network_endpoints( This corresponds to the ``global_network_endpoint_groups_attach_endpoints_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. @@ -429,10 +425,8 @@ def attach_network_endpoints( request = compute.AttachNetworkEndpointsGlobalNetworkEndpointGroupRequest( request ) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if network_endpoint_group is not None: @@ -487,7 +481,6 @@ def delete( This corresponds to the ``network_endpoint_group`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -539,10 +532,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteGlobalNetworkEndpointGroupRequest): request = compute.DeleteGlobalNetworkEndpointGroupRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if network_endpoint_group is not None: @@ -596,7 +587,6 @@ def detach_network_endpoints( This corresponds to the ``global_network_endpoint_groups_detach_endpoints_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. @@ -658,10 +648,8 @@ def detach_network_endpoints( request = compute.DetachNetworkEndpointsGlobalNetworkEndpointGroupRequest( request ) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if network_endpoint_group is not None: @@ -715,7 +703,6 @@ def get( This corresponds to the ``network_endpoint_group`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -756,10 +743,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetGlobalNetworkEndpointGroupRequest): request = compute.GetGlobalNetworkEndpointGroupRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if network_endpoint_group is not None: @@ -804,7 +789,6 @@ def insert( This corresponds to the ``network_endpoint_group_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. @@ -856,10 +840,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertGlobalNetworkEndpointGroupRequest): request = compute.InsertGlobalNetworkEndpointGroupRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if network_endpoint_group_resource is not None: @@ -899,7 +881,6 @@ def list( 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. @@ -929,10 +910,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListGlobalNetworkEndpointGroupsRequest): request = compute.ListGlobalNetworkEndpointGroupsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -984,7 +963,6 @@ def list_network_endpoints( This corresponds to the ``network_endpoint_group`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1018,10 +996,8 @@ def list_network_endpoints( request = compute.ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest( request ) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if network_endpoint_group is not None: diff --git a/google/cloud/compute_v1/services/global_network_endpoint_groups/pagers.py b/google/cloud/compute_v1/services/global_network_endpoint_groups/pagers.py index 551f20668..a7ccd93c7 100644 --- a/google/cloud/compute_v1/services/global_network_endpoint_groups/pagers.py +++ b/google/cloud/compute_v1/services/global_network_endpoint_groups/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/global_network_endpoint_groups/transports/__init__.py b/google/cloud/compute_v1/services/global_network_endpoint_groups/transports/__init__.py index 2f83d8801..9a80084b3 100644 --- a/google/cloud/compute_v1/services/global_network_endpoint_groups/transports/__init__.py +++ b/google/cloud/compute_v1/services/global_network_endpoint_groups/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/global_network_endpoint_groups/transports/base.py b/google/cloud/compute_v1/services/global_network_endpoint_groups/transports/base.py index 63cbe2a2d..abc9c4820 100644 --- a/google/cloud/compute_v1/services/global_network_endpoint_groups/transports/base.py +++ b/google/cloud/compute_v1/services/global_network_endpoint_groups/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class GlobalNetworkEndpointGroupsTransport(abc.ABC): """Abstract transport class for GlobalNetworkEndpointGroups.""" @@ -44,21 +54,24 @@ class GlobalNetworkEndpointGroupsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -139,58 +199,56 @@ def _prep_wrapped_messages(self, client_info): @property def attach_network_endpoints( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AttachNetworkEndpointsGlobalNetworkEndpointGroupRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteGlobalNetworkEndpointGroupRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def detach_network_endpoints( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DetachNetworkEndpointsGlobalNetworkEndpointGroupRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetGlobalNetworkEndpointGroupRequest], - typing.Union[ - compute.NetworkEndpointGroup, typing.Awaitable[compute.NetworkEndpointGroup] - ], + Union[compute.NetworkEndpointGroup, Awaitable[compute.NetworkEndpointGroup]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertGlobalNetworkEndpointGroupRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListGlobalNetworkEndpointGroupsRequest], - typing.Union[ + Union[ compute.NetworkEndpointGroupList, - typing.Awaitable[compute.NetworkEndpointGroupList], + Awaitable[compute.NetworkEndpointGroupList], ], ]: raise NotImplementedError() @@ -198,11 +256,11 @@ def list( @property def list_network_endpoints( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest], - typing.Union[ + Union[ compute.NetworkEndpointGroupsListNetworkEndpoints, - typing.Awaitable[compute.NetworkEndpointGroupsListNetworkEndpoints], + Awaitable[compute.NetworkEndpointGroupsListNetworkEndpoints], ], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/global_network_endpoint_groups/transports/rest.py b/google/cloud/compute_v1/services/global_network_endpoint_groups/transports/rest.py index 316ce70e5..7a599103f 100644 --- a/google/cloud/compute_v1/services/global_network_endpoint_groups/transports/rest.py +++ b/google/cloud/compute_v1/services/global_network_endpoint_groups/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 GlobalNetworkEndpointGroupsTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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 attach_network_endpoints( self, @@ -103,8 +103,7 @@ def attach_network_endpoints( Args: request (~.compute.AttachNetworkEndpointsGlobalNetworkEndpointGroupRequest): - The request object. - A request message for + The request object. A request message for GlobalNetworkEndpointGroups.AttachNetworkEndpoints. See the method description for details. @@ -161,15 +160,17 @@ def attach_network_endpoints( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if ( + compute.AttachNetworkEndpointsGlobalNetworkEndpointGroupRequest.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() if v - ] + 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 @@ -191,8 +192,7 @@ def delete( Args: request (~.compute.DeleteGlobalNetworkEndpointGroupRequest): - The request object. - A request message for + The request object. A request message for GlobalNetworkEndpointGroups.Delete. See the method description for details. @@ -242,19 +242,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteGlobalNetworkEndpointGroupRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -272,8 +271,7 @@ def detach_network_endpoints( Args: request (~.compute.DetachNetworkEndpointsGlobalNetworkEndpointGroupRequest): - The request object. - A request message for + The request object. A request message for GlobalNetworkEndpointGroups.DetachNetworkEndpoints. See the method description for details. @@ -330,15 +328,17 @@ def detach_network_endpoints( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if ( + compute.DetachNetworkEndpointsGlobalNetworkEndpointGroupRequest.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() if v - ] + 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 @@ -360,8 +360,7 @@ def get( Args: request (~.compute.GetGlobalNetworkEndpointGroupRequest): - The request object. - A request message for + The request object. A request message for GlobalNetworkEndpointGroups.Get. See the method description for details. @@ -397,16 +396,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -426,8 +424,7 @@ def insert( Args: request (~.compute.InsertGlobalNetworkEndpointGroupRequest): - The request object. - A request message for + The request object. A request message for GlobalNetworkEndpointGroups.Insert. See the method description for details. @@ -482,15 +479,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertGlobalNetworkEndpointGroupRequest.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() if v - ] + 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 @@ -512,8 +508,7 @@ def list( Args: request (~.compute.ListGlobalNetworkEndpointGroupsRequest): - The request object. - A request message for + The request object. A request message for GlobalNetworkEndpointGroups.List. See the method description for details. @@ -533,23 +528,29 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListGlobalNetworkEndpointGroupsRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListGlobalNetworkEndpointGroupsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListGlobalNetworkEndpointGroupsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListGlobalNetworkEndpointGroupsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if ( + compute.ListGlobalNetworkEndpointGroupsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -569,8 +570,7 @@ def list_network_endpoints( Args: request (~.compute.ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest): - The request object. - A request message for + The request object. A request message for GlobalNetworkEndpointGroups.ListNetworkEndpoints. See the method description for details. @@ -592,23 +592,41 @@ def list_network_endpoints( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if ( + compute.ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest.filter + in request + ): + query_params["filter"] = request.filter + if ( + compute.ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest.max_results + in request + ): + query_params["maxResults"] = request.max_results + if ( + compute.ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest.order_by + in request + ): + query_params["orderBy"] = request.order_by + if ( + compute.ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest.page_token + in request + ): + query_params["pageToken"] = request.page_token + if ( + compute.ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest.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() if v - ] + 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 - response = self._session.post(url) + response = self._session.post(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() diff --git a/google/cloud/compute_v1/services/global_operations/__init__.py b/google/cloud/compute_v1/services/global_operations/__init__.py index e9d752f14..b978133b3 100644 --- a/google/cloud/compute_v1/services/global_operations/__init__.py +++ b/google/cloud/compute_v1/services/global_operations/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import GlobalOperationsClient __all__ = ("GlobalOperationsClient",) diff --git a/google/cloud/compute_v1/services/global_operations/client.py b/google/cloud/compute_v1/services/global_operations/client.py index c434d8215..52239171c 100644 --- a/google/cloud/compute_v1/services/global_operations/client.py +++ b/google/cloud/compute_v1/services/global_operations/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.global_operations import pagers from google.cloud.compute_v1.types import compute - from .transports.base import GlobalOperationsTransport, DEFAULT_CLIENT_INFO from .transports.rest import GlobalOperationsRestTransport @@ -215,7 +212,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, GlobalOperationsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -346,7 +343,6 @@ def aggregated_list( 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. @@ -376,10 +372,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListGlobalOperationsRequest): request = compute.AggregatedListGlobalOperationsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -428,7 +422,6 @@ def delete( This corresponds to the ``operation`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -458,10 +451,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteGlobalOperationRequest): request = compute.DeleteGlobalOperationRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if operation is not None: @@ -507,7 +498,6 @@ def get( This corresponds to the ``operation`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -559,10 +549,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetGlobalOperationRequest): request = compute.GetGlobalOperationRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if operation is not None: @@ -600,7 +588,6 @@ def list( 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. @@ -632,10 +619,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListGlobalOperationsRequest): request = compute.ListGlobalOperationsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -698,7 +683,6 @@ def wait( This corresponds to the ``operation`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -750,10 +734,8 @@ def wait( # there are no flattened fields. if not isinstance(request, compute.WaitGlobalOperationRequest): request = compute.WaitGlobalOperationRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if operation is not None: diff --git a/google/cloud/compute_v1/services/global_operations/pagers.py b/google/cloud/compute_v1/services/global_operations/pagers.py index 3acc037f2..3c37f2037 100644 --- a/google/cloud/compute_v1/services/global_operations/pagers.py +++ b/google/cloud/compute_v1/services/global_operations/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/global_operations/transports/__init__.py b/google/cloud/compute_v1/services/global_operations/transports/__init__.py index c7a900ad0..5a757ff02 100644 --- a/google/cloud/compute_v1/services/global_operations/transports/__init__.py +++ b/google/cloud/compute_v1/services/global_operations/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/global_operations/transports/base.py b/google/cloud/compute_v1/services/global_operations/transports/base.py index 85ec14be4..6a7e5f352 100644 --- a/google/cloud/compute_v1/services/global_operations/transports/base.py +++ b/google/cloud/compute_v1/services/global_operations/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class GlobalOperationsTransport(abc.ABC): """Abstract transport class for GlobalOperations.""" @@ -44,21 +54,24 @@ class GlobalOperationsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -127,11 +187,10 @@ def _prep_wrapped_messages(self, client_info): @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListGlobalOperationsRequest], - typing.Union[ - compute.OperationAggregatedList, - typing.Awaitable[compute.OperationAggregatedList], + Union[ + compute.OperationAggregatedList, Awaitable[compute.OperationAggregatedList] ], ]: raise NotImplementedError() @@ -139,11 +198,11 @@ def aggregated_list( @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteGlobalOperationRequest], - typing.Union[ + Union[ compute.DeleteGlobalOperationResponse, - typing.Awaitable[compute.DeleteGlobalOperationResponse], + Awaitable[compute.DeleteGlobalOperationResponse], ], ]: raise NotImplementedError() @@ -151,27 +210,27 @@ def delete( @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetGlobalOperationRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListGlobalOperationsRequest], - typing.Union[compute.OperationList, typing.Awaitable[compute.OperationList]], + Union[compute.OperationList, Awaitable[compute.OperationList]], ]: raise NotImplementedError() @property def wait( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.WaitGlobalOperationRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/global_operations/transports/rest.py b/google/cloud/compute_v1/services/global_operations/transports/rest.py index dbf1c8336..f47f32e9e 100644 --- a/google/cloud/compute_v1/services/global_operations/transports/rest.py +++ b/google/cloud/compute_v1/services/global_operations/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 GlobalOperationsTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListGlobalOperationsRequest): - The request object. - A request message for + The request object. A request message for GlobalOperations.AggregatedList. See the method description for details. @@ -124,24 +123,31 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListGlobalOperationsRequest.filter in request: + query_params["filter"] = request.filter + if compute.AggregatedListGlobalOperationsRequest.include_all_scopes in request: + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListGlobalOperationsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListGlobalOperationsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListGlobalOperationsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if ( + compute.AggregatedListGlobalOperationsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -161,8 +167,7 @@ def delete( Args: request (~.compute.DeleteGlobalOperationRequest): - The request object. - A request message for + The request object. A request message for GlobalOperations.Delete. See the method description for details. @@ -186,16 +191,15 @@ def delete( # 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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -215,8 +219,7 @@ def get( Args: request (~.compute.GetGlobalOperationRequest): - The request object. - A request message for + The request object. A request message for GlobalOperations.Get. See the method description for details. @@ -265,16 +268,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -292,8 +294,7 @@ def list( Args: request (~.compute.ListGlobalOperationsRequest): - The request object. - A request message for + The request object. A request message for GlobalOperations.List. See the method description for details. @@ -315,23 +316,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListGlobalOperationsRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListGlobalOperationsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListGlobalOperationsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListGlobalOperationsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListGlobalOperationsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -351,8 +355,7 @@ def wait( Args: request (~.compute.WaitGlobalOperationRequest): - The request object. - A request message for + The request object. A request message for GlobalOperations.Wait. See the method description for details. @@ -401,16 +404,15 @@ def wait( # 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() if v - ] + 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 - response = self._session.post(url) + response = self._session.post(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() diff --git a/google/cloud/compute_v1/services/global_organization_operations/__init__.py b/google/cloud/compute_v1/services/global_organization_operations/__init__.py index da4fdd0c7..3f1da89ca 100644 --- a/google/cloud/compute_v1/services/global_organization_operations/__init__.py +++ b/google/cloud/compute_v1/services/global_organization_operations/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import GlobalOrganizationOperationsClient __all__ = ("GlobalOrganizationOperationsClient",) diff --git a/google/cloud/compute_v1/services/global_organization_operations/client.py b/google/cloud/compute_v1/services/global_organization_operations/client.py index 6ca1466bc..3a3a87cea 100644 --- a/google/cloud/compute_v1/services/global_organization_operations/client.py +++ b/google/cloud/compute_v1/services/global_organization_operations/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.global_organization_operations import pagers from google.cloud.compute_v1.types import compute - from .transports.base import GlobalOrganizationOperationsTransport, DEFAULT_CLIENT_INFO from .transports.rest import GlobalOrganizationOperationsRestTransport @@ -219,7 +216,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, GlobalOrganizationOperationsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -352,7 +349,6 @@ def delete( This corresponds to the ``operation`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -382,10 +378,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteGlobalOrganizationOperationRequest): request = compute.DeleteGlobalOrganizationOperationRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if operation is not None: request.operation = operation @@ -423,7 +417,6 @@ def get( This corresponds to the ``operation`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -475,10 +468,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetGlobalOrganizationOperationRequest): request = compute.GetGlobalOrganizationOperationRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if operation is not None: request.operation = operation @@ -508,7 +499,6 @@ def list( The request object. A request message for GlobalOrganizationOperations.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. @@ -525,7 +515,6 @@ def list( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a compute.ListGlobalOrganizationOperationsRequest. # There's no risk of modifying the input as we've already verified diff --git a/google/cloud/compute_v1/services/global_organization_operations/pagers.py b/google/cloud/compute_v1/services/global_organization_operations/pagers.py index 30b420d47..abef18dba 100644 --- a/google/cloud/compute_v1/services/global_organization_operations/pagers.py +++ b/google/cloud/compute_v1/services/global_organization_operations/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/global_organization_operations/transports/__init__.py b/google/cloud/compute_v1/services/global_organization_operations/transports/__init__.py index e7da8591f..f6f510116 100644 --- a/google/cloud/compute_v1/services/global_organization_operations/transports/__init__.py +++ b/google/cloud/compute_v1/services/global_organization_operations/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/global_organization_operations/transports/base.py b/google/cloud/compute_v1/services/global_organization_operations/transports/base.py index 3fb2829e2..ef78ef50a 100644 --- a/google/cloud/compute_v1/services/global_organization_operations/transports/base.py +++ b/google/cloud/compute_v1/services/global_organization_operations/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class GlobalOrganizationOperationsTransport(abc.ABC): """Abstract transport class for GlobalOrganizationOperations.""" @@ -44,21 +54,24 @@ class GlobalOrganizationOperationsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -121,11 +181,11 @@ def _prep_wrapped_messages(self, client_info): @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteGlobalOrganizationOperationRequest], - typing.Union[ + Union[ compute.DeleteGlobalOrganizationOperationResponse, - typing.Awaitable[compute.DeleteGlobalOrganizationOperationResponse], + Awaitable[compute.DeleteGlobalOrganizationOperationResponse], ], ]: raise NotImplementedError() @@ -133,18 +193,18 @@ def delete( @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetGlobalOrganizationOperationRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListGlobalOrganizationOperationsRequest], - typing.Union[compute.OperationList, typing.Awaitable[compute.OperationList]], + Union[compute.OperationList, Awaitable[compute.OperationList]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/global_organization_operations/transports/rest.py b/google/cloud/compute_v1/services/global_organization_operations/transports/rest.py index 1f275a59d..f92e7e235 100644 --- a/google/cloud/compute_v1/services/global_organization_operations/transports/rest.py +++ b/google/cloud/compute_v1/services/global_organization_operations/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 GlobalOrganizationOperationsTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def delete( Args: request (~.compute.DeleteGlobalOrganizationOperationRequest): - The request object. - A request message for + The request object. A request message for GlobalOrganizationOperations.Delete. See the method description for details. @@ -127,19 +126,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "parentId": request.parent_id, - } + query_params = {} + if compute.DeleteGlobalOrganizationOperationRequest.parent_id in request: + query_params["parentId"] = request.parent_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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -159,8 +157,7 @@ def get( Args: request (~.compute.GetGlobalOrganizationOperationRequest): - The request object. - A request message for + The request object. A request message for GlobalOrganizationOperations.Get. See the method description for details. @@ -208,19 +205,18 @@ def get( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "parentId": request.parent_id, - } + query_params = {} + if compute.GetGlobalOrganizationOperationRequest.parent_id in request: + query_params["parentId"] = request.parent_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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -238,8 +234,7 @@ def list( Args: request (~.compute.ListGlobalOrganizationOperationsRequest): - The request object. - A request message for + The request object. A request message for GlobalOrganizationOperations.List. See the method description for details. @@ -261,24 +256,31 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "parentId": request.parent_id, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListGlobalOrganizationOperationsRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListGlobalOrganizationOperationsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListGlobalOrganizationOperationsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListGlobalOrganizationOperationsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListGlobalOrganizationOperationsRequest.parent_id in request: + query_params["parentId"] = request.parent_id + if ( + compute.ListGlobalOrganizationOperationsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() diff --git a/google/cloud/compute_v1/services/health_checks/__init__.py b/google/cloud/compute_v1/services/health_checks/__init__.py index e71cd3ae4..58cf9e323 100644 --- a/google/cloud/compute_v1/services/health_checks/__init__.py +++ b/google/cloud/compute_v1/services/health_checks/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import HealthChecksClient __all__ = ("HealthChecksClient",) diff --git a/google/cloud/compute_v1/services/health_checks/client.py b/google/cloud/compute_v1/services/health_checks/client.py index de3f512b5..9747cb710 100644 --- a/google/cloud/compute_v1/services/health_checks/client.py +++ b/google/cloud/compute_v1/services/health_checks/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.health_checks import pagers from google.cloud.compute_v1.types import compute - from .transports.base import HealthChecksTransport, DEFAULT_CLIENT_INFO from .transports.rest import HealthChecksRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, HealthChecksTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -347,7 +344,6 @@ def aggregated_list( 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. @@ -377,10 +373,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListHealthChecksRequest): request = compute.AggregatedListHealthChecksRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -429,7 +423,6 @@ def delete( This corresponds to the ``health_check`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -481,10 +474,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteHealthCheckRequest): request = compute.DeleteHealthCheckRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if health_check is not None: @@ -531,7 +522,6 @@ def get( This corresponds to the ``health_check`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -586,10 +576,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetHealthCheckRequest): request = compute.GetHealthCheckRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if health_check is not None: @@ -633,7 +621,6 @@ def insert( This corresponds to the ``health_check_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. @@ -685,10 +672,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertHealthCheckRequest): request = compute.InsertHealthCheckRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if health_check_resource is not None: @@ -726,7 +711,6 @@ def list( 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. @@ -758,10 +742,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListHealthChecksRequest): request = compute.ListHealthChecksRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -819,7 +801,6 @@ def patch( This corresponds to the ``health_check_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. @@ -871,10 +852,8 @@ def patch( # there are no flattened fields. if not isinstance(request, compute.PatchHealthCheckRequest): request = compute.PatchHealthCheckRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if health_check is not None: @@ -928,7 +907,6 @@ def update( This corresponds to the ``health_check_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. @@ -980,10 +958,8 @@ def update( # there are no flattened fields. if not isinstance(request, compute.UpdateHealthCheckRequest): request = compute.UpdateHealthCheckRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if health_check is not None: diff --git a/google/cloud/compute_v1/services/health_checks/pagers.py b/google/cloud/compute_v1/services/health_checks/pagers.py index 6a2d05b87..28f28c8e7 100644 --- a/google/cloud/compute_v1/services/health_checks/pagers.py +++ b/google/cloud/compute_v1/services/health_checks/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/health_checks/transports/__init__.py b/google/cloud/compute_v1/services/health_checks/transports/__init__.py index 2355cdfbe..821eb3a59 100644 --- a/google/cloud/compute_v1/services/health_checks/transports/__init__.py +++ b/google/cloud/compute_v1/services/health_checks/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/health_checks/transports/base.py b/google/cloud/compute_v1/services/health_checks/transports/base.py index a3b47639e..c5240e6d6 100644 --- a/google/cloud/compute_v1/services/health_checks/transports/base.py +++ b/google/cloud/compute_v1/services/health_checks/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class HealthChecksTransport(abc.ABC): """Abstract transport class for HealthChecks.""" @@ -44,21 +54,24 @@ class HealthChecksTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -133,11 +193,11 @@ def _prep_wrapped_messages(self, client_info): @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListHealthChecksRequest], - typing.Union[ + Union[ compute.HealthChecksAggregatedList, - typing.Awaitable[compute.HealthChecksAggregatedList], + Awaitable[compute.HealthChecksAggregatedList], ], ]: raise NotImplementedError() @@ -145,56 +205,54 @@ def aggregated_list( @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteHealthCheckRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetHealthCheckRequest], - typing.Union[compute.HealthCheck, typing.Awaitable[compute.HealthCheck]], + Union[compute.HealthCheck, Awaitable[compute.HealthCheck]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertHealthCheckRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListHealthChecksRequest], - typing.Union[ - compute.HealthCheckList, typing.Awaitable[compute.HealthCheckList] - ], + Union[compute.HealthCheckList, Awaitable[compute.HealthCheckList]], ]: raise NotImplementedError() @property def patch( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchHealthCheckRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def update( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.UpdateHealthCheckRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/health_checks/transports/rest.py b/google/cloud/compute_v1/services/health_checks/transports/rest.py index 97bc8ce96..7712fc072 100644 --- a/google/cloud/compute_v1/services/health_checks/transports/rest.py +++ b/google/cloud/compute_v1/services/health_checks/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 HealthChecksTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListHealthChecksRequest): - The request object. - A request message for + The request object. A request message for HealthChecks.AggregatedList. See the method description for details. @@ -124,24 +123,28 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListHealthChecksRequest.filter in request: + query_params["filter"] = request.filter + if compute.AggregatedListHealthChecksRequest.include_all_scopes in request: + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListHealthChecksRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListHealthChecksRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListHealthChecksRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.AggregatedListHealthChecksRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -161,8 +164,7 @@ def delete( Args: request (~.compute.DeleteHealthCheckRequest): - The request object. - A request message for + The request object. A request message for HealthChecks.Delete. See the method description for details. @@ -210,19 +212,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteHealthCheckRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -240,8 +241,7 @@ def get( Args: request (~.compute.GetHealthCheckRequest): - The request object. - A request message for + The request object. A request message for HealthChecks.Get. See the method description for details. @@ -290,16 +290,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -319,8 +318,7 @@ def insert( Args: request (~.compute.InsertHealthCheckRequest): - The request object. - A request message for + The request object. A request message for HealthChecks.Insert. See the method description for details. @@ -375,15 +373,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertHealthCheckRequest.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() if v - ] + 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 @@ -405,8 +402,7 @@ def list( Args: request (~.compute.ListHealthChecksRequest): - The request object. - A request message for + The request object. A request message for HealthChecks.List. See the method description for details. @@ -428,23 +424,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListHealthChecksRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListHealthChecksRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListHealthChecksRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListHealthChecksRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListHealthChecksRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -464,8 +463,7 @@ def patch( Args: request (~.compute.PatchHealthCheckRequest): - The request object. - A request message for + The request object. A request message for HealthChecks.Patch. See the method description for details. @@ -520,15 +518,14 @@ def patch( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.PatchHealthCheckRequest.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() if v - ] + 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 @@ -550,8 +547,7 @@ def update( Args: request (~.compute.UpdateHealthCheckRequest): - The request object. - A request message for + The request object. A request message for HealthChecks.Update. See the method description for details. @@ -606,15 +602,14 @@ def update( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.UpdateHealthCheckRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/images/__init__.py b/google/cloud/compute_v1/services/images/__init__.py index 8a203ed93..3cdbececa 100644 --- a/google/cloud/compute_v1/services/images/__init__.py +++ b/google/cloud/compute_v1/services/images/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import ImagesClient __all__ = ("ImagesClient",) diff --git a/google/cloud/compute_v1/services/images/client.py b/google/cloud/compute_v1/services/images/client.py index 3566dfa73..6d3a5edc1 100644 --- a/google/cloud/compute_v1/services/images/client.py +++ b/google/cloud/compute_v1/services/images/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.images import pagers from google.cloud.compute_v1.types import compute - from .transports.base import ImagesTransport, DEFAULT_CLIENT_INFO from .transports.rest import ImagesRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ImagesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -349,7 +346,6 @@ def delete( This corresponds to the ``image`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -401,10 +397,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteImageRequest): request = compute.DeleteImageRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if image is not None: @@ -455,7 +449,6 @@ def deprecate( This corresponds to the ``deprecation_status_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. @@ -507,10 +500,8 @@ def deprecate( # there are no flattened fields. if not isinstance(request, compute.DeprecateImageRequest): request = compute.DeprecateImageRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if image is not None: @@ -555,7 +546,6 @@ def get( This corresponds to the ``image`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -587,10 +577,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetImageRequest): request = compute.GetImageRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if image is not None: @@ -636,7 +624,6 @@ def get_from_family( This corresponds to the ``family`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -668,10 +655,8 @@ def get_from_family( # there are no flattened fields. if not isinstance(request, compute.GetFromFamilyImageRequest): request = compute.GetFromFamilyImageRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if family is not None: @@ -717,7 +702,6 @@ def get_iam_policy( 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. @@ -795,10 +779,8 @@ def get_iam_policy( # there are no flattened fields. if not isinstance(request, compute.GetIamPolicyImageRequest): request = compute.GetIamPolicyImageRequest(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: @@ -841,7 +823,6 @@ def insert( This corresponds to the ``image_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. @@ -893,10 +874,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertImageRequest): request = compute.InsertImageRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if image_resource is not None: @@ -939,7 +918,6 @@ def list( 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. @@ -970,10 +948,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListImagesRequest): request = compute.ListImagesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -1027,7 +1003,6 @@ def patch( This corresponds to the ``image_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. @@ -1079,10 +1054,8 @@ def patch( # there are no flattened fields. if not isinstance(request, compute.PatchImageRequest): request = compute.PatchImageRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if image is not None: @@ -1136,7 +1109,6 @@ def set_iam_policy( This corresponds to the ``global_set_policy_request_resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1216,10 +1188,8 @@ def set_iam_policy( # there are no flattened fields. if not isinstance(request, compute.SetIamPolicyImageRequest): request = compute.SetIamPolicyImageRequest(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: @@ -1275,7 +1245,6 @@ def set_labels( 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. @@ -1329,10 +1298,8 @@ def set_labels( # there are no flattened fields. if not isinstance(request, compute.SetLabelsImageRequest): request = compute.SetLabelsImageRequest(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: @@ -1388,7 +1355,6 @@ def test_iam_permissions( 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. @@ -1417,10 +1383,8 @@ def test_iam_permissions( # there are no flattened fields. if not isinstance(request, compute.TestIamPermissionsImageRequest): request = compute.TestIamPermissionsImageRequest(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: diff --git a/google/cloud/compute_v1/services/images/pagers.py b/google/cloud/compute_v1/services/images/pagers.py index 00ab35682..2bcf2aea7 100644 --- a/google/cloud/compute_v1/services/images/pagers.py +++ b/google/cloud/compute_v1/services/images/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/images/transports/__init__.py b/google/cloud/compute_v1/services/images/transports/__init__.py index 8d2d142e7..09b0ef729 100644 --- a/google/cloud/compute_v1/services/images/transports/__init__.py +++ b/google/cloud/compute_v1/services/images/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/images/transports/base.py b/google/cloud/compute_v1/services/images/transports/base.py index a799924f5..22c6d7ef1 100644 --- a/google/cloud/compute_v1/services/images/transports/base.py +++ b/google/cloud/compute_v1/services/images/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class ImagesTransport(abc.ABC): """Abstract transport class for Images.""" @@ -44,21 +54,24 @@ class ImagesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -147,101 +207,99 @@ def _prep_wrapped_messages(self, client_info): @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteImageRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def deprecate( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeprecateImageRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ - [compute.GetImageRequest], - typing.Union[compute.Image, typing.Awaitable[compute.Image]], + ) -> Callable[ + [compute.GetImageRequest], Union[compute.Image, Awaitable[compute.Image]] ]: raise NotImplementedError() @property def get_from_family( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetFromFamilyImageRequest], - typing.Union[compute.Image, typing.Awaitable[compute.Image]], + Union[compute.Image, Awaitable[compute.Image]], ]: raise NotImplementedError() @property def get_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetIamPolicyImageRequest], - typing.Union[compute.Policy, typing.Awaitable[compute.Policy]], + Union[compute.Policy, Awaitable[compute.Policy]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertImageRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListImagesRequest], - typing.Union[compute.ImageList, typing.Awaitable[compute.ImageList]], + Union[compute.ImageList, Awaitable[compute.ImageList]], ]: raise NotImplementedError() @property def patch( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchImageRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetIamPolicyImageRequest], - typing.Union[compute.Policy, typing.Awaitable[compute.Policy]], + Union[compute.Policy, Awaitable[compute.Policy]], ]: raise NotImplementedError() @property def set_labels( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetLabelsImageRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.TestIamPermissionsImageRequest], - typing.Union[ - compute.TestPermissionsResponse, - typing.Awaitable[compute.TestPermissionsResponse], + Union[ + compute.TestPermissionsResponse, Awaitable[compute.TestPermissionsResponse] ], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/images/transports/rest.py b/google/cloud/compute_v1/services/images/transports/rest.py index 9ab03daeb..3b6d735cf 100644 --- a/google/cloud/compute_v1/services/images/transports/rest.py +++ b/google/cloud/compute_v1/services/images/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 ImagesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def delete( Args: request (~.compute.DeleteImageRequest): - The request object. - A request message for Images.Delete. + The request object. A request message for Images.Delete. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -151,19 +150,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteImageRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -181,8 +179,7 @@ def deprecate( Args: request (~.compute.DeprecateImageRequest): - The request object. - A request message for + The request object. A request message for Images.Deprecate. See the method description for details. @@ -237,15 +234,14 @@ def deprecate( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeprecateImageRequest.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() if v - ] + 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 @@ -267,8 +263,7 @@ def get( Args: request (~.compute.GetImageRequest): - The request object. - A request message for Images.Get. See + The request object. A request message for Images.Get. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -293,16 +288,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -320,8 +314,7 @@ def get_from_family( Args: request (~.compute.GetFromFamilyImageRequest): - The request object. - A request message for + The request object. A request message for Images.GetFromFamily. See the method description for details. @@ -347,16 +340,15 @@ def get_from_family( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -374,8 +366,7 @@ def get_iam_policy( Args: request (~.compute.GetIamPolicyImageRequest): - The request object. - A request message for + The request object. A request message for Images.GetIamPolicy. See the method description for details. @@ -445,19 +436,20 @@ def get_iam_policy( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "optionsRequestedPolicyVersion": request.options_requested_policy_version, - } + query_params = {} + if compute.GetIamPolicyImageRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -475,8 +467,7 @@ def insert( Args: request (~.compute.InsertImageRequest): - The request object. - A request message for Images.Insert. + The request object. A request message for Images.Insert. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -530,16 +521,16 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "forceCreate": request.force_create, - "requestId": request.request_id, - } + query_params = {} + if compute.InsertImageRequest.force_create in request: + query_params["forceCreate"] = request.force_create + if compute.InsertImageRequest.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() if v - ] + 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 @@ -561,8 +552,7 @@ def list( Args: request (~.compute.ListImagesRequest): - The request object. - A request message for Images.List. + The request object. A request message for Images.List. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -581,23 +571,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListImagesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListImagesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListImagesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListImagesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListImagesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -615,8 +608,7 @@ def patch( Args: request (~.compute.PatchImageRequest): - The request object. - A request message for Images.Patch. + The request object. A request message for Images.Patch. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -670,15 +662,14 @@ def patch( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.PatchImageRequest.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() if v - ] + 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 @@ -700,8 +691,7 @@ def set_iam_policy( Args: request (~.compute.SetIamPolicyImageRequest): - The request object. - A request message for + The request object. A request message for Images.SetIamPolicy. See the method description for details. @@ -779,12 +769,11 @@ def set_iam_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() if v - ] + 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 @@ -806,8 +795,7 @@ def set_labels( Args: request (~.compute.SetLabelsImageRequest): - The request object. - A request message for + The request object. A request message for Images.SetLabels. See the method description for details. @@ -863,12 +851,11 @@ def set_labels( # 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() if v - ] + 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 @@ -890,8 +877,7 @@ def test_iam_permissions( Args: request (~.compute.TestIamPermissionsImageRequest): - The request object. - A request message for + The request object. A request message for Images.TestIamPermissions. See the method description for details. @@ -919,12 +905,11 @@ def test_iam_permissions( # 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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/instance_group_managers/__init__.py b/google/cloud/compute_v1/services/instance_group_managers/__init__.py index a554c74ca..d26bc6308 100644 --- a/google/cloud/compute_v1/services/instance_group_managers/__init__.py +++ b/google/cloud/compute_v1/services/instance_group_managers/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import InstanceGroupManagersClient __all__ = ("InstanceGroupManagersClient",) diff --git a/google/cloud/compute_v1/services/instance_group_managers/client.py b/google/cloud/compute_v1/services/instance_group_managers/client.py index 240ed9f14..5484b9544 100644 --- a/google/cloud/compute_v1/services/instance_group_managers/client.py +++ b/google/cloud/compute_v1/services/instance_group_managers/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.instance_group_managers import pagers from google.cloud.compute_v1.types import compute - from .transports.base import InstanceGroupManagersTransport, DEFAULT_CLIENT_INFO from .transports.rest import InstanceGroupManagersRestTransport @@ -217,7 +214,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, InstanceGroupManagersTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -386,7 +383,6 @@ def abandon_instances( This corresponds to the ``instance_group_managers_abandon_instances_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. @@ -445,10 +441,8 @@ def abandon_instances( # there are no flattened fields. if not isinstance(request, compute.AbandonInstancesInstanceGroupManagerRequest): request = compute.AbandonInstancesInstanceGroupManagerRequest(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: @@ -492,7 +486,6 @@ def aggregated_list( 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. @@ -522,10 +515,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListInstanceGroupManagersRequest): request = compute.AggregatedListInstanceGroupManagersRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -591,7 +582,6 @@ def apply_updates_to_instances( This corresponds to the ``instance_group_managers_apply_updates_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. @@ -654,10 +644,8 @@ def apply_updates_to_instances( request = compute.ApplyUpdatesToInstancesInstanceGroupManagerRequest( 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: @@ -732,7 +720,6 @@ def create_instances( This corresponds to the ``instance_group_managers_create_instances_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. @@ -791,10 +778,8 @@ def create_instances( # there are no flattened fields. if not isinstance(request, compute.CreateInstancesInstanceGroupManagerRequest): request = compute.CreateInstancesInstanceGroupManagerRequest(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: @@ -856,7 +841,6 @@ def delete( This corresponds to the ``instance_group_manager`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -908,10 +892,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteInstanceGroupManagerRequest): request = compute.DeleteInstanceGroupManagerRequest(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: @@ -986,7 +968,6 @@ def delete_instances( This corresponds to the ``instance_group_managers_delete_instances_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. @@ -1045,10 +1026,8 @@ def delete_instances( # there are no flattened fields. if not isinstance(request, compute.DeleteInstancesInstanceGroupManagerRequest): request = compute.DeleteInstancesInstanceGroupManagerRequest(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: @@ -1115,7 +1094,6 @@ def delete_per_instance_configs( This corresponds to the ``instance_group_managers_delete_per_instance_configs_req_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. @@ -1178,10 +1156,8 @@ def delete_per_instance_configs( request = compute.DeletePerInstanceConfigsInstanceGroupManagerRequest( 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: @@ -1247,7 +1223,6 @@ def get( This corresponds to the ``instance_group_manager`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1288,10 +1263,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetInstanceGroupManagerRequest): request = compute.GetInstanceGroupManagerRequest(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: @@ -1354,7 +1327,6 @@ def insert( This corresponds to the ``instance_group_manager_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. @@ -1406,10 +1378,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertInstanceGroupManagerRequest): request = compute.InsertInstanceGroupManagerRequest(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: @@ -1459,7 +1429,6 @@ def list( This corresponds to the ``zone`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1490,10 +1459,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListInstanceGroupManagersRequest): request = compute.ListInstanceGroupManagersRequest(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: @@ -1557,7 +1524,6 @@ def list_errors( This corresponds to the ``instance_group_manager`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1587,10 +1553,8 @@ def list_errors( # there are no flattened fields. if not isinstance(request, compute.ListErrorsInstanceGroupManagersRequest): request = compute.ListErrorsInstanceGroupManagersRequest(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: @@ -1658,7 +1622,6 @@ def list_managed_instances( This corresponds to the ``instance_group_manager`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1690,10 +1653,8 @@ def list_managed_instances( request, compute.ListManagedInstancesInstanceGroupManagersRequest ): request = compute.ListManagedInstancesInstanceGroupManagersRequest(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: @@ -1757,7 +1718,6 @@ def list_per_instance_configs( This corresponds to the ``instance_group_manager`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1791,10 +1751,8 @@ def list_per_instance_configs( request = compute.ListPerInstanceConfigsInstanceGroupManagersRequest( 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: @@ -1871,7 +1829,6 @@ def patch( This corresponds to the ``instance_group_manager_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. @@ -1925,10 +1882,8 @@ def patch( # there are no flattened fields. if not isinstance(request, compute.PatchInstanceGroupManagerRequest): request = compute.PatchInstanceGroupManagerRequest(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: @@ -1997,7 +1952,6 @@ def patch_per_instance_configs( This corresponds to the ``instance_group_managers_patch_per_instance_configs_req_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. @@ -2060,10 +2014,8 @@ def patch_per_instance_configs( request = compute.PatchPerInstanceConfigsInstanceGroupManagerRequest( 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: @@ -2146,7 +2098,6 @@ def recreate_instances( This corresponds to the ``instance_group_managers_recreate_instances_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. @@ -2207,10 +2158,8 @@ def recreate_instances( request, compute.RecreateInstancesInstanceGroupManagerRequest ): request = compute.RecreateInstancesInstanceGroupManagerRequest(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: @@ -2302,7 +2251,6 @@ def resize( This corresponds to the ``size`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2354,10 +2302,8 @@ def resize( # there are no flattened fields. if not isinstance(request, compute.ResizeInstanceGroupManagerRequest): request = compute.ResizeInstanceGroupManagerRequest(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: @@ -2424,7 +2370,6 @@ def set_instance_template( This corresponds to the ``instance_group_managers_set_instance_template_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. @@ -2485,10 +2430,8 @@ def set_instance_template( request, compute.SetInstanceTemplateInstanceGroupManagerRequest ): request = compute.SetInstanceTemplateInstanceGroupManagerRequest(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: @@ -2563,7 +2506,6 @@ def set_target_pools( This corresponds to the ``instance_group_managers_set_target_pools_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. @@ -2622,10 +2564,8 @@ def set_target_pools( # there are no flattened fields. if not isinstance(request, compute.SetTargetPoolsInstanceGroupManagerRequest): request = compute.SetTargetPoolsInstanceGroupManagerRequest(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: @@ -2694,7 +2634,6 @@ def update_per_instance_configs( This corresponds to the ``instance_group_managers_update_per_instance_configs_req_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. @@ -2757,10 +2696,8 @@ def update_per_instance_configs( request = compute.UpdatePerInstanceConfigsInstanceGroupManagerRequest( 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: diff --git a/google/cloud/compute_v1/services/instance_group_managers/pagers.py b/google/cloud/compute_v1/services/instance_group_managers/pagers.py index e5200c6f8..50bd2b911 100644 --- a/google/cloud/compute_v1/services/instance_group_managers/pagers.py +++ b/google/cloud/compute_v1/services/instance_group_managers/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/instance_group_managers/transports/__init__.py b/google/cloud/compute_v1/services/instance_group_managers/transports/__init__.py index 8ef825a6e..e5cc97800 100644 --- a/google/cloud/compute_v1/services/instance_group_managers/transports/__init__.py +++ b/google/cloud/compute_v1/services/instance_group_managers/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/instance_group_managers/transports/base.py b/google/cloud/compute_v1/services/instance_group_managers/transports/base.py index 9ee32445c..65462ca24 100644 --- a/google/cloud/compute_v1/services/instance_group_managers/transports/base.py +++ b/google/cloud/compute_v1/services/instance_group_managers/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class InstanceGroupManagersTransport(abc.ABC): """Abstract transport class for InstanceGroupManagers.""" @@ -44,21 +54,24 @@ class InstanceGroupManagersTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -186,20 +246,20 @@ def _prep_wrapped_messages(self, client_info): @property def abandon_instances( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AbandonInstancesInstanceGroupManagerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListInstanceGroupManagersRequest], - typing.Union[ + Union[ compute.InstanceGroupManagerAggregatedList, - typing.Awaitable[compute.InstanceGroupManagerAggregatedList], + Awaitable[compute.InstanceGroupManagerAggregatedList], ], ]: raise NotImplementedError() @@ -207,76 +267,74 @@ def aggregated_list( @property def apply_updates_to_instances( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ApplyUpdatesToInstancesInstanceGroupManagerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def create_instances( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.CreateInstancesInstanceGroupManagerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteInstanceGroupManagerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def delete_instances( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteInstancesInstanceGroupManagerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def delete_per_instance_configs( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeletePerInstanceConfigsInstanceGroupManagerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetInstanceGroupManagerRequest], - typing.Union[ - compute.InstanceGroupManager, typing.Awaitable[compute.InstanceGroupManager] - ], + Union[compute.InstanceGroupManager, Awaitable[compute.InstanceGroupManager]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertInstanceGroupManagerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListInstanceGroupManagersRequest], - typing.Union[ + Union[ compute.InstanceGroupManagerList, - typing.Awaitable[compute.InstanceGroupManagerList], + Awaitable[compute.InstanceGroupManagerList], ], ]: raise NotImplementedError() @@ -284,11 +342,11 @@ def list( @property def list_errors( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListErrorsInstanceGroupManagersRequest], - typing.Union[ + Union[ compute.InstanceGroupManagersListErrorsResponse, - typing.Awaitable[compute.InstanceGroupManagersListErrorsResponse], + Awaitable[compute.InstanceGroupManagersListErrorsResponse], ], ]: raise NotImplementedError() @@ -296,11 +354,11 @@ def list_errors( @property def list_managed_instances( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListManagedInstancesInstanceGroupManagersRequest], - typing.Union[ + Union[ compute.InstanceGroupManagersListManagedInstancesResponse, - typing.Awaitable[compute.InstanceGroupManagersListManagedInstancesResponse], + Awaitable[compute.InstanceGroupManagersListManagedInstancesResponse], ], ]: raise NotImplementedError() @@ -308,11 +366,11 @@ def list_managed_instances( @property def list_per_instance_configs( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListPerInstanceConfigsInstanceGroupManagersRequest], - typing.Union[ + Union[ compute.InstanceGroupManagersListPerInstanceConfigsResp, - typing.Awaitable[compute.InstanceGroupManagersListPerInstanceConfigsResp], + Awaitable[compute.InstanceGroupManagersListPerInstanceConfigsResp], ], ]: raise NotImplementedError() @@ -320,63 +378,63 @@ def list_per_instance_configs( @property def patch( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchInstanceGroupManagerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def patch_per_instance_configs( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchPerInstanceConfigsInstanceGroupManagerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def recreate_instances( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.RecreateInstancesInstanceGroupManagerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def resize( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ResizeInstanceGroupManagerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_instance_template( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetInstanceTemplateInstanceGroupManagerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_target_pools( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetTargetPoolsInstanceGroupManagerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def update_per_instance_configs( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.UpdatePerInstanceConfigsInstanceGroupManagerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/instance_group_managers/transports/rest.py b/google/cloud/compute_v1/services/instance_group_managers/transports/rest.py index a3783aa93..daa4607ab 100644 --- a/google/cloud/compute_v1/services/instance_group_managers/transports/rest.py +++ b/google/cloud/compute_v1/services/instance_group_managers/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 InstanceGroupManagersTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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 abandon_instances( self, @@ -103,8 +103,7 @@ def abandon_instances( Args: request (~.compute.AbandonInstancesInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for InstanceGroupManagers.AbandonInstances. See the method description for details. @@ -162,15 +161,14 @@ def abandon_instances( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.AbandonInstancesInstanceGroupManagerRequest.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() if v - ] + 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 @@ -192,8 +190,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListInstanceGroupManagersRequest): - The request object. - A request message for + The request object. A request message for InstanceGroupManagers.AggregatedList. See the method description for details. @@ -213,24 +210,34 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListInstanceGroupManagersRequest.filter in request: + query_params["filter"] = request.filter + if ( + compute.AggregatedListInstanceGroupManagersRequest.include_all_scopes + in request + ): + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListInstanceGroupManagersRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListInstanceGroupManagersRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListInstanceGroupManagersRequest.page_token in request: + query_params["pageToken"] = request.page_token + if ( + compute.AggregatedListInstanceGroupManagersRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -251,8 +258,7 @@ def apply_updates_to_instances( Args: request (~.compute.ApplyUpdatesToInstancesInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for InstanceGroupManagers.ApplyUpdatesToInstances. See the method description for details. @@ -311,12 +317,11 @@ def apply_updates_to_instances( # 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() if v - ] + 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 @@ -338,8 +343,7 @@ def create_instances( Args: request (~.compute.CreateInstancesInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for InstanceGroupManagers.CreateInstances. See the method description for details. @@ -397,15 +401,14 @@ def create_instances( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.CreateInstancesInstanceGroupManagerRequest.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() if v - ] + 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 @@ -427,8 +430,7 @@ def delete( Args: request (~.compute.DeleteInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for InstanceGroupManagers.Delete. See the method description for details. @@ -479,19 +481,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteInstanceGroupManagerRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -509,8 +510,7 @@ def delete_instances( Args: request (~.compute.DeleteInstancesInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for InstanceGroupManagers.DeleteInstances. See the method description for details. @@ -568,15 +568,14 @@ def delete_instances( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteInstancesInstanceGroupManagerRequest.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() if v - ] + 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 @@ -599,8 +598,7 @@ def delete_per_instance_configs( Args: request (~.compute.DeletePerInstanceConfigsInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for InstanceGroupManagers.DeletePerInstanceConfigs. See the method description for details. @@ -659,12 +657,11 @@ def delete_per_instance_configs( # 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() if v - ] + 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 @@ -686,8 +683,7 @@ def get( Args: request (~.compute.GetInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for InstanceGroupManagers.Get. See the method description for details. @@ -725,16 +721,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -754,8 +749,7 @@ def insert( Args: request (~.compute.InsertInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for InstanceGroupManagers.Insert. See the method description for details. @@ -810,15 +804,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertInstanceGroupManagerRequest.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() if v - ] + 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 @@ -840,8 +833,7 @@ def list( Args: request (~.compute.ListInstanceGroupManagersRequest): - The request object. - A request message for + The request object. A request message for InstanceGroupManagers.List. See the method description for details. @@ -861,23 +853,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListInstanceGroupManagersRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListInstanceGroupManagersRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListInstanceGroupManagersRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListInstanceGroupManagersRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListInstanceGroupManagersRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -897,8 +892,7 @@ def list_errors( Args: request (~.compute.ListErrorsInstanceGroupManagersRequest): - The request object. - A request message for + The request object. A request message for InstanceGroupManagers.ListErrors. See the method description for details. @@ -921,23 +915,29 @@ def list_errors( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListErrorsInstanceGroupManagersRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListErrorsInstanceGroupManagersRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListErrorsInstanceGroupManagersRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListErrorsInstanceGroupManagersRequest.page_token in request: + query_params["pageToken"] = request.page_token + if ( + compute.ListErrorsInstanceGroupManagersRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -957,8 +957,7 @@ def list_managed_instances( Args: request (~.compute.ListManagedInstancesInstanceGroupManagersRequest): - The request object. - A request message for + The request object. A request message for InstanceGroupManagers.ListManagedInstances. See the method description for details. @@ -981,23 +980,35 @@ def list_managed_instances( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListManagedInstancesInstanceGroupManagersRequest.filter in request: + query_params["filter"] = request.filter + if ( + compute.ListManagedInstancesInstanceGroupManagersRequest.max_results + in request + ): + query_params["maxResults"] = request.max_results + if compute.ListManagedInstancesInstanceGroupManagersRequest.order_by in request: + query_params["orderBy"] = request.order_by + if ( + compute.ListManagedInstancesInstanceGroupManagersRequest.page_token + in request + ): + query_params["pageToken"] = request.page_token + if ( + compute.ListManagedInstancesInstanceGroupManagersRequest.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() if v - ] + 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 - response = self._session.post(url) + response = self._session.post(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -1017,8 +1028,7 @@ def list_per_instance_configs( Args: request (~.compute.ListPerInstanceConfigsInstanceGroupManagersRequest): - The request object. - A request message for + The request object. A request message for InstanceGroupManagers.ListPerInstanceConfigs. See the method description for details. @@ -1041,23 +1051,38 @@ def list_per_instance_configs( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListPerInstanceConfigsInstanceGroupManagersRequest.filter in request: + query_params["filter"] = request.filter + if ( + compute.ListPerInstanceConfigsInstanceGroupManagersRequest.max_results + in request + ): + query_params["maxResults"] = request.max_results + if ( + compute.ListPerInstanceConfigsInstanceGroupManagersRequest.order_by + in request + ): + query_params["orderBy"] = request.order_by + if ( + compute.ListPerInstanceConfigsInstanceGroupManagersRequest.page_token + in request + ): + query_params["pageToken"] = request.page_token + if ( + compute.ListPerInstanceConfigsInstanceGroupManagersRequest.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() if v - ] + 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 - response = self._session.post(url) + response = self._session.post(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -1077,8 +1102,7 @@ def patch( Args: request (~.compute.PatchInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for InstanceGroupManagers.Patch. See the method description for details. @@ -1136,15 +1160,14 @@ def patch( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.PatchInstanceGroupManagerRequest.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() if v - ] + 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 @@ -1167,8 +1190,7 @@ def patch_per_instance_configs( Args: request (~.compute.PatchPerInstanceConfigsInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for InstanceGroupManagers.PatchPerInstanceConfigs. See the method description for details. @@ -1226,15 +1248,17 @@ def patch_per_instance_configs( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if ( + compute.PatchPerInstanceConfigsInstanceGroupManagerRequest.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() if v - ] + 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 @@ -1256,8 +1280,7 @@ def recreate_instances( Args: request (~.compute.RecreateInstancesInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for InstanceGroupManagers.RecreateInstances. See the method description for details. @@ -1315,15 +1338,14 @@ def recreate_instances( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.RecreateInstancesInstanceGroupManagerRequest.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() if v - ] + 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 @@ -1345,8 +1367,7 @@ def resize( Args: request (~.compute.ResizeInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for InstanceGroupManagers.Resize. See the method description for details. @@ -1397,20 +1418,20 @@ def resize( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - "size": request.size, - } + query_params = {} + if compute.ResizeInstanceGroupManagerRequest.request_id in request: + query_params["requestId"] = request.request_id + if request.size: + query_params["size"] = request.size + # 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() if v - ] + 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 - response = self._session.post(url) + response = self._session.post(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -1428,8 +1449,7 @@ def set_instance_template( Args: request (~.compute.SetInstanceTemplateInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for InstanceGroupManagers.SetInstanceTemplate. See the method description for details. @@ -1487,15 +1507,14 @@ def set_instance_template( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetInstanceTemplateInstanceGroupManagerRequest.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() if v - ] + 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 @@ -1517,8 +1536,7 @@ def set_target_pools( Args: request (~.compute.SetTargetPoolsInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for InstanceGroupManagers.SetTargetPools. See the method description for details. @@ -1576,15 +1594,14 @@ def set_target_pools( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetTargetPoolsInstanceGroupManagerRequest.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() if v - ] + 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 @@ -1607,8 +1624,7 @@ def update_per_instance_configs( Args: request (~.compute.UpdatePerInstanceConfigsInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for InstanceGroupManagers.UpdatePerInstanceConfigs. See the method description for details. @@ -1666,15 +1682,17 @@ def update_per_instance_configs( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if ( + compute.UpdatePerInstanceConfigsInstanceGroupManagerRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/instance_groups/__init__.py b/google/cloud/compute_v1/services/instance_groups/__init__.py index 37b6827cc..e1351f9c4 100644 --- a/google/cloud/compute_v1/services/instance_groups/__init__.py +++ b/google/cloud/compute_v1/services/instance_groups/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import InstanceGroupsClient __all__ = ("InstanceGroupsClient",) diff --git a/google/cloud/compute_v1/services/instance_groups/client.py b/google/cloud/compute_v1/services/instance_groups/client.py index b42d42a87..8c2a02340 100644 --- a/google/cloud/compute_v1/services/instance_groups/client.py +++ b/google/cloud/compute_v1/services/instance_groups/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.instance_groups import pagers from google.cloud.compute_v1.types import compute - from .transports.base import InstanceGroupsTransport, DEFAULT_CLIENT_INFO from .transports.rest import InstanceGroupsRestTransport @@ -215,7 +212,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, InstanceGroupsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -371,7 +368,6 @@ def add_instances( This corresponds to the ``instance_groups_add_instances_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. @@ -430,10 +426,8 @@ def add_instances( # there are no flattened fields. if not isinstance(request, compute.AddInstancesInstanceGroupRequest): request = compute.AddInstancesInstanceGroupRequest(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: @@ -477,7 +471,6 @@ def aggregated_list( 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. @@ -507,10 +500,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListInstanceGroupsRequest): request = compute.AggregatedListInstanceGroupsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -570,7 +561,6 @@ def delete( This corresponds to the ``instance_group`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -622,10 +612,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteInstanceGroupRequest): request = compute.DeleteInstanceGroupRequest(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: @@ -682,7 +670,6 @@ def get( This corresponds to the ``instance_group`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -731,10 +718,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetInstanceGroupRequest): request = compute.GetInstanceGroupRequest(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: @@ -788,7 +773,6 @@ def insert( This corresponds to the ``instance_group_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. @@ -840,10 +824,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertInstanceGroupRequest): request = compute.InsertInstanceGroupRequest(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: @@ -894,7 +876,6 @@ def list( This corresponds to the ``zone`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -925,10 +906,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListInstanceGroupsRequest): request = compute.ListInstanceGroupsRequest(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: @@ -995,7 +974,6 @@ def list_instances( This corresponds to the ``instance_groups_list_instances_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. @@ -1032,10 +1010,8 @@ def list_instances( # there are no flattened fields. if not isinstance(request, compute.ListInstancesInstanceGroupsRequest): request = compute.ListInstancesInstanceGroupsRequest(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: @@ -1111,7 +1087,6 @@ def remove_instances( This corresponds to the ``instance_groups_remove_instances_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. @@ -1170,10 +1145,8 @@ def remove_instances( # there are no flattened fields. if not isinstance(request, compute.RemoveInstancesInstanceGroupRequest): request = compute.RemoveInstancesInstanceGroupRequest(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: @@ -1239,7 +1212,6 @@ def set_named_ports( This corresponds to the ``instance_groups_set_named_ports_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. @@ -1298,10 +1270,8 @@ def set_named_ports( # there are no flattened fields. if not isinstance(request, compute.SetNamedPortsInstanceGroupRequest): request = compute.SetNamedPortsInstanceGroupRequest(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: diff --git a/google/cloud/compute_v1/services/instance_groups/pagers.py b/google/cloud/compute_v1/services/instance_groups/pagers.py index a19c7f07f..6c24e583c 100644 --- a/google/cloud/compute_v1/services/instance_groups/pagers.py +++ b/google/cloud/compute_v1/services/instance_groups/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/instance_groups/transports/__init__.py b/google/cloud/compute_v1/services/instance_groups/transports/__init__.py index 81ac5c242..be755bbe1 100644 --- a/google/cloud/compute_v1/services/instance_groups/transports/__init__.py +++ b/google/cloud/compute_v1/services/instance_groups/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/instance_groups/transports/base.py b/google/cloud/compute_v1/services/instance_groups/transports/base.py index f11d83174..a43607dad 100644 --- a/google/cloud/compute_v1/services/instance_groups/transports/base.py +++ b/google/cloud/compute_v1/services/instance_groups/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class InstanceGroupsTransport(abc.ABC): """Abstract transport class for InstanceGroups.""" @@ -44,21 +54,24 @@ class InstanceGroupsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -139,20 +199,20 @@ def _prep_wrapped_messages(self, client_info): @property def add_instances( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AddInstancesInstanceGroupRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListInstanceGroupsRequest], - typing.Union[ + Union[ compute.InstanceGroupAggregatedList, - typing.Awaitable[compute.InstanceGroupAggregatedList], + Awaitable[compute.InstanceGroupAggregatedList], ], ]: raise NotImplementedError() @@ -160,49 +220,47 @@ def aggregated_list( @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteInstanceGroupRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetInstanceGroupRequest], - typing.Union[compute.InstanceGroup, typing.Awaitable[compute.InstanceGroup]], + Union[compute.InstanceGroup, Awaitable[compute.InstanceGroup]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertInstanceGroupRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListInstanceGroupsRequest], - typing.Union[ - compute.InstanceGroupList, typing.Awaitable[compute.InstanceGroupList] - ], + Union[compute.InstanceGroupList, Awaitable[compute.InstanceGroupList]], ]: raise NotImplementedError() @property def list_instances( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListInstancesInstanceGroupsRequest], - typing.Union[ + Union[ compute.InstanceGroupsListInstances, - typing.Awaitable[compute.InstanceGroupsListInstances], + Awaitable[compute.InstanceGroupsListInstances], ], ]: raise NotImplementedError() @@ -210,18 +268,18 @@ def list_instances( @property def remove_instances( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.RemoveInstancesInstanceGroupRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_named_ports( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetNamedPortsInstanceGroupRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/instance_groups/transports/rest.py b/google/cloud/compute_v1/services/instance_groups/transports/rest.py index e91329549..63d2c7c0c 100644 --- a/google/cloud/compute_v1/services/instance_groups/transports/rest.py +++ b/google/cloud/compute_v1/services/instance_groups/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 InstanceGroupsTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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_instances( self, @@ -103,8 +103,7 @@ def add_instances( Args: request (~.compute.AddInstancesInstanceGroupRequest): - The request object. - A request message for + The request object. A request message for InstanceGroups.AddInstances. See the method description for details. @@ -162,15 +161,14 @@ def add_instances( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.AddInstancesInstanceGroupRequest.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() if v - ] + 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 @@ -192,8 +190,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListInstanceGroupsRequest): - The request object. - A request message for + The request object. A request message for InstanceGroups.AggregatedList. See the method description for details. @@ -213,24 +210,31 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListInstanceGroupsRequest.filter in request: + query_params["filter"] = request.filter + if compute.AggregatedListInstanceGroupsRequest.include_all_scopes in request: + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListInstanceGroupsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListInstanceGroupsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListInstanceGroupsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if ( + compute.AggregatedListInstanceGroupsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -250,8 +254,7 @@ def delete( Args: request (~.compute.DeleteInstanceGroupRequest): - The request object. - A request message for + The request object. A request message for InstanceGroups.Delete. See the method description for details. @@ -302,19 +305,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteInstanceGroupRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -332,8 +334,7 @@ def get( Args: request (~.compute.GetInstanceGroupRequest): - The request object. - A request message for + The request object. A request message for InstanceGroups.Get. See the method description for details. @@ -377,16 +378,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -406,8 +406,7 @@ def insert( Args: request (~.compute.InsertInstanceGroupRequest): - The request object. - A request message for + The request object. A request message for InstanceGroups.Insert. See the method description for details. @@ -462,15 +461,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertInstanceGroupRequest.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() if v - ] + 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 @@ -492,8 +490,7 @@ def list( Args: request (~.compute.ListInstanceGroupsRequest): - The request object. - A request message for + The request object. A request message for InstanceGroups.List. See the method description for details. @@ -513,23 +510,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListInstanceGroupsRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListInstanceGroupsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListInstanceGroupsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListInstanceGroupsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListInstanceGroupsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -549,8 +549,7 @@ def list_instances( Args: request (~.compute.ListInstancesInstanceGroupsRequest): - The request object. - A request message for + The request object. A request message for InstanceGroups.ListInstances. See the method description for details. @@ -580,19 +579,22 @@ def list_instances( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListInstancesInstanceGroupsRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListInstancesInstanceGroupsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListInstancesInstanceGroupsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListInstancesInstanceGroupsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListInstancesInstanceGroupsRequest.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() if v - ] + 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 @@ -616,8 +618,7 @@ def remove_instances( Args: request (~.compute.RemoveInstancesInstanceGroupRequest): - The request object. - A request message for + The request object. A request message for InstanceGroups.RemoveInstances. See the method description for details. @@ -675,15 +676,14 @@ def remove_instances( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.RemoveInstancesInstanceGroupRequest.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() if v - ] + 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 @@ -705,8 +705,7 @@ def set_named_ports( Args: request (~.compute.SetNamedPortsInstanceGroupRequest): - The request object. - A request message for + The request object. A request message for InstanceGroups.SetNamedPorts. See the method description for details. @@ -764,15 +763,14 @@ def set_named_ports( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetNamedPortsInstanceGroupRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/instance_templates/__init__.py b/google/cloud/compute_v1/services/instance_templates/__init__.py index 8673dbc8a..36d687e93 100644 --- a/google/cloud/compute_v1/services/instance_templates/__init__.py +++ b/google/cloud/compute_v1/services/instance_templates/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import InstanceTemplatesClient __all__ = ("InstanceTemplatesClient",) diff --git a/google/cloud/compute_v1/services/instance_templates/client.py b/google/cloud/compute_v1/services/instance_templates/client.py index 014c7b7e2..94603ad5d 100644 --- a/google/cloud/compute_v1/services/instance_templates/client.py +++ b/google/cloud/compute_v1/services/instance_templates/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.instance_templates import pagers from google.cloud.compute_v1.types import compute - from .transports.base import InstanceTemplatesTransport, DEFAULT_CLIENT_INFO from .transports.rest import InstanceTemplatesRestTransport @@ -217,7 +214,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, InstanceTemplatesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -359,7 +356,6 @@ def delete( This corresponds to the ``instance_template`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -411,10 +407,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteInstanceTemplateRequest): request = compute.DeleteInstanceTemplateRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if instance_template is not None: @@ -459,7 +453,6 @@ def get( This corresponds to the ``instance_template`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -492,10 +485,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetInstanceTemplateRequest): request = compute.GetInstanceTemplateRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if instance_template is not None: @@ -541,7 +532,6 @@ def get_iam_policy( 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. @@ -619,10 +609,8 @@ def get_iam_policy( # there are no flattened fields. if not isinstance(request, compute.GetIamPolicyInstanceTemplateRequest): request = compute.GetIamPolicyInstanceTemplateRequest(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: @@ -670,7 +658,6 @@ def insert( This corresponds to the ``instance_template_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. @@ -722,10 +709,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertInstanceTemplateRequest): request = compute.InsertInstanceTemplateRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if instance_template_resource is not None: @@ -763,7 +748,6 @@ def list( 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. @@ -794,10 +778,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListInstanceTemplatesRequest): request = compute.ListInstanceTemplatesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -853,7 +835,6 @@ def set_iam_policy( This corresponds to the ``global_set_policy_request_resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -933,10 +914,8 @@ def set_iam_policy( # there are no flattened fields. if not isinstance(request, compute.SetIamPolicyInstanceTemplateRequest): request = compute.SetIamPolicyInstanceTemplateRequest(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: @@ -992,7 +971,6 @@ def test_iam_permissions( 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. @@ -1021,10 +999,8 @@ def test_iam_permissions( # there are no flattened fields. if not isinstance(request, compute.TestIamPermissionsInstanceTemplateRequest): request = compute.TestIamPermissionsInstanceTemplateRequest(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: diff --git a/google/cloud/compute_v1/services/instance_templates/pagers.py b/google/cloud/compute_v1/services/instance_templates/pagers.py index 5f767a6cb..1813c70b2 100644 --- a/google/cloud/compute_v1/services/instance_templates/pagers.py +++ b/google/cloud/compute_v1/services/instance_templates/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/instance_templates/transports/__init__.py b/google/cloud/compute_v1/services/instance_templates/transports/__init__.py index dd337ea5c..1c251431c 100644 --- a/google/cloud/compute_v1/services/instance_templates/transports/__init__.py +++ b/google/cloud/compute_v1/services/instance_templates/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/instance_templates/transports/base.py b/google/cloud/compute_v1/services/instance_templates/transports/base.py index 1784d4c83..f0f9ee394 100644 --- a/google/cloud/compute_v1/services/instance_templates/transports/base.py +++ b/google/cloud/compute_v1/services/instance_templates/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class InstanceTemplatesTransport(abc.ABC): """Abstract transport class for InstanceTemplates.""" @@ -44,21 +54,24 @@ class InstanceTemplatesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -135,69 +195,64 @@ def _prep_wrapped_messages(self, client_info): @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteInstanceTemplateRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetInstanceTemplateRequest], - typing.Union[ - compute.InstanceTemplate, typing.Awaitable[compute.InstanceTemplate] - ], + Union[compute.InstanceTemplate, Awaitable[compute.InstanceTemplate]], ]: raise NotImplementedError() @property def get_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetIamPolicyInstanceTemplateRequest], - typing.Union[compute.Policy, typing.Awaitable[compute.Policy]], + Union[compute.Policy, Awaitable[compute.Policy]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertInstanceTemplateRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListInstanceTemplatesRequest], - typing.Union[ - compute.InstanceTemplateList, typing.Awaitable[compute.InstanceTemplateList] - ], + Union[compute.InstanceTemplateList, Awaitable[compute.InstanceTemplateList]], ]: raise NotImplementedError() @property def set_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetIamPolicyInstanceTemplateRequest], - typing.Union[compute.Policy, typing.Awaitable[compute.Policy]], + Union[compute.Policy, Awaitable[compute.Policy]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.TestIamPermissionsInstanceTemplateRequest], - typing.Union[ - compute.TestPermissionsResponse, - typing.Awaitable[compute.TestPermissionsResponse], + Union[ + compute.TestPermissionsResponse, Awaitable[compute.TestPermissionsResponse] ], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/instance_templates/transports/rest.py b/google/cloud/compute_v1/services/instance_templates/transports/rest.py index 5aeace414..529c9c7b6 100644 --- a/google/cloud/compute_v1/services/instance_templates/transports/rest.py +++ b/google/cloud/compute_v1/services/instance_templates/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 InstanceTemplatesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def delete( Args: request (~.compute.DeleteInstanceTemplateRequest): - The request object. - A request message for + The request object. A request message for InstanceTemplates.Delete. See the method description for details. @@ -154,19 +153,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteInstanceTemplateRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -184,8 +182,7 @@ def get( Args: request (~.compute.GetInstanceTemplateRequest): - The request object. - A request message for + The request object. A request message for InstanceTemplates.Get. See the method description for details. @@ -214,16 +211,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -243,8 +239,7 @@ def get_iam_policy( Args: request (~.compute.GetIamPolicyInstanceTemplateRequest): - The request object. - A request message for + The request object. A request message for InstanceTemplates.GetIamPolicy. See the method description for details. @@ -314,19 +309,23 @@ def get_iam_policy( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "optionsRequestedPolicyVersion": request.options_requested_policy_version, - } + query_params = {} + if ( + compute.GetIamPolicyInstanceTemplateRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -344,8 +343,7 @@ def insert( Args: request (~.compute.InsertInstanceTemplateRequest): - The request object. - A request message for + The request object. A request message for InstanceTemplates.Insert. See the method description for details. @@ -400,15 +398,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertInstanceTemplateRequest.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() if v - ] + 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 @@ -430,8 +427,7 @@ def list( Args: request (~.compute.ListInstanceTemplatesRequest): - The request object. - A request message for + The request object. A request message for InstanceTemplates.List. See the method description for details. @@ -451,23 +447,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListInstanceTemplatesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListInstanceTemplatesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListInstanceTemplatesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListInstanceTemplatesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListInstanceTemplatesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -487,8 +486,7 @@ def set_iam_policy( Args: request (~.compute.SetIamPolicyInstanceTemplateRequest): - The request object. - A request message for + The request object. A request message for InstanceTemplates.SetIamPolicy. See the method description for details. @@ -566,12 +564,11 @@ def set_iam_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() if v - ] + 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 @@ -593,8 +590,7 @@ def test_iam_permissions( Args: request (~.compute.TestIamPermissionsInstanceTemplateRequest): - The request object. - A request message for + The request object. A request message for InstanceTemplates.TestIamPermissions. See the method description for details. @@ -622,12 +618,11 @@ def test_iam_permissions( # 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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/instances/__init__.py b/google/cloud/compute_v1/services/instances/__init__.py index a6408efd8..2fb8d6fa3 100644 --- a/google/cloud/compute_v1/services/instances/__init__.py +++ b/google/cloud/compute_v1/services/instances/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import InstancesClient __all__ = ("InstancesClient",) diff --git a/google/cloud/compute_v1/services/instances/client.py b/google/cloud/compute_v1/services/instances/client.py index fd5da4d87..120e78a47 100644 --- a/google/cloud/compute_v1/services/instances/client.py +++ b/google/cloud/compute_v1/services/instances/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.instances import pagers from google.cloud.compute_v1.types import compute - from .transports.base import InstancesTransport, DEFAULT_CLIENT_INFO from .transports.rest import InstancesRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, InstancesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -373,7 +370,6 @@ def add_access_config( This corresponds to the ``access_config_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. @@ -427,10 +423,8 @@ def add_access_config( # there are no flattened fields. if not isinstance(request, compute.AddAccessConfigInstanceRequest): request = compute.AddAccessConfigInstanceRequest(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: @@ -495,7 +489,6 @@ def add_resource_policies( This corresponds to the ``instances_add_resource_policies_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. @@ -549,10 +542,8 @@ def add_resource_policies( # there are no flattened fields. if not isinstance(request, compute.AddResourcePoliciesInstanceRequest): request = compute.AddResourcePoliciesInstanceRequest(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: @@ -596,7 +587,6 @@ def aggregated_list( 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. @@ -626,10 +616,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListInstancesRequest): request = compute.AggregatedListInstancesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -694,7 +682,6 @@ def attach_disk( This corresponds to the ``attached_disk_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. @@ -746,10 +733,8 @@ def attach_disk( # there are no flattened fields. if not isinstance(request, compute.AttachDiskInstanceRequest): request = compute.AttachDiskInstanceRequest(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: @@ -807,7 +792,6 @@ def delete( This corresponds to the ``instance`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -859,10 +843,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteInstanceRequest): request = compute.DeleteInstanceRequest(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: @@ -930,7 +912,6 @@ def delete_access_config( 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. @@ -984,10 +965,8 @@ def delete_access_config( # there are no flattened fields. if not isinstance(request, compute.DeleteAccessConfigInstanceRequest): request = compute.DeleteAccessConfigInstanceRequest(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: @@ -1054,7 +1033,6 @@ def detach_disk( This corresponds to the ``device_name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1106,10 +1084,8 @@ def detach_disk( # there are no flattened fields. if not isinstance(request, compute.DetachDiskInstanceRequest): request = compute.DetachDiskInstanceRequest(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: @@ -1166,7 +1142,6 @@ def get( This corresponds to the ``instance`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1199,10 +1174,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetInstanceRequest): request = compute.GetInstanceRequest(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: @@ -1257,7 +1230,6 @@ def get_guest_attributes( This corresponds to the ``instance`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1284,10 +1256,8 @@ def get_guest_attributes( # there are no flattened fields. if not isinstance(request, compute.GetGuestAttributesInstanceRequest): request = compute.GetGuestAttributesInstanceRequest(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: @@ -1343,7 +1313,6 @@ def get_iam_policy( 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. @@ -1421,10 +1390,8 @@ def get_iam_policy( # there are no flattened fields. if not isinstance(request, compute.GetIamPolicyInstanceRequest): request = compute.GetIamPolicyInstanceRequest(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: @@ -1479,7 +1446,6 @@ def get_screenshot( This corresponds to the ``instance`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1506,10 +1472,8 @@ def get_screenshot( # there are no flattened fields. if not isinstance(request, compute.GetScreenshotInstanceRequest): request = compute.GetScreenshotInstanceRequest(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: @@ -1565,7 +1529,6 @@ def get_serial_port_output( This corresponds to the ``instance`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1592,10 +1555,8 @@ def get_serial_port_output( # there are no flattened fields. if not isinstance(request, compute.GetSerialPortOutputInstanceRequest): request = compute.GetSerialPortOutputInstanceRequest(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: @@ -1650,7 +1611,6 @@ def get_shielded_instance_identity( This corresponds to the ``instance`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1677,10 +1637,8 @@ def get_shielded_instance_identity( # there are no flattened fields. if not isinstance(request, compute.GetShieldedInstanceIdentityInstanceRequest): request = compute.GetShieldedInstanceIdentityInstanceRequest(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: @@ -1736,7 +1694,6 @@ def insert( This corresponds to the ``instance_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. @@ -1788,10 +1745,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertInstanceRequest): request = compute.InsertInstanceRequest(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: @@ -1838,7 +1793,6 @@ def list( This corresponds to the ``zone`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1869,10 +1823,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListInstancesRequest): request = compute.ListInstancesRequest(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: @@ -1938,7 +1890,6 @@ def list_referrers( This corresponds to the ``instance`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1970,10 +1921,8 @@ def list_referrers( # there are no flattened fields. if not isinstance(request, compute.ListReferrersInstancesRequest): request = compute.ListReferrersInstancesRequest(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: @@ -2038,7 +1987,6 @@ def remove_resource_policies( This corresponds to the ``instances_remove_resource_policies_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. @@ -2097,10 +2045,8 @@ def remove_resource_policies( # there are no flattened fields. if not isinstance(request, compute.RemoveResourcePoliciesInstanceRequest): request = compute.RemoveResourcePoliciesInstanceRequest(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: @@ -2160,7 +2106,6 @@ def reset( This corresponds to the ``instance`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2212,10 +2157,8 @@ def reset( # there are no flattened fields. if not isinstance(request, compute.ResetInstanceRequest): request = compute.ResetInstanceRequest(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: @@ -2270,7 +2213,6 @@ def set_deletion_protection( 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. @@ -2322,10 +2264,8 @@ def set_deletion_protection( # there are no flattened fields. if not isinstance(request, compute.SetDeletionProtectionInstanceRequest): request = compute.SetDeletionProtectionInstanceRequest(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: @@ -2397,7 +2337,6 @@ def set_disk_auto_delete( This corresponds to the ``device_name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2449,10 +2388,8 @@ def set_disk_auto_delete( # there are no flattened fields. if not isinstance(request, compute.SetDiskAutoDeleteInstanceRequest): request = compute.SetDiskAutoDeleteInstanceRequest(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: @@ -2518,7 +2455,6 @@ def set_iam_policy( This corresponds to the ``zone_set_policy_request_resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2598,10 +2534,8 @@ def set_iam_policy( # there are no flattened fields. if not isinstance(request, compute.SetIamPolicyInstanceRequest): request = compute.SetIamPolicyInstanceRequest(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: @@ -2667,7 +2601,6 @@ def set_labels( This corresponds to the ``instances_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. @@ -2721,10 +2654,8 @@ def set_labels( # there are no flattened fields. if not isinstance(request, compute.SetLabelsInstanceRequest): request = compute.SetLabelsInstanceRequest(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: @@ -2790,7 +2721,6 @@ def set_machine_resources( This corresponds to the ``instances_set_machine_resources_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. @@ -2844,10 +2774,8 @@ def set_machine_resources( # there are no flattened fields. if not isinstance(request, compute.SetMachineResourcesInstanceRequest): request = compute.SetMachineResourcesInstanceRequest(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: @@ -2913,7 +2841,6 @@ def set_machine_type( This corresponds to the ``instances_set_machine_type_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. @@ -2967,10 +2894,8 @@ def set_machine_type( # there are no flattened fields. if not isinstance(request, compute.SetMachineTypeInstanceRequest): request = compute.SetMachineTypeInstanceRequest(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: @@ -3036,7 +2961,6 @@ def set_metadata( This corresponds to the ``metadata_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. @@ -3088,10 +3012,8 @@ def set_metadata( # there are no flattened fields. if not isinstance(request, compute.SetMetadataInstanceRequest): request = compute.SetMetadataInstanceRequest(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: @@ -3157,7 +3079,6 @@ def set_min_cpu_platform( This corresponds to the ``instances_set_min_cpu_platform_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. @@ -3211,10 +3132,8 @@ def set_min_cpu_platform( # there are no flattened fields. if not isinstance(request, compute.SetMinCpuPlatformInstanceRequest): request = compute.SetMinCpuPlatformInstanceRequest(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: @@ -3280,7 +3199,6 @@ def set_scheduling( This corresponds to the ``scheduling_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. @@ -3332,10 +3250,8 @@ def set_scheduling( # there are no flattened fields. if not isinstance(request, compute.SetSchedulingInstanceRequest): request = compute.SetSchedulingInstanceRequest(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: @@ -3400,7 +3316,6 @@ def set_service_account( This corresponds to the ``instances_set_service_account_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. @@ -3454,10 +3369,8 @@ def set_service_account( # there are no flattened fields. if not isinstance(request, compute.SetServiceAccountInstanceRequest): request = compute.SetServiceAccountInstanceRequest(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: @@ -3525,7 +3438,6 @@ def set_shielded_instance_integrity_policy( This corresponds to the ``shielded_instance_integrity_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. @@ -3581,10 +3493,8 @@ def set_shielded_instance_integrity_policy( request, compute.SetShieldedInstanceIntegrityPolicyInstanceRequest ): request = compute.SetShieldedInstanceIntegrityPolicyInstanceRequest(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: @@ -3652,7 +3562,6 @@ def set_tags( This corresponds to the ``tags_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. @@ -3704,10 +3613,8 @@ def set_tags( # there are no flattened fields. if not isinstance(request, compute.SetTagsInstanceRequest): request = compute.SetTagsInstanceRequest(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: @@ -3764,7 +3671,6 @@ def simulate_maintenance_event( This corresponds to the ``instance`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -3816,10 +3722,8 @@ def simulate_maintenance_event( # there are no flattened fields. if not isinstance(request, compute.SimulateMaintenanceEventInstanceRequest): request = compute.SimulateMaintenanceEventInstanceRequest(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: @@ -3877,7 +3781,6 @@ def start( This corresponds to the ``instance`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -3929,10 +3832,8 @@ def start( # there are no flattened fields. if not isinstance(request, compute.StartInstanceRequest): request = compute.StartInstanceRequest(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: @@ -3995,7 +3896,6 @@ def start_with_encryption_key( This corresponds to the ``instances_start_with_encryption_key_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. @@ -4054,10 +3954,8 @@ def start_with_encryption_key( # there are no flattened fields. if not isinstance(request, compute.StartWithEncryptionKeyInstanceRequest): request = compute.StartWithEncryptionKeyInstanceRequest(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: @@ -4123,7 +4021,6 @@ def stop( This corresponds to the ``instance`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -4175,10 +4072,8 @@ def stop( # there are no flattened fields. if not isinstance(request, compute.StopInstanceRequest): request = compute.StopInstanceRequest(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: @@ -4240,7 +4135,6 @@ def test_iam_permissions( 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. @@ -4269,10 +4163,8 @@ def test_iam_permissions( # there are no flattened fields. if not isinstance(request, compute.TestIamPermissionsInstanceRequest): request = compute.TestIamPermissionsInstanceRequest(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: @@ -4340,7 +4232,6 @@ def update( This corresponds to the ``instance_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. @@ -4392,10 +4283,8 @@ def update( # there are no flattened fields. if not isinstance(request, compute.UpdateInstanceRequest): request = compute.UpdateInstanceRequest(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: @@ -4467,7 +4356,6 @@ def update_access_config( This corresponds to the ``access_config_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. @@ -4521,10 +4409,8 @@ def update_access_config( # there are no flattened fields. if not isinstance(request, compute.UpdateAccessConfigInstanceRequest): request = compute.UpdateAccessConfigInstanceRequest(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: @@ -4592,7 +4478,6 @@ def update_display_device( This corresponds to the ``display_device_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. @@ -4644,10 +4529,8 @@ def update_display_device( # there are no flattened fields. if not isinstance(request, compute.UpdateDisplayDeviceInstanceRequest): request = compute.UpdateDisplayDeviceInstanceRequest(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: @@ -4717,7 +4600,6 @@ def update_network_interface( This corresponds to the ``network_interface_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. @@ -4771,10 +4653,8 @@ def update_network_interface( # there are no flattened fields. if not isinstance(request, compute.UpdateNetworkInterfaceInstanceRequest): request = compute.UpdateNetworkInterfaceInstanceRequest(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: @@ -4842,7 +4722,6 @@ def update_shielded_instance_config( This corresponds to the ``shielded_instance_config_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. @@ -4896,10 +4775,8 @@ def update_shielded_instance_config( # there are no flattened fields. if not isinstance(request, compute.UpdateShieldedInstanceConfigInstanceRequest): request = compute.UpdateShieldedInstanceConfigInstanceRequest(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: diff --git a/google/cloud/compute_v1/services/instances/pagers.py b/google/cloud/compute_v1/services/instances/pagers.py index 3907eddb3..d262c74c8 100644 --- a/google/cloud/compute_v1/services/instances/pagers.py +++ b/google/cloud/compute_v1/services/instances/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/instances/transports/__init__.py b/google/cloud/compute_v1/services/instances/transports/__init__.py index 95bffc99a..818b5ff02 100644 --- a/google/cloud/compute_v1/services/instances/transports/__init__.py +++ b/google/cloud/compute_v1/services/instances/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/instances/transports/base.py b/google/cloud/compute_v1/services/instances/transports/base.py index 6a13c0da3..5adbe7c79 100644 --- a/google/cloud/compute_v1/services/instances/transports/base.py +++ b/google/cloud/compute_v1/services/instances/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class InstancesTransport(abc.ABC): """Abstract transport class for Instances.""" @@ -44,21 +54,24 @@ class InstancesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -268,29 +328,28 @@ def _prep_wrapped_messages(self, client_info): @property def add_access_config( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AddAccessConfigInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def add_resource_policies( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AddResourcePoliciesInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListInstancesRequest], - typing.Union[ - compute.InstanceAggregatedList, - typing.Awaitable[compute.InstanceAggregatedList], + Union[ + compute.InstanceAggregatedList, Awaitable[compute.InstanceAggregatedList] ], ]: raise NotImplementedError() @@ -298,96 +357,92 @@ def aggregated_list( @property def attach_disk( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AttachDiskInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def delete_access_config( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteAccessConfigInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def detach_disk( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DetachDiskInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetInstanceRequest], - typing.Union[compute.Instance, typing.Awaitable[compute.Instance]], + Union[compute.Instance, Awaitable[compute.Instance]], ]: raise NotImplementedError() @property def get_guest_attributes( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetGuestAttributesInstanceRequest], - typing.Union[ - compute.GuestAttributes, typing.Awaitable[compute.GuestAttributes] - ], + Union[compute.GuestAttributes, Awaitable[compute.GuestAttributes]], ]: raise NotImplementedError() @property def get_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetIamPolicyInstanceRequest], - typing.Union[compute.Policy, typing.Awaitable[compute.Policy]], + Union[compute.Policy, Awaitable[compute.Policy]], ]: raise NotImplementedError() @property def get_screenshot( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetScreenshotInstanceRequest], - typing.Union[compute.Screenshot, typing.Awaitable[compute.Screenshot]], + Union[compute.Screenshot, Awaitable[compute.Screenshot]], ]: raise NotImplementedError() @property def get_serial_port_output( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetSerialPortOutputInstanceRequest], - typing.Union[ - compute.SerialPortOutput, typing.Awaitable[compute.SerialPortOutput] - ], + Union[compute.SerialPortOutput, Awaitable[compute.SerialPortOutput]], ]: raise NotImplementedError() @property def get_shielded_instance_identity( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetShieldedInstanceIdentityInstanceRequest], - typing.Union[ + Union[ compute.ShieldedInstanceIdentity, - typing.Awaitable[compute.ShieldedInstanceIdentity], + Awaitable[compute.ShieldedInstanceIdentity], ], ]: raise NotImplementedError() @@ -395,203 +450,199 @@ def get_shielded_instance_identity( @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListInstancesRequest], - typing.Union[compute.InstanceList, typing.Awaitable[compute.InstanceList]], + Union[compute.InstanceList, Awaitable[compute.InstanceList]], ]: raise NotImplementedError() @property def list_referrers( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListReferrersInstancesRequest], - typing.Union[ - compute.InstanceListReferrers, - typing.Awaitable[compute.InstanceListReferrers], - ], + Union[compute.InstanceListReferrers, Awaitable[compute.InstanceListReferrers]], ]: raise NotImplementedError() @property def remove_resource_policies( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.RemoveResourcePoliciesInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def reset( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ResetInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_deletion_protection( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetDeletionProtectionInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_disk_auto_delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetDiskAutoDeleteInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetIamPolicyInstanceRequest], - typing.Union[compute.Policy, typing.Awaitable[compute.Policy]], + Union[compute.Policy, Awaitable[compute.Policy]], ]: raise NotImplementedError() @property def set_labels( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetLabelsInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_machine_resources( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetMachineResourcesInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_machine_type( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetMachineTypeInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_metadata( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetMetadataInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_min_cpu_platform( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetMinCpuPlatformInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_scheduling( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetSchedulingInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_service_account( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetServiceAccountInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_shielded_instance_integrity_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetShieldedInstanceIntegrityPolicyInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_tags( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetTagsInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def simulate_maintenance_event( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SimulateMaintenanceEventInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def start( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.StartInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def start_with_encryption_key( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.StartWithEncryptionKeyInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def stop( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.StopInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.TestIamPermissionsInstanceRequest], - typing.Union[ - compute.TestPermissionsResponse, - typing.Awaitable[compute.TestPermissionsResponse], + Union[ + compute.TestPermissionsResponse, Awaitable[compute.TestPermissionsResponse] ], ]: raise NotImplementedError() @@ -599,45 +650,45 @@ def test_iam_permissions( @property def update( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.UpdateInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def update_access_config( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.UpdateAccessConfigInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def update_display_device( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.UpdateDisplayDeviceInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def update_network_interface( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.UpdateNetworkInterfaceInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def update_shielded_instance_config( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.UpdateShieldedInstanceConfigInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/instances/transports/rest.py b/google/cloud/compute_v1/services/instances/transports/rest.py index 17120121d..aea694285 100644 --- a/google/cloud/compute_v1/services/instances/transports/rest.py +++ b/google/cloud/compute_v1/services/instances/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 InstancesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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_access_config( self, @@ -103,8 +103,7 @@ def add_access_config( Args: request (~.compute.AddAccessConfigInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.AddAccessConfig. See the method description for details. @@ -162,16 +161,16 @@ def add_access_config( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "networkInterface": request.network_interface, - "requestId": request.request_id, - } + query_params = {} + if request.network_interface: + query_params["networkInterface"] = request.network_interface + if compute.AddAccessConfigInstanceRequest.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() if v - ] + 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 @@ -193,8 +192,7 @@ def add_resource_policies( Args: request (~.compute.AddResourcePoliciesInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.AddResourcePolicies. See the method description for details. @@ -252,15 +250,14 @@ def add_resource_policies( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.AddResourcePoliciesInstanceRequest.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() if v - ] + 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 @@ -282,8 +279,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListInstancesRequest): - The request object. - A request message for + The request object. A request message for Instances.AggregatedList. See the method description for details. @@ -303,24 +299,28 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListInstancesRequest.filter in request: + query_params["filter"] = request.filter + if compute.AggregatedListInstancesRequest.include_all_scopes in request: + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListInstancesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListInstancesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListInstancesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.AggregatedListInstancesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -340,8 +340,7 @@ def attach_disk( Args: request (~.compute.AttachDiskInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.AttachDisk. See the method description for details. @@ -399,16 +398,16 @@ def attach_disk( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "forceAttach": request.force_attach, - "requestId": request.request_id, - } + query_params = {} + if compute.AttachDiskInstanceRequest.force_attach in request: + query_params["forceAttach"] = request.force_attach + if compute.AttachDiskInstanceRequest.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() if v - ] + 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 @@ -430,8 +429,7 @@ def delete( Args: request (~.compute.DeleteInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.Delete. See the method description for details. @@ -482,19 +480,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteInstanceRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -512,8 +509,7 @@ def delete_access_config( Args: request (~.compute.DeleteAccessConfigInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.DeleteAccessConfig. See the method description for details. @@ -564,21 +560,22 @@ def delete_access_config( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "accessConfig": request.access_config, - "networkInterface": request.network_interface, - "requestId": request.request_id, - } + query_params = {} + if request.access_config: + query_params["accessConfig"] = request.access_config + if request.network_interface: + query_params["networkInterface"] = request.network_interface + if compute.DeleteAccessConfigInstanceRequest.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() if v - ] + 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 - response = self._session.post(url) + response = self._session.post(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -596,8 +593,7 @@ def detach_disk( Args: request (~.compute.DetachDiskInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.DetachDisk. See the method description for details. @@ -648,20 +644,20 @@ def detach_disk( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "deviceName": request.device_name, - "requestId": request.request_id, - } + query_params = {} + if request.device_name: + query_params["deviceName"] = request.device_name + if compute.DetachDiskInstanceRequest.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() if v - ] + 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 - response = self._session.post(url) + response = self._session.post(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -679,8 +675,7 @@ def get( Args: request (~.compute.GetInstanceRequest): - The request object. - A request message for Instances.Get. + The request object. A request message for Instances.Get. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -709,16 +704,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -736,8 +730,7 @@ def get_guest_attributes( Args: request (~.compute.GetGuestAttributesInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.GetGuestAttributes. See the method description for details. @@ -760,20 +753,20 @@ def get_guest_attributes( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "queryPath": request.query_path, - "variableKey": request.variable_key, - } + query_params = {} + if compute.GetGuestAttributesInstanceRequest.query_path in request: + query_params["queryPath"] = request.query_path + if compute.GetGuestAttributesInstanceRequest.variable_key in request: + query_params["variableKey"] = request.variable_key + # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -793,8 +786,7 @@ def get_iam_policy( Args: request (~.compute.GetIamPolicyInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.GetIamPolicy. See the method description for details. @@ -867,19 +859,23 @@ def get_iam_policy( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "optionsRequestedPolicyVersion": request.options_requested_policy_version, - } + query_params = {} + if ( + compute.GetIamPolicyInstanceRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -897,8 +893,7 @@ def get_screenshot( Args: request (~.compute.GetScreenshotInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.GetScreenshot. See the method description for details. @@ -922,16 +917,15 @@ def get_screenshot( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -951,8 +945,7 @@ def get_serial_port_output( Args: request (~.compute.GetSerialPortOutputInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.GetSerialPortOutput. See the method description for details. @@ -975,20 +968,20 @@ def get_serial_port_output( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "port": request.port, - "start": request.start, - } + query_params = {} + if compute.GetSerialPortOutputInstanceRequest.port in request: + query_params["port"] = request.port + if compute.GetSerialPortOutputInstanceRequest.start in request: + query_params["start"] = request.start + # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -1009,8 +1002,7 @@ def get_shielded_instance_identity( Args: request (~.compute.GetShieldedInstanceIdentityInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.GetShieldedInstanceIdentity. See the method description for details. @@ -1034,16 +1026,15 @@ def get_shielded_instance_identity( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -1063,8 +1054,7 @@ def insert( Args: request (~.compute.InsertInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.Insert. See the method description for details. @@ -1119,16 +1109,16 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - "sourceInstanceTemplate": request.source_instance_template, - } + query_params = {} + if compute.InsertInstanceRequest.request_id in request: + query_params["requestId"] = request.request_id + if compute.InsertInstanceRequest.source_instance_template in request: + query_params["sourceInstanceTemplate"] = request.source_instance_template + # 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() if v - ] + 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 @@ -1150,8 +1140,7 @@ def list( Args: request (~.compute.ListInstancesRequest): - The request object. - A request message for Instances.List. + The request object. A request message for Instances.List. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -1170,23 +1159,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListInstancesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListInstancesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListInstancesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListInstancesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListInstancesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -1206,8 +1198,7 @@ def list_referrers( Args: request (~.compute.ListReferrersInstancesRequest): - The request object. - A request message for + The request object. A request message for Instances.ListReferrers. See the method description for details. @@ -1232,23 +1223,26 @@ def list_referrers( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListReferrersInstancesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListReferrersInstancesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListReferrersInstancesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListReferrersInstancesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListReferrersInstancesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -1268,8 +1262,7 @@ def remove_resource_policies( Args: request (~.compute.RemoveResourcePoliciesInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.RemoveResourcePolicies. See the method description for details. @@ -1327,15 +1320,14 @@ def remove_resource_policies( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.RemoveResourcePoliciesInstanceRequest.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() if v - ] + 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 @@ -1357,8 +1349,7 @@ def reset( Args: request (~.compute.ResetInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.Reset. See the method description for details. @@ -1409,19 +1400,18 @@ def reset( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.ResetInstanceRequest.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() if v - ] + 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 - response = self._session.post(url) + response = self._session.post(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -1439,8 +1429,7 @@ def set_deletion_protection( Args: request (~.compute.SetDeletionProtectionInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.SetDeletionProtection. See the method description for details. @@ -1491,20 +1480,20 @@ def set_deletion_protection( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "deletionProtection": request.deletion_protection, - "requestId": request.request_id, - } + query_params = {} + if compute.SetDeletionProtectionInstanceRequest.deletion_protection in request: + query_params["deletionProtection"] = request.deletion_protection + if compute.SetDeletionProtectionInstanceRequest.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() if v - ] + 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 - response = self._session.post(url) + response = self._session.post(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -1522,8 +1511,7 @@ def set_disk_auto_delete( Args: request (~.compute.SetDiskAutoDeleteInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.SetDiskAutoDelete. See the method description for details. @@ -1574,21 +1562,22 @@ def set_disk_auto_delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "autoDelete": request.auto_delete, - "deviceName": request.device_name, - "requestId": request.request_id, - } + query_params = {} + if request.auto_delete: + query_params["autoDelete"] = request.auto_delete + if request.device_name: + query_params["deviceName"] = request.device_name + if compute.SetDiskAutoDeleteInstanceRequest.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() if v - ] + 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 - response = self._session.post(url) + response = self._session.post(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -1606,8 +1595,7 @@ def set_iam_policy( Args: request (~.compute.SetIamPolicyInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.SetIamPolicy. See the method description for details. @@ -1688,12 +1676,11 @@ def set_iam_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() if v - ] + 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 @@ -1715,8 +1702,7 @@ def set_labels( Args: request (~.compute.SetLabelsInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.SetLabels. See the method description for details. @@ -1774,15 +1760,14 @@ def set_labels( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetLabelsInstanceRequest.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() if v - ] + 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 @@ -1804,8 +1789,7 @@ def set_machine_resources( Args: request (~.compute.SetMachineResourcesInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.SetMachineResources. See the method description for details. @@ -1863,15 +1847,14 @@ def set_machine_resources( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetMachineResourcesInstanceRequest.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() if v - ] + 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 @@ -1893,8 +1876,7 @@ def set_machine_type( Args: request (~.compute.SetMachineTypeInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.SetMachineType. See the method description for details. @@ -1952,15 +1934,14 @@ def set_machine_type( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetMachineTypeInstanceRequest.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() if v - ] + 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 @@ -1982,8 +1963,7 @@ def set_metadata( Args: request (~.compute.SetMetadataInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.SetMetadata. See the method description for details. @@ -2041,15 +2021,14 @@ def set_metadata( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetMetadataInstanceRequest.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() if v - ] + 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 @@ -2071,8 +2050,7 @@ def set_min_cpu_platform( Args: request (~.compute.SetMinCpuPlatformInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.SetMinCpuPlatform. See the method description for details. @@ -2130,15 +2108,14 @@ def set_min_cpu_platform( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetMinCpuPlatformInstanceRequest.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() if v - ] + 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 @@ -2160,8 +2137,7 @@ def set_scheduling( Args: request (~.compute.SetSchedulingInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.SetScheduling. See the method description for details. @@ -2219,15 +2195,14 @@ def set_scheduling( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetSchedulingInstanceRequest.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() if v - ] + 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 @@ -2249,8 +2224,7 @@ def set_service_account( Args: request (~.compute.SetServiceAccountInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.SetServiceAccount. See the method description for details. @@ -2308,15 +2282,14 @@ def set_service_account( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetServiceAccountInstanceRequest.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() if v - ] + 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 @@ -2339,8 +2312,7 @@ def set_shielded_instance_integrity_policy( Args: request (~.compute.SetShieldedInstanceIntegrityPolicyInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.SetShieldedInstanceIntegrityPolicy. See the method description for details. @@ -2398,15 +2370,17 @@ def set_shielded_instance_integrity_policy( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if ( + compute.SetShieldedInstanceIntegrityPolicyInstanceRequest.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() if v - ] + 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 @@ -2428,8 +2402,7 @@ def set_tags( Args: request (~.compute.SetTagsInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.SetTags. See the method description for details. @@ -2487,15 +2460,14 @@ def set_tags( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetTagsInstanceRequest.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() if v - ] + 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 @@ -2518,8 +2490,7 @@ def simulate_maintenance_event( Args: request (~.compute.SimulateMaintenanceEventInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.SimulateMaintenanceEvent. See the method description for details. @@ -2571,16 +2542,15 @@ def simulate_maintenance_event( # 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() if v - ] + 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 - response = self._session.post(url) + response = self._session.post(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -2598,8 +2568,7 @@ def start( Args: request (~.compute.StartInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.Start. See the method description for details. @@ -2650,19 +2619,18 @@ def start( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.StartInstanceRequest.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() if v - ] + 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 - response = self._session.post(url) + response = self._session.post(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -2680,8 +2648,7 @@ def start_with_encryption_key( Args: request (~.compute.StartWithEncryptionKeyInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.StartWithEncryptionKey. See the method description for details. @@ -2739,15 +2706,14 @@ def start_with_encryption_key( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.StartWithEncryptionKeyInstanceRequest.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() if v - ] + 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 @@ -2769,8 +2735,7 @@ def stop( Args: request (~.compute.StopInstanceRequest): - The request object. - A request message for Instances.Stop. + The request object. A request message for Instances.Stop. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -2820,19 +2785,18 @@ def stop( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.StopInstanceRequest.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() if v - ] + 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 - response = self._session.post(url) + response = self._session.post(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -2850,8 +2814,7 @@ def test_iam_permissions( Args: request (~.compute.TestIamPermissionsInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.TestIamPermissions. See the method description for details. @@ -2882,12 +2845,11 @@ def test_iam_permissions( # 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() if v - ] + 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 @@ -2911,8 +2873,7 @@ def update( Args: request (~.compute.UpdateInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.Update. See the method description for details. @@ -2970,17 +2931,20 @@ def update( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "minimalAction": request.minimal_action, - "mostDisruptiveAllowedAction": request.most_disruptive_allowed_action, - "requestId": request.request_id, - } + query_params = {} + if compute.UpdateInstanceRequest.minimal_action in request: + query_params["minimalAction"] = request.minimal_action + if compute.UpdateInstanceRequest.most_disruptive_allowed_action in request: + query_params[ + "mostDisruptiveAllowedAction" + ] = request.most_disruptive_allowed_action + if compute.UpdateInstanceRequest.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() if v - ] + 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 @@ -3002,8 +2966,7 @@ def update_access_config( Args: request (~.compute.UpdateAccessConfigInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.UpdateAccessConfig. See the method description for details. @@ -3061,16 +3024,16 @@ def update_access_config( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "networkInterface": request.network_interface, - "requestId": request.request_id, - } + query_params = {} + if request.network_interface: + query_params["networkInterface"] = request.network_interface + if compute.UpdateAccessConfigInstanceRequest.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() if v - ] + 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 @@ -3092,8 +3055,7 @@ def update_display_device( Args: request (~.compute.UpdateDisplayDeviceInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.UpdateDisplayDevice. See the method description for details. @@ -3151,15 +3113,14 @@ def update_display_device( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.UpdateDisplayDeviceInstanceRequest.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() if v - ] + 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 @@ -3181,8 +3142,7 @@ def update_network_interface( Args: request (~.compute.UpdateNetworkInterfaceInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.UpdateNetworkInterface. See the method description for details. @@ -3240,16 +3200,16 @@ def update_network_interface( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "networkInterface": request.network_interface, - "requestId": request.request_id, - } + query_params = {} + if request.network_interface: + query_params["networkInterface"] = request.network_interface + if compute.UpdateNetworkInterfaceInstanceRequest.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() if v - ] + 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 @@ -3272,8 +3232,7 @@ def update_shielded_instance_config( Args: request (~.compute.UpdateShieldedInstanceConfigInstanceRequest): - The request object. - A request message for + The request object. A request message for Instances.UpdateShieldedInstanceConfig. See the method description for details. @@ -3331,15 +3290,14 @@ def update_shielded_instance_config( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.UpdateShieldedInstanceConfigInstanceRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/interconnect_attachments/__init__.py b/google/cloud/compute_v1/services/interconnect_attachments/__init__.py index 6dbd34468..9a9f14a9d 100644 --- a/google/cloud/compute_v1/services/interconnect_attachments/__init__.py +++ b/google/cloud/compute_v1/services/interconnect_attachments/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import InterconnectAttachmentsClient __all__ = ("InterconnectAttachmentsClient",) diff --git a/google/cloud/compute_v1/services/interconnect_attachments/client.py b/google/cloud/compute_v1/services/interconnect_attachments/client.py index 8a4ed7dfa..f2ad8da5e 100644 --- a/google/cloud/compute_v1/services/interconnect_attachments/client.py +++ b/google/cloud/compute_v1/services/interconnect_attachments/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.interconnect_attachments import pagers from google.cloud.compute_v1.types import compute - from .transports.base import InterconnectAttachmentsTransport, DEFAULT_CLIENT_INFO from .transports.rest import InterconnectAttachmentsRestTransport @@ -217,7 +214,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, InterconnectAttachmentsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -349,7 +346,6 @@ def aggregated_list( 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. @@ -381,10 +377,8 @@ def aggregated_list( request, compute.AggregatedListInterconnectAttachmentsRequest ): request = compute.AggregatedListInterconnectAttachmentsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -439,7 +433,6 @@ def delete( This corresponds to the ``interconnect_attachment`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -491,10 +484,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteInterconnectAttachmentRequest): request = compute.DeleteInterconnectAttachmentRequest(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: @@ -547,7 +538,6 @@ def get( This corresponds to the ``interconnect_attachment`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -582,10 +572,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetInterconnectAttachmentRequest): request = compute.GetInterconnectAttachmentRequest(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: @@ -637,7 +625,6 @@ def insert( This corresponds to the ``interconnect_attachment_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. @@ -689,10 +676,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertInterconnectAttachmentRequest): request = compute.InsertInterconnectAttachmentRequest(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: @@ -740,7 +725,6 @@ def list( 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. @@ -772,10 +756,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListInterconnectAttachmentsRequest): request = compute.ListInterconnectAttachmentsRequest(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: @@ -843,7 +825,6 @@ def patch( This corresponds to the ``interconnect_attachment_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. @@ -897,10 +878,8 @@ def patch( # there are no flattened fields. if not isinstance(request, compute.PatchInterconnectAttachmentRequest): request = compute.PatchInterconnectAttachmentRequest(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: diff --git a/google/cloud/compute_v1/services/interconnect_attachments/pagers.py b/google/cloud/compute_v1/services/interconnect_attachments/pagers.py index ae4acf937..bcb65e01f 100644 --- a/google/cloud/compute_v1/services/interconnect_attachments/pagers.py +++ b/google/cloud/compute_v1/services/interconnect_attachments/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/interconnect_attachments/transports/__init__.py b/google/cloud/compute_v1/services/interconnect_attachments/transports/__init__.py index dc5dc2d1b..deb77805b 100644 --- a/google/cloud/compute_v1/services/interconnect_attachments/transports/__init__.py +++ b/google/cloud/compute_v1/services/interconnect_attachments/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/interconnect_attachments/transports/base.py b/google/cloud/compute_v1/services/interconnect_attachments/transports/base.py index 099a18e7e..121c8a8d4 100644 --- a/google/cloud/compute_v1/services/interconnect_attachments/transports/base.py +++ b/google/cloud/compute_v1/services/interconnect_attachments/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class InterconnectAttachmentsTransport(abc.ABC): """Abstract transport class for InterconnectAttachments.""" @@ -44,21 +54,24 @@ class InterconnectAttachmentsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -130,11 +190,11 @@ def _prep_wrapped_messages(self, client_info): @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListInterconnectAttachmentsRequest], - typing.Union[ + Union[ compute.InterconnectAttachmentAggregatedList, - typing.Awaitable[compute.InterconnectAttachmentAggregatedList], + Awaitable[compute.InterconnectAttachmentAggregatedList], ], ]: raise NotImplementedError() @@ -142,20 +202,19 @@ def aggregated_list( @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteInterconnectAttachmentRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetInterconnectAttachmentRequest], - typing.Union[ - compute.InterconnectAttachment, - typing.Awaitable[compute.InterconnectAttachment], + Union[ + compute.InterconnectAttachment, Awaitable[compute.InterconnectAttachment] ], ]: raise NotImplementedError() @@ -163,20 +222,20 @@ def get( @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertInterconnectAttachmentRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListInterconnectAttachmentsRequest], - typing.Union[ + Union[ compute.InterconnectAttachmentList, - typing.Awaitable[compute.InterconnectAttachmentList], + Awaitable[compute.InterconnectAttachmentList], ], ]: raise NotImplementedError() @@ -184,9 +243,9 @@ def list( @property def patch( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchInterconnectAttachmentRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/interconnect_attachments/transports/rest.py b/google/cloud/compute_v1/services/interconnect_attachments/transports/rest.py index 3b0be04eb..b8f2f8396 100644 --- a/google/cloud/compute_v1/services/interconnect_attachments/transports/rest.py +++ b/google/cloud/compute_v1/services/interconnect_attachments/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 InterconnectAttachmentsTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListInterconnectAttachmentsRequest): - The request object. - A request message for + The request object. A request message for InterconnectAttachments.AggregatedList. See the method description for details. @@ -124,24 +123,34 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListInterconnectAttachmentsRequest.filter in request: + query_params["filter"] = request.filter + if ( + compute.AggregatedListInterconnectAttachmentsRequest.include_all_scopes + in request + ): + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListInterconnectAttachmentsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListInterconnectAttachmentsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListInterconnectAttachmentsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if ( + compute.AggregatedListInterconnectAttachmentsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -161,8 +170,7 @@ def delete( Args: request (~.compute.DeleteInterconnectAttachmentRequest): - The request object. - A request message for + The request object. A request message for InterconnectAttachments.Delete. See the method description for details. @@ -213,19 +221,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteInterconnectAttachmentRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -243,8 +250,7 @@ def get( Args: request (~.compute.GetInterconnectAttachmentRequest): - The request object. - A request message for + The request object. A request message for InterconnectAttachments.Get. See the method description for details. @@ -275,16 +281,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -304,8 +309,7 @@ def insert( Args: request (~.compute.InsertInterconnectAttachmentRequest): - The request object. - A request message for + The request object. A request message for InterconnectAttachments.Insert. See the method description for details. @@ -360,16 +364,16 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - "validateOnly": request.validate_only, - } + query_params = {} + if compute.InsertInterconnectAttachmentRequest.request_id in request: + query_params["requestId"] = request.request_id + if compute.InsertInterconnectAttachmentRequest.validate_only in request: + query_params["validateOnly"] = request.validate_only + # 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() if v - ] + 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 @@ -391,8 +395,7 @@ def list( Args: request (~.compute.ListInterconnectAttachmentsRequest): - The request object. - A request message for + The request object. A request message for InterconnectAttachments.List. See the method description for details. @@ -415,23 +418,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListInterconnectAttachmentsRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListInterconnectAttachmentsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListInterconnectAttachmentsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListInterconnectAttachmentsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListInterconnectAttachmentsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -451,8 +457,7 @@ def patch( Args: request (~.compute.PatchInterconnectAttachmentRequest): - The request object. - A request message for + The request object. A request message for InterconnectAttachments.Patch. See the method description for details. @@ -510,15 +515,14 @@ def patch( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.PatchInterconnectAttachmentRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/interconnect_locations/__init__.py b/google/cloud/compute_v1/services/interconnect_locations/__init__.py index a0278c79e..1caf82cfb 100644 --- a/google/cloud/compute_v1/services/interconnect_locations/__init__.py +++ b/google/cloud/compute_v1/services/interconnect_locations/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import InterconnectLocationsClient __all__ = ("InterconnectLocationsClient",) diff --git a/google/cloud/compute_v1/services/interconnect_locations/client.py b/google/cloud/compute_v1/services/interconnect_locations/client.py index 64f9a72a2..72e6b7507 100644 --- a/google/cloud/compute_v1/services/interconnect_locations/client.py +++ b/google/cloud/compute_v1/services/interconnect_locations/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.interconnect_locations import pagers from google.cloud.compute_v1.types import compute - from .transports.base import InterconnectLocationsTransport, DEFAULT_CLIENT_INFO from .transports.rest import InterconnectLocationsRestTransport @@ -217,7 +214,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, InterconnectLocationsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -358,7 +355,6 @@ def get( This corresponds to the ``interconnect_location`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -392,10 +388,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetInterconnectLocationRequest): request = compute.GetInterconnectLocationRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if interconnect_location is not None: @@ -433,7 +427,6 @@ def list( 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. @@ -465,10 +458,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListInterconnectLocationsRequest): request = compute.ListInterconnectLocationsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project diff --git a/google/cloud/compute_v1/services/interconnect_locations/pagers.py b/google/cloud/compute_v1/services/interconnect_locations/pagers.py index 176d02915..454443958 100644 --- a/google/cloud/compute_v1/services/interconnect_locations/pagers.py +++ b/google/cloud/compute_v1/services/interconnect_locations/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/interconnect_locations/transports/__init__.py b/google/cloud/compute_v1/services/interconnect_locations/transports/__init__.py index ac29f4456..d48b5f819 100644 --- a/google/cloud/compute_v1/services/interconnect_locations/transports/__init__.py +++ b/google/cloud/compute_v1/services/interconnect_locations/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/interconnect_locations/transports/base.py b/google/cloud/compute_v1/services/interconnect_locations/transports/base.py index c4333575a..f380ce641 100644 --- a/google/cloud/compute_v1/services/interconnect_locations/transports/base.py +++ b/google/cloud/compute_v1/services/interconnect_locations/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class InterconnectLocationsTransport(abc.ABC): """Abstract transport class for InterconnectLocations.""" @@ -45,21 +55,24 @@ class InterconnectLocationsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -68,13 +81,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -82,28 +95,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -119,22 +179,20 @@ def _prep_wrapped_messages(self, client_info): @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetInterconnectLocationRequest], - typing.Union[ - compute.InterconnectLocation, typing.Awaitable[compute.InterconnectLocation] - ], + Union[compute.InterconnectLocation, Awaitable[compute.InterconnectLocation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListInterconnectLocationsRequest], - typing.Union[ + Union[ compute.InterconnectLocationList, - typing.Awaitable[compute.InterconnectLocationList], + Awaitable[compute.InterconnectLocationList], ], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/interconnect_locations/transports/rest.py b/google/cloud/compute_v1/services/interconnect_locations/transports/rest.py index 1dd38c4b4..0d1c0d7a0 100644 --- a/google/cloud/compute_v1/services/interconnect_locations/transports/rest.py +++ b/google/cloud/compute_v1/services/interconnect_locations/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 InterconnectLocationsTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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 get( self, @@ -103,8 +103,7 @@ def get( Args: request (~.compute.GetInterconnectLocationRequest): - The request object. - A request message for + The request object. A request message for InterconnectLocations.Get. See the method description for details. @@ -134,16 +133,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -163,8 +161,7 @@ def list( Args: request (~.compute.ListInterconnectLocationsRequest): - The request object. - A request message for + The request object. A request message for InterconnectLocations.List. See the method description for details. @@ -187,23 +184,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListInterconnectLocationsRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListInterconnectLocationsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListInterconnectLocationsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListInterconnectLocationsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListInterconnectLocationsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() diff --git a/google/cloud/compute_v1/services/interconnects/__init__.py b/google/cloud/compute_v1/services/interconnects/__init__.py index 0da6543a2..3abd737d0 100644 --- a/google/cloud/compute_v1/services/interconnects/__init__.py +++ b/google/cloud/compute_v1/services/interconnects/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import InterconnectsClient __all__ = ("InterconnectsClient",) diff --git a/google/cloud/compute_v1/services/interconnects/client.py b/google/cloud/compute_v1/services/interconnects/client.py index 1a28e42b3..53106779b 100644 --- a/google/cloud/compute_v1/services/interconnects/client.py +++ b/google/cloud/compute_v1/services/interconnects/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.interconnects import pagers from google.cloud.compute_v1.types import compute - from .transports.base import InterconnectsTransport, DEFAULT_CLIENT_INFO from .transports.rest import InterconnectsRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, InterconnectsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -350,7 +347,6 @@ def delete( This corresponds to the ``interconnect`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -402,10 +398,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteInterconnectRequest): request = compute.DeleteInterconnectRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if interconnect is not None: @@ -449,7 +443,6 @@ def get( This corresponds to the ``interconnect`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -483,10 +476,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetInterconnectRequest): request = compute.GetInterconnectRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if interconnect is not None: @@ -532,7 +523,6 @@ def get_diagnostics( This corresponds to the ``interconnect`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -561,10 +551,8 @@ def get_diagnostics( # there are no flattened fields. if not isinstance(request, compute.GetDiagnosticsInterconnectRequest): request = compute.GetDiagnosticsInterconnectRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if interconnect is not None: @@ -608,7 +596,6 @@ def insert( This corresponds to the ``interconnect_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. @@ -660,10 +647,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertInterconnectRequest): request = compute.InsertInterconnectRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if interconnect_resource is not None: @@ -701,7 +686,6 @@ def list( 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. @@ -733,10 +717,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListInterconnectsRequest): request = compute.ListInterconnectsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -792,7 +774,6 @@ def patch( This corresponds to the ``interconnect_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. @@ -844,10 +825,8 @@ def patch( # there are no flattened fields. if not isinstance(request, compute.PatchInterconnectRequest): request = compute.PatchInterconnectRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if interconnect is not None: diff --git a/google/cloud/compute_v1/services/interconnects/pagers.py b/google/cloud/compute_v1/services/interconnects/pagers.py index 4ce5501ed..5957ea431 100644 --- a/google/cloud/compute_v1/services/interconnects/pagers.py +++ b/google/cloud/compute_v1/services/interconnects/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/interconnects/transports/__init__.py b/google/cloud/compute_v1/services/interconnects/transports/__init__.py index 644cf5272..86e59e74b 100644 --- a/google/cloud/compute_v1/services/interconnects/transports/__init__.py +++ b/google/cloud/compute_v1/services/interconnects/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/interconnects/transports/base.py b/google/cloud/compute_v1/services/interconnects/transports/base.py index 652df2824..8dc2b5262 100644 --- a/google/cloud/compute_v1/services/interconnects/transports/base.py +++ b/google/cloud/compute_v1/services/interconnects/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class InterconnectsTransport(abc.ABC): """Abstract transport class for Interconnects.""" @@ -44,21 +54,24 @@ class InterconnectsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -130,29 +190,29 @@ def _prep_wrapped_messages(self, client_info): @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteInterconnectRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetInterconnectRequest], - typing.Union[compute.Interconnect, typing.Awaitable[compute.Interconnect]], + Union[compute.Interconnect, Awaitable[compute.Interconnect]], ]: raise NotImplementedError() @property def get_diagnostics( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetDiagnosticsInterconnectRequest], - typing.Union[ + Union[ compute.InterconnectsGetDiagnosticsResponse, - typing.Awaitable[compute.InterconnectsGetDiagnosticsResponse], + Awaitable[compute.InterconnectsGetDiagnosticsResponse], ], ]: raise NotImplementedError() @@ -160,29 +220,27 @@ def get_diagnostics( @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertInterconnectRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListInterconnectsRequest], - typing.Union[ - compute.InterconnectList, typing.Awaitable[compute.InterconnectList] - ], + Union[compute.InterconnectList, Awaitable[compute.InterconnectList]], ]: raise NotImplementedError() @property def patch( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchInterconnectRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/interconnects/transports/rest.py b/google/cloud/compute_v1/services/interconnects/transports/rest.py index e76972813..c210d4970 100644 --- a/google/cloud/compute_v1/services/interconnects/transports/rest.py +++ b/google/cloud/compute_v1/services/interconnects/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 InterconnectsTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def delete( Args: request (~.compute.DeleteInterconnectRequest): - The request object. - A request message for + The request object. A request message for Interconnects.Delete. See the method description for details. @@ -152,19 +151,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteInterconnectRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -182,8 +180,7 @@ def get( Args: request (~.compute.GetInterconnectRequest): - The request object. - A request message for + The request object. A request message for Interconnects.Get. See the method description for details. @@ -211,16 +208,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -240,8 +236,7 @@ def get_diagnostics( Args: request (~.compute.GetDiagnosticsInterconnectRequest): - The request object. - A request message for + The request object. A request message for Interconnects.GetDiagnostics. See the method description for details. @@ -264,16 +259,15 @@ def get_diagnostics( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -293,8 +287,7 @@ def insert( Args: request (~.compute.InsertInterconnectRequest): - The request object. - A request message for + The request object. A request message for Interconnects.Insert. See the method description for details. @@ -349,15 +342,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertInterconnectRequest.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() if v - ] + 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 @@ -379,8 +371,7 @@ def list( Args: request (~.compute.ListInterconnectsRequest): - The request object. - A request message for + The request object. A request message for Interconnects.List. See the method description for details. @@ -402,23 +393,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListInterconnectsRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListInterconnectsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListInterconnectsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListInterconnectsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListInterconnectsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -438,8 +432,7 @@ def patch( Args: request (~.compute.PatchInterconnectRequest): - The request object. - A request message for + The request object. A request message for Interconnects.Patch. See the method description for details. @@ -494,15 +487,14 @@ def patch( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.PatchInterconnectRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/license_codes/__init__.py b/google/cloud/compute_v1/services/license_codes/__init__.py index 776ca068a..234ce94d4 100644 --- a/google/cloud/compute_v1/services/license_codes/__init__.py +++ b/google/cloud/compute_v1/services/license_codes/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import LicenseCodesClient __all__ = ("LicenseCodesClient",) diff --git a/google/cloud/compute_v1/services/license_codes/client.py b/google/cloud/compute_v1/services/license_codes/client.py index 1f3ebec3c..e124cef56 100644 --- a/google/cloud/compute_v1/services/license_codes/client.py +++ b/google/cloud/compute_v1/services/license_codes/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,17 +21,16 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 LicenseCodesTransport, DEFAULT_CLIENT_INFO from .transports.rest import LicenseCodesRestTransport @@ -212,7 +209,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, LicenseCodesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -355,7 +352,6 @@ def get( This corresponds to the ``license_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -389,10 +385,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetLicenseCodeRequest): request = compute.GetLicenseCodeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if license_code is not None: @@ -446,7 +440,6 @@ def test_iam_permissions( 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. @@ -475,10 +468,8 @@ def test_iam_permissions( # there are no flattened fields. if not isinstance(request, compute.TestIamPermissionsLicenseCodeRequest): request = compute.TestIamPermissionsLicenseCodeRequest(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: diff --git a/google/cloud/compute_v1/services/license_codes/transports/__init__.py b/google/cloud/compute_v1/services/license_codes/transports/__init__.py index 68c535bdf..c29811e09 100644 --- a/google/cloud/compute_v1/services/license_codes/transports/__init__.py +++ b/google/cloud/compute_v1/services/license_codes/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/license_codes/transports/base.py b/google/cloud/compute_v1/services/license_codes/transports/base.py index 577255802..f9134fe1c 100644 --- a/google/cloud/compute_v1/services/license_codes/transports/base.py +++ b/google/cloud/compute_v1/services/license_codes/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class LicenseCodesTransport(abc.ABC): """Abstract transport class for LicenseCodes.""" @@ -45,21 +55,24 @@ class LicenseCodesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -68,13 +81,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -82,28 +95,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -121,20 +181,19 @@ def _prep_wrapped_messages(self, client_info): @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetLicenseCodeRequest], - typing.Union[compute.LicenseCode, typing.Awaitable[compute.LicenseCode]], + Union[compute.LicenseCode, Awaitable[compute.LicenseCode]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.TestIamPermissionsLicenseCodeRequest], - typing.Union[ - compute.TestPermissionsResponse, - typing.Awaitable[compute.TestPermissionsResponse], + Union[ + compute.TestPermissionsResponse, Awaitable[compute.TestPermissionsResponse] ], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/license_codes/transports/rest.py b/google/cloud/compute_v1/services/license_codes/transports/rest.py index 3b3730e53..a5654f343 100644 --- a/google/cloud/compute_v1/services/license_codes/transports/rest.py +++ b/google/cloud/compute_v1/services/license_codes/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 LicenseCodesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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 get( self, @@ -103,8 +103,7 @@ def get( Args: request (~.compute.GetLicenseCodeRequest): - The request object. - A request message for + The request object. A request message for LicenseCodes.Get. See the method description for details. @@ -132,16 +131,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -161,8 +159,7 @@ def test_iam_permissions( Args: request (~.compute.TestIamPermissionsLicenseCodeRequest): - The request object. - A request message for + The request object. A request message for LicenseCodes.TestIamPermissions. See the method description for details. @@ -190,12 +187,11 @@ def test_iam_permissions( # 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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/licenses/__init__.py b/google/cloud/compute_v1/services/licenses/__init__.py index e4634fb9c..8d4691c97 100644 --- a/google/cloud/compute_v1/services/licenses/__init__.py +++ b/google/cloud/compute_v1/services/licenses/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import LicensesClient __all__ = ("LicensesClient",) diff --git a/google/cloud/compute_v1/services/licenses/client.py b/google/cloud/compute_v1/services/licenses/client.py index 58f6f8177..6a407fac9 100644 --- a/google/cloud/compute_v1/services/licenses/client.py +++ b/google/cloud/compute_v1/services/licenses/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.licenses import pagers from google.cloud.compute_v1.types import compute - from .transports.base import LicensesTransport, DEFAULT_CLIENT_INFO from .transports.rest import LicensesRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, LicensesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -353,7 +350,6 @@ def delete( This corresponds to the ``license_`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -405,10 +401,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteLicenseRequest): request = compute.DeleteLicenseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if license_ is not None: @@ -454,7 +448,6 @@ def get( This corresponds to the ``license_`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -488,10 +481,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetLicenseRequest): request = compute.GetLicenseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if license_ is not None: @@ -539,7 +530,6 @@ def get_iam_policy( 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. @@ -617,10 +607,8 @@ def get_iam_policy( # there are no flattened fields. if not isinstance(request, compute.GetIamPolicyLicenseRequest): request = compute.GetIamPolicyLicenseRequest(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: @@ -665,7 +653,6 @@ def insert( This corresponds to the ``license_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. @@ -717,10 +704,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertLicenseRequest): request = compute.InsertLicenseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if license_resource is not None: @@ -765,7 +750,6 @@ def list( 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. @@ -795,10 +779,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListLicensesRequest): request = compute.ListLicensesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -856,7 +838,6 @@ def set_iam_policy( This corresponds to the ``global_set_policy_request_resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -936,10 +917,8 @@ def set_iam_policy( # there are no flattened fields. if not isinstance(request, compute.SetIamPolicyLicenseRequest): request = compute.SetIamPolicyLicenseRequest(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: @@ -997,7 +976,6 @@ def test_iam_permissions( 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. @@ -1026,10 +1004,8 @@ def test_iam_permissions( # there are no flattened fields. if not isinstance(request, compute.TestIamPermissionsLicenseRequest): request = compute.TestIamPermissionsLicenseRequest(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: diff --git a/google/cloud/compute_v1/services/licenses/pagers.py b/google/cloud/compute_v1/services/licenses/pagers.py index b6c5bd63a..e22067820 100644 --- a/google/cloud/compute_v1/services/licenses/pagers.py +++ b/google/cloud/compute_v1/services/licenses/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/licenses/transports/__init__.py b/google/cloud/compute_v1/services/licenses/transports/__init__.py index 7f10bc354..f76b5a9fd 100644 --- a/google/cloud/compute_v1/services/licenses/transports/__init__.py +++ b/google/cloud/compute_v1/services/licenses/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/licenses/transports/base.py b/google/cloud/compute_v1/services/licenses/transports/base.py index e122e0e11..1c94a953e 100644 --- a/google/cloud/compute_v1/services/licenses/transports/base.py +++ b/google/cloud/compute_v1/services/licenses/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class LicensesTransport(abc.ABC): """Abstract transport class for Licenses.""" @@ -44,21 +54,24 @@ class LicensesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -135,67 +195,63 @@ def _prep_wrapped_messages(self, client_info): @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteLicenseRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ - [compute.GetLicenseRequest], - typing.Union[compute.License, typing.Awaitable[compute.License]], + ) -> Callable[ + [compute.GetLicenseRequest], Union[compute.License, Awaitable[compute.License]] ]: raise NotImplementedError() @property def get_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetIamPolicyLicenseRequest], - typing.Union[compute.Policy, typing.Awaitable[compute.Policy]], + Union[compute.Policy, Awaitable[compute.Policy]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertLicenseRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListLicensesRequest], - typing.Union[ - compute.LicensesListResponse, typing.Awaitable[compute.LicensesListResponse] - ], + Union[compute.LicensesListResponse, Awaitable[compute.LicensesListResponse]], ]: raise NotImplementedError() @property def set_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetIamPolicyLicenseRequest], - typing.Union[compute.Policy, typing.Awaitable[compute.Policy]], + Union[compute.Policy, Awaitable[compute.Policy]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.TestIamPermissionsLicenseRequest], - typing.Union[ - compute.TestPermissionsResponse, - typing.Awaitable[compute.TestPermissionsResponse], + Union[ + compute.TestPermissionsResponse, Awaitable[compute.TestPermissionsResponse] ], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/licenses/transports/rest.py b/google/cloud/compute_v1/services/licenses/transports/rest.py index 1369503ed..e61526e69 100644 --- a/google/cloud/compute_v1/services/licenses/transports/rest.py +++ b/google/cloud/compute_v1/services/licenses/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 LicensesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def delete( Args: request (~.compute.DeleteLicenseRequest): - The request object. - A request message for + The request object. A request message for Licenses.Delete. See the method description for details. @@ -152,20 +151,20 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "license": request.license_, - "requestId": request.request_id, - } + query_params = {} + if request.license_: + query_params["license"] = request.license_ + if compute.DeleteLicenseRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -183,8 +182,7 @@ def get( Args: request (~.compute.GetLicenseRequest): - The request object. - A request message for Licenses.Get. + The request object. A request message for Licenses.Get. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -210,19 +208,18 @@ def get( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "license": request.license_, - } + query_params = {} + if request.license_: + query_params["license"] = request.license_ + # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -240,8 +237,7 @@ def get_iam_policy( Args: request (~.compute.GetIamPolicyLicenseRequest): - The request object. - A request message for + The request object. A request message for Licenses.GetIamPolicy. See the method description for details. @@ -311,19 +307,23 @@ def get_iam_policy( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "optionsRequestedPolicyVersion": request.options_requested_policy_version, - } + query_params = {} + if ( + compute.GetIamPolicyLicenseRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -341,8 +341,7 @@ def insert( Args: request (~.compute.InsertLicenseRequest): - The request object. - A request message for + The request object. A request message for Licenses.Insert. See the method description for details. @@ -397,15 +396,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertLicenseRequest.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() if v - ] + 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 @@ -427,8 +425,7 @@ def list( Args: request (~.compute.ListLicensesRequest): - The request object. - A request message for Licenses.List. + The request object. A request message for Licenses.List. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -447,23 +444,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListLicensesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListLicensesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListLicensesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListLicensesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListLicensesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -483,8 +483,7 @@ def set_iam_policy( Args: request (~.compute.SetIamPolicyLicenseRequest): - The request object. - A request message for + The request object. A request message for Licenses.SetIamPolicy. See the method description for details. @@ -562,12 +561,11 @@ def set_iam_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() if v - ] + 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 @@ -589,8 +587,7 @@ def test_iam_permissions( Args: request (~.compute.TestIamPermissionsLicenseRequest): - The request object. - A request message for + The request object. A request message for Licenses.TestIamPermissions. See the method description for details. @@ -618,12 +615,11 @@ def test_iam_permissions( # 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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/machine_types/__init__.py b/google/cloud/compute_v1/services/machine_types/__init__.py index 0f31f1962..1eb2025f7 100644 --- a/google/cloud/compute_v1/services/machine_types/__init__.py +++ b/google/cloud/compute_v1/services/machine_types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import MachineTypesClient __all__ = ("MachineTypesClient",) diff --git a/google/cloud/compute_v1/services/machine_types/client.py b/google/cloud/compute_v1/services/machine_types/client.py index b04341968..45f008787 100644 --- a/google/cloud/compute_v1/services/machine_types/client.py +++ b/google/cloud/compute_v1/services/machine_types/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.machine_types import pagers from google.cloud.compute_v1.types import compute - from .transports.base import MachineTypesTransport, DEFAULT_CLIENT_INFO from .transports.rest import MachineTypesRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, MachineTypesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -344,7 +341,6 @@ def aggregated_list( 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. @@ -374,10 +370,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListMachineTypesRequest): request = compute.AggregatedListMachineTypesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -433,7 +427,6 @@ def get( This corresponds to the ``machine_type`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -467,10 +460,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetMachineTypeRequest): request = compute.GetMachineTypeRequest(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: @@ -518,7 +509,6 @@ def list( This corresponds to the ``zone`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -549,10 +539,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListMachineTypesRequest): request = compute.ListMachineTypesRequest(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: diff --git a/google/cloud/compute_v1/services/machine_types/pagers.py b/google/cloud/compute_v1/services/machine_types/pagers.py index 8221af685..03022c088 100644 --- a/google/cloud/compute_v1/services/machine_types/pagers.py +++ b/google/cloud/compute_v1/services/machine_types/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/machine_types/transports/__init__.py b/google/cloud/compute_v1/services/machine_types/transports/__init__.py index edf017220..3adb876b7 100644 --- a/google/cloud/compute_v1/services/machine_types/transports/__init__.py +++ b/google/cloud/compute_v1/services/machine_types/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/machine_types/transports/base.py b/google/cloud/compute_v1/services/machine_types/transports/base.py index 4b7322c72..c59db0130 100644 --- a/google/cloud/compute_v1/services/machine_types/transports/base.py +++ b/google/cloud/compute_v1/services/machine_types/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class MachineTypesTransport(abc.ABC): """Abstract transport class for MachineTypes.""" @@ -45,21 +55,24 @@ class MachineTypesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -68,13 +81,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -82,28 +95,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -122,11 +182,11 @@ def _prep_wrapped_messages(self, client_info): @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListMachineTypesRequest], - typing.Union[ + Union[ compute.MachineTypeAggregatedList, - typing.Awaitable[compute.MachineTypeAggregatedList], + Awaitable[compute.MachineTypeAggregatedList], ], ]: raise NotImplementedError() @@ -134,20 +194,18 @@ def aggregated_list( @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetMachineTypeRequest], - typing.Union[compute.MachineType, typing.Awaitable[compute.MachineType]], + Union[compute.MachineType, Awaitable[compute.MachineType]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListMachineTypesRequest], - typing.Union[ - compute.MachineTypeList, typing.Awaitable[compute.MachineTypeList] - ], + Union[compute.MachineTypeList, Awaitable[compute.MachineTypeList]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/machine_types/transports/rest.py b/google/cloud/compute_v1/services/machine_types/transports/rest.py index 518203bbb..1bff48975 100644 --- a/google/cloud/compute_v1/services/machine_types/transports/rest.py +++ b/google/cloud/compute_v1/services/machine_types/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 MachineTypesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListMachineTypesRequest): - The request object. - A request message for + The request object. A request message for MachineTypes.AggregatedList. See the method description for details. @@ -124,24 +123,28 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListMachineTypesRequest.filter in request: + query_params["filter"] = request.filter + if compute.AggregatedListMachineTypesRequest.include_all_scopes in request: + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListMachineTypesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListMachineTypesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListMachineTypesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.AggregatedListMachineTypesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -161,8 +164,7 @@ def get( Args: request (~.compute.GetMachineTypeRequest): - The request object. - A request message for + The request object. A request message for MachineTypes.Get. See the method description for details. @@ -192,16 +194,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -221,8 +222,7 @@ def list( Args: request (~.compute.ListMachineTypesRequest): - The request object. - A request message for + The request object. A request message for MachineTypes.List. See the method description for details. @@ -242,23 +242,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListMachineTypesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListMachineTypesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListMachineTypesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListMachineTypesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListMachineTypesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() diff --git a/google/cloud/compute_v1/services/network_endpoint_groups/__init__.py b/google/cloud/compute_v1/services/network_endpoint_groups/__init__.py index 15b060bcb..89621c127 100644 --- a/google/cloud/compute_v1/services/network_endpoint_groups/__init__.py +++ b/google/cloud/compute_v1/services/network_endpoint_groups/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import NetworkEndpointGroupsClient __all__ = ("NetworkEndpointGroupsClient",) diff --git a/google/cloud/compute_v1/services/network_endpoint_groups/client.py b/google/cloud/compute_v1/services/network_endpoint_groups/client.py index 67b7509d0..316988e95 100644 --- a/google/cloud/compute_v1/services/network_endpoint_groups/client.py +++ b/google/cloud/compute_v1/services/network_endpoint_groups/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.network_endpoint_groups import pagers from google.cloud.compute_v1.types import compute - from .transports.base import NetworkEndpointGroupsTransport, DEFAULT_CLIENT_INFO from .transports.rest import NetworkEndpointGroupsRestTransport @@ -217,7 +214,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, NetworkEndpointGroupsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -349,7 +346,6 @@ def aggregated_list( 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. @@ -379,10 +375,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListNetworkEndpointGroupsRequest): request = compute.AggregatedListNetworkEndpointGroupsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -449,7 +443,6 @@ def attach_network_endpoints( This corresponds to the ``network_endpoint_groups_attach_endpoints_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. @@ -510,10 +503,8 @@ def attach_network_endpoints( request, compute.AttachNetworkEndpointsNetworkEndpointGroupRequest ): request = compute.AttachNetworkEndpointsNetworkEndpointGroupRequest(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: @@ -578,7 +569,6 @@ def delete( This corresponds to the ``network_endpoint_group`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -630,10 +620,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteNetworkEndpointGroupRequest): request = compute.DeleteNetworkEndpointGroupRequest(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: @@ -698,7 +686,6 @@ def detach_network_endpoints( This corresponds to the ``network_endpoint_groups_detach_endpoints_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. @@ -759,10 +746,8 @@ def detach_network_endpoints( request, compute.DetachNetworkEndpointsNetworkEndpointGroupRequest ): request = compute.DetachNetworkEndpointsNetworkEndpointGroupRequest(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: @@ -824,7 +809,6 @@ def get( This corresponds to the ``network_endpoint_group`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -865,10 +849,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetNetworkEndpointGroupRequest): request = compute.GetNetworkEndpointGroupRequest(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: @@ -924,7 +906,6 @@ def insert( This corresponds to the ``network_endpoint_group_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. @@ -976,10 +957,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertNetworkEndpointGroupRequest): request = compute.InsertNetworkEndpointGroupRequest(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: @@ -1030,7 +1009,6 @@ def list( This corresponds to the ``zone`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1060,10 +1038,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListNetworkEndpointGroupsRequest): request = compute.ListNetworkEndpointGroupsRequest(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: @@ -1132,7 +1108,6 @@ def list_network_endpoints( This corresponds to the ``network_endpoint_groups_list_endpoints_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. @@ -1171,10 +1146,8 @@ def list_network_endpoints( request, compute.ListNetworkEndpointsNetworkEndpointGroupsRequest ): request = compute.ListNetworkEndpointsNetworkEndpointGroupsRequest(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: @@ -1246,7 +1219,6 @@ def test_iam_permissions( 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. @@ -1277,10 +1249,8 @@ def test_iam_permissions( request, compute.TestIamPermissionsNetworkEndpointGroupRequest ): request = compute.TestIamPermissionsNetworkEndpointGroupRequest(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: diff --git a/google/cloud/compute_v1/services/network_endpoint_groups/pagers.py b/google/cloud/compute_v1/services/network_endpoint_groups/pagers.py index 6a377efbd..d9191ba28 100644 --- a/google/cloud/compute_v1/services/network_endpoint_groups/pagers.py +++ b/google/cloud/compute_v1/services/network_endpoint_groups/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/network_endpoint_groups/transports/__init__.py b/google/cloud/compute_v1/services/network_endpoint_groups/transports/__init__.py index 2cdb67509..ab5ed8fdd 100644 --- a/google/cloud/compute_v1/services/network_endpoint_groups/transports/__init__.py +++ b/google/cloud/compute_v1/services/network_endpoint_groups/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/network_endpoint_groups/transports/base.py b/google/cloud/compute_v1/services/network_endpoint_groups/transports/base.py index 30ba854ce..8d181e9b7 100644 --- a/google/cloud/compute_v1/services/network_endpoint_groups/transports/base.py +++ b/google/cloud/compute_v1/services/network_endpoint_groups/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class NetworkEndpointGroupsTransport(abc.ABC): """Abstract transport class for NetworkEndpointGroups.""" @@ -44,21 +54,24 @@ class NetworkEndpointGroupsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -147,11 +207,11 @@ def _prep_wrapped_messages(self, client_info): @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListNetworkEndpointGroupsRequest], - typing.Union[ + Union[ compute.NetworkEndpointGroupAggregatedList, - typing.Awaitable[compute.NetworkEndpointGroupAggregatedList], + Awaitable[compute.NetworkEndpointGroupAggregatedList], ], ]: raise NotImplementedError() @@ -159,58 +219,56 @@ def aggregated_list( @property def attach_network_endpoints( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AttachNetworkEndpointsNetworkEndpointGroupRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteNetworkEndpointGroupRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def detach_network_endpoints( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DetachNetworkEndpointsNetworkEndpointGroupRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetNetworkEndpointGroupRequest], - typing.Union[ - compute.NetworkEndpointGroup, typing.Awaitable[compute.NetworkEndpointGroup] - ], + Union[compute.NetworkEndpointGroup, Awaitable[compute.NetworkEndpointGroup]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertNetworkEndpointGroupRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListNetworkEndpointGroupsRequest], - typing.Union[ + Union[ compute.NetworkEndpointGroupList, - typing.Awaitable[compute.NetworkEndpointGroupList], + Awaitable[compute.NetworkEndpointGroupList], ], ]: raise NotImplementedError() @@ -218,11 +276,11 @@ def list( @property def list_network_endpoints( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListNetworkEndpointsNetworkEndpointGroupsRequest], - typing.Union[ + Union[ compute.NetworkEndpointGroupsListNetworkEndpoints, - typing.Awaitable[compute.NetworkEndpointGroupsListNetworkEndpoints], + Awaitable[compute.NetworkEndpointGroupsListNetworkEndpoints], ], ]: raise NotImplementedError() @@ -230,11 +288,10 @@ def list_network_endpoints( @property def test_iam_permissions( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.TestIamPermissionsNetworkEndpointGroupRequest], - typing.Union[ - compute.TestPermissionsResponse, - typing.Awaitable[compute.TestPermissionsResponse], + Union[ + compute.TestPermissionsResponse, Awaitable[compute.TestPermissionsResponse] ], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/network_endpoint_groups/transports/rest.py b/google/cloud/compute_v1/services/network_endpoint_groups/transports/rest.py index 0c61fe85f..93999ea36 100644 --- a/google/cloud/compute_v1/services/network_endpoint_groups/transports/rest.py +++ b/google/cloud/compute_v1/services/network_endpoint_groups/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 NetworkEndpointGroupsTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListNetworkEndpointGroupsRequest): - The request object. - A request message for + The request object. A request message for NetworkEndpointGroups.AggregatedList. See the method description for details. @@ -124,24 +123,34 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListNetworkEndpointGroupsRequest.filter in request: + query_params["filter"] = request.filter + if ( + compute.AggregatedListNetworkEndpointGroupsRequest.include_all_scopes + in request + ): + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListNetworkEndpointGroupsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListNetworkEndpointGroupsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListNetworkEndpointGroupsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if ( + compute.AggregatedListNetworkEndpointGroupsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -161,8 +170,7 @@ def attach_network_endpoints( Args: request (~.compute.AttachNetworkEndpointsNetworkEndpointGroupRequest): - The request object. - A request message for + The request object. A request message for NetworkEndpointGroups.AttachNetworkEndpoints. See the method description for details. @@ -220,15 +228,17 @@ def attach_network_endpoints( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if ( + compute.AttachNetworkEndpointsNetworkEndpointGroupRequest.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() if v - ] + 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 @@ -250,8 +260,7 @@ def delete( Args: request (~.compute.DeleteNetworkEndpointGroupRequest): - The request object. - A request message for + The request object. A request message for NetworkEndpointGroups.Delete. See the method description for details. @@ -302,19 +311,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteNetworkEndpointGroupRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -332,8 +340,7 @@ def detach_network_endpoints( Args: request (~.compute.DetachNetworkEndpointsNetworkEndpointGroupRequest): - The request object. - A request message for + The request object. A request message for NetworkEndpointGroups.DetachNetworkEndpoints. See the method description for details. @@ -391,15 +398,17 @@ def detach_network_endpoints( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if ( + compute.DetachNetworkEndpointsNetworkEndpointGroupRequest.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() if v - ] + 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 @@ -421,8 +430,7 @@ def get( Args: request (~.compute.GetNetworkEndpointGroupRequest): - The request object. - A request message for + The request object. A request message for NetworkEndpointGroups.Get. See the method description for details. @@ -459,16 +467,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -488,8 +495,7 @@ def insert( Args: request (~.compute.InsertNetworkEndpointGroupRequest): - The request object. - A request message for + The request object. A request message for NetworkEndpointGroups.Insert. See the method description for details. @@ -544,15 +550,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertNetworkEndpointGroupRequest.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() if v - ] + 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 @@ -574,8 +579,7 @@ def list( Args: request (~.compute.ListNetworkEndpointGroupsRequest): - The request object. - A request message for + The request object. A request message for NetworkEndpointGroups.List. See the method description for details. @@ -595,23 +599,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListNetworkEndpointGroupsRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListNetworkEndpointGroupsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListNetworkEndpointGroupsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListNetworkEndpointGroupsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListNetworkEndpointGroupsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -631,8 +638,7 @@ def list_network_endpoints( Args: request (~.compute.ListNetworkEndpointsNetworkEndpointGroupsRequest): - The request object. - A request message for + The request object. A request message for NetworkEndpointGroups.ListNetworkEndpoints. See the method description for details. @@ -662,19 +668,31 @@ def list_network_endpoints( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListNetworkEndpointsNetworkEndpointGroupsRequest.filter in request: + query_params["filter"] = request.filter + if ( + compute.ListNetworkEndpointsNetworkEndpointGroupsRequest.max_results + in request + ): + query_params["maxResults"] = request.max_results + if compute.ListNetworkEndpointsNetworkEndpointGroupsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if ( + compute.ListNetworkEndpointsNetworkEndpointGroupsRequest.page_token + in request + ): + query_params["pageToken"] = request.page_token + if ( + compute.ListNetworkEndpointsNetworkEndpointGroupsRequest.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() if v - ] + 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 @@ -698,8 +716,7 @@ def test_iam_permissions( Args: request (~.compute.TestIamPermissionsNetworkEndpointGroupRequest): - The request object. - A request message for + The request object. A request message for NetworkEndpointGroups.TestIamPermissions. See the method description for details. @@ -730,12 +747,11 @@ def test_iam_permissions( # 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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/networks/__init__.py b/google/cloud/compute_v1/services/networks/__init__.py index d2b2528f0..ba5c6e5cd 100644 --- a/google/cloud/compute_v1/services/networks/__init__.py +++ b/google/cloud/compute_v1/services/networks/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import NetworksClient __all__ = ("NetworksClient",) diff --git a/google/cloud/compute_v1/services/networks/client.py b/google/cloud/compute_v1/services/networks/client.py index e569f7f57..868a50b2a 100644 --- a/google/cloud/compute_v1/services/networks/client.py +++ b/google/cloud/compute_v1/services/networks/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.networks import pagers from google.cloud.compute_v1.types import compute - from .transports.base import NetworksTransport, DEFAULT_CLIENT_INFO from .transports.rest import NetworksRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, NetworksTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -358,7 +355,6 @@ def add_peering( This corresponds to the ``networks_add_peering_request_resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -412,10 +408,8 @@ def add_peering( # there are no flattened fields. if not isinstance(request, compute.AddPeeringNetworkRequest): request = compute.AddPeeringNetworkRequest(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: @@ -461,7 +455,6 @@ def delete( 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. @@ -513,10 +506,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteNetworkRequest): request = compute.DeleteNetworkRequest(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: @@ -559,7 +550,6 @@ def get( 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. @@ -592,10 +582,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetNetworkRequest): request = compute.GetNetworkRequest(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: @@ -638,7 +626,6 @@ def insert( This corresponds to the ``network_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. @@ -690,10 +677,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertNetworkRequest): request = compute.InsertNetworkRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if network_resource is not None: @@ -730,7 +715,6 @@ def list( 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. @@ -761,10 +745,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListNetworksRequest): request = compute.ListNetworksRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -812,7 +794,6 @@ def list_peering_routes( 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. @@ -842,10 +823,8 @@ def list_peering_routes( # there are no flattened fields. if not isinstance(request, compute.ListPeeringRoutesNetworksRequest): request = compute.ListPeeringRoutesNetworksRequest(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: @@ -901,7 +880,6 @@ def patch( This corresponds to the ``network_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. @@ -953,10 +931,8 @@ def patch( # there are no flattened fields. if not isinstance(request, compute.PatchNetworkRequest): request = compute.PatchNetworkRequest(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: @@ -1009,7 +985,6 @@ def remove_peering( This corresponds to the ``networks_remove_peering_request_resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1063,10 +1038,8 @@ def remove_peering( # there are no flattened fields. if not isinstance(request, compute.RemovePeeringNetworkRequest): request = compute.RemovePeeringNetworkRequest(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: @@ -1114,7 +1087,6 @@ def switch_to_custom_mode( 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. @@ -1166,10 +1138,8 @@ def switch_to_custom_mode( # there are no flattened fields. if not isinstance(request, compute.SwitchToCustomModeNetworkRequest): request = compute.SwitchToCustomModeNetworkRequest(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: @@ -1223,7 +1193,6 @@ def update_peering( This corresponds to the ``networks_update_peering_request_resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1277,10 +1246,8 @@ def update_peering( # there are no flattened fields. if not isinstance(request, compute.UpdatePeeringNetworkRequest): request = compute.UpdatePeeringNetworkRequest(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: diff --git a/google/cloud/compute_v1/services/networks/pagers.py b/google/cloud/compute_v1/services/networks/pagers.py index 3866c6c47..647a3325e 100644 --- a/google/cloud/compute_v1/services/networks/pagers.py +++ b/google/cloud/compute_v1/services/networks/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/networks/transports/__init__.py b/google/cloud/compute_v1/services/networks/transports/__init__.py index 265cabb98..292b2724d 100644 --- a/google/cloud/compute_v1/services/networks/transports/__init__.py +++ b/google/cloud/compute_v1/services/networks/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/networks/transports/base.py b/google/cloud/compute_v1/services/networks/transports/base.py index b8644a906..410f7f8fb 100644 --- a/google/cloud/compute_v1/services/networks/transports/base.py +++ b/google/cloud/compute_v1/services/networks/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class NetworksTransport(abc.ABC): """Abstract transport class for Networks.""" @@ -44,21 +54,24 @@ class NetworksTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -144,56 +204,55 @@ def _prep_wrapped_messages(self, client_info): @property def add_peering( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AddPeeringNetworkRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteNetworkRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ - [compute.GetNetworkRequest], - typing.Union[compute.Network, typing.Awaitable[compute.Network]], + ) -> Callable[ + [compute.GetNetworkRequest], Union[compute.Network, Awaitable[compute.Network]] ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertNetworkRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListNetworksRequest], - typing.Union[compute.NetworkList, typing.Awaitable[compute.NetworkList]], + Union[compute.NetworkList, Awaitable[compute.NetworkList]], ]: raise NotImplementedError() @property def list_peering_routes( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListPeeringRoutesNetworksRequest], - typing.Union[ + Union[ compute.ExchangedPeeringRoutesList, - typing.Awaitable[compute.ExchangedPeeringRoutesList], + Awaitable[compute.ExchangedPeeringRoutesList], ], ]: raise NotImplementedError() @@ -201,36 +260,36 @@ def list_peering_routes( @property def patch( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchNetworkRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def remove_peering( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.RemovePeeringNetworkRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def switch_to_custom_mode( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SwitchToCustomModeNetworkRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def update_peering( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.UpdatePeeringNetworkRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/networks/transports/rest.py b/google/cloud/compute_v1/services/networks/transports/rest.py index 7c83b6f63..44479696a 100644 --- a/google/cloud/compute_v1/services/networks/transports/rest.py +++ b/google/cloud/compute_v1/services/networks/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 NetworksTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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_peering( self, @@ -103,8 +103,7 @@ def add_peering( Args: request (~.compute.AddPeeringNetworkRequest): - The request object. - A request message for + The request object. A request message for Networks.AddPeering. See the method description for details. @@ -159,15 +158,14 @@ def add_peering( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.AddPeeringNetworkRequest.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() if v - ] + 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 @@ -189,8 +187,7 @@ def delete( Args: request (~.compute.DeleteNetworkRequest): - The request object. - A request message for + The request object. A request message for Networks.Delete. See the method description for details. @@ -238,19 +235,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteNetworkRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -268,8 +264,7 @@ def get( Args: request (~.compute.GetNetworkRequest): - The request object. - A request message for Networks.Get. + The request object. A request message for Networks.Get. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -295,16 +290,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -322,8 +316,7 @@ def insert( Args: request (~.compute.InsertNetworkRequest): - The request object. - A request message for + The request object. A request message for Networks.Insert. See the method description for details. @@ -378,15 +371,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertNetworkRequest.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() if v - ] + 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 @@ -408,8 +400,7 @@ def list( Args: request (~.compute.ListNetworksRequest): - The request object. - A request message for Networks.List. + The request object. A request message for Networks.List. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -428,23 +419,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListNetworksRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListNetworksRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListNetworksRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListNetworksRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListNetworksRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -464,8 +458,7 @@ def list_peering_routes( Args: request (~.compute.ListPeeringRoutesNetworksRequest): - The request object. - A request message for + The request object. A request message for Networks.ListPeeringRoutes. See the method description for details. @@ -485,26 +478,32 @@ def list_peering_routes( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "direction": request.direction, - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "peeringName": request.peering_name, - "region": request.region, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListPeeringRoutesNetworksRequest.direction in request: + query_params["direction"] = request.direction + if compute.ListPeeringRoutesNetworksRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListPeeringRoutesNetworksRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListPeeringRoutesNetworksRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListPeeringRoutesNetworksRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListPeeringRoutesNetworksRequest.peering_name in request: + query_params["peeringName"] = request.peering_name + if compute.ListPeeringRoutesNetworksRequest.region in request: + query_params["region"] = request.region + if compute.ListPeeringRoutesNetworksRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -524,8 +523,7 @@ def patch( Args: request (~.compute.PatchNetworkRequest): - The request object. - A request message for Networks.Patch. + The request object. A request message for Networks.Patch. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -579,15 +577,14 @@ def patch( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.PatchNetworkRequest.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() if v - ] + 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 @@ -609,8 +606,7 @@ def remove_peering( Args: request (~.compute.RemovePeeringNetworkRequest): - The request object. - A request message for + The request object. A request message for Networks.RemovePeering. See the method description for details. @@ -665,15 +661,14 @@ def remove_peering( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.RemovePeeringNetworkRequest.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() if v - ] + 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 @@ -695,8 +690,7 @@ def switch_to_custom_mode( Args: request (~.compute.SwitchToCustomModeNetworkRequest): - The request object. - A request message for + The request object. A request message for Networks.SwitchToCustomMode. See the method description for details. @@ -744,19 +738,18 @@ def switch_to_custom_mode( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SwitchToCustomModeNetworkRequest.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() if v - ] + 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 - response = self._session.post(url) + response = self._session.post(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -774,8 +767,7 @@ def update_peering( Args: request (~.compute.UpdatePeeringNetworkRequest): - The request object. - A request message for + The request object. A request message for Networks.UpdatePeering. See the method description for details. @@ -830,15 +822,14 @@ def update_peering( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.UpdatePeeringNetworkRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/node_groups/__init__.py b/google/cloud/compute_v1/services/node_groups/__init__.py index eb9b113c6..eeac66673 100644 --- a/google/cloud/compute_v1/services/node_groups/__init__.py +++ b/google/cloud/compute_v1/services/node_groups/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import NodeGroupsClient __all__ = ("NodeGroupsClient",) diff --git a/google/cloud/compute_v1/services/node_groups/client.py b/google/cloud/compute_v1/services/node_groups/client.py index 14d60b3fc..7887af8d8 100644 --- a/google/cloud/compute_v1/services/node_groups/client.py +++ b/google/cloud/compute_v1/services/node_groups/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.node_groups import pagers from google.cloud.compute_v1.types import compute - from .transports.base import NodeGroupsTransport, DEFAULT_CLIENT_INFO from .transports.rest import NodeGroupsRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, NodeGroupsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -364,7 +361,6 @@ def add_nodes( This corresponds to the ``node_groups_add_nodes_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. @@ -418,10 +414,8 @@ def add_nodes( # there are no flattened fields. if not isinstance(request, compute.AddNodesNodeGroupRequest): request = compute.AddNodesNodeGroupRequest(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: @@ -466,7 +460,6 @@ def aggregated_list( 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. @@ -496,10 +489,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListNodeGroupsRequest): request = compute.AggregatedListNodeGroupsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -556,7 +547,6 @@ def delete( This corresponds to the ``node_group`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -608,10 +598,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteNodeGroupRequest): request = compute.DeleteNodeGroupRequest(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: @@ -672,7 +660,6 @@ def delete_nodes( This corresponds to the ``node_groups_delete_nodes_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. @@ -726,10 +713,8 @@ def delete_nodes( # there are no flattened fields. if not isinstance(request, compute.DeleteNodesNodeGroupRequest): request = compute.DeleteNodesNodeGroupRequest(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: @@ -788,7 +773,6 @@ def get( This corresponds to the ``node_group`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -825,10 +809,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetNodeGroupRequest): request = compute.GetNodeGroupRequest(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: @@ -884,7 +866,6 @@ def get_iam_policy( 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. @@ -962,10 +943,8 @@ def get_iam_policy( # there are no flattened fields. if not isinstance(request, compute.GetIamPolicyNodeGroupRequest): request = compute.GetIamPolicyNodeGroupRequest(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: @@ -1027,7 +1006,6 @@ def insert( This corresponds to the ``node_group_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. @@ -1081,10 +1059,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertNodeGroupRequest): request = compute.InsertNodeGroupRequest(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: @@ -1134,7 +1110,6 @@ def list( This corresponds to the ``zone`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1165,10 +1140,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListNodeGroupsRequest): request = compute.ListNodeGroupsRequest(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: @@ -1227,7 +1200,6 @@ def list_nodes( This corresponds to the ``node_group`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1257,10 +1229,8 @@ def list_nodes( # there are no flattened fields. if not isinstance(request, compute.ListNodesNodeGroupsRequest): request = compute.ListNodesNodeGroupsRequest(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: @@ -1327,7 +1297,6 @@ def patch( This corresponds to the ``node_group_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. @@ -1379,10 +1348,8 @@ def patch( # there are no flattened fields. if not isinstance(request, compute.PatchNodeGroupRequest): request = compute.PatchNodeGroupRequest(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: @@ -1446,7 +1413,6 @@ def set_iam_policy( This corresponds to the ``zone_set_policy_request_resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1526,10 +1492,8 @@ def set_iam_policy( # there are no flattened fields. if not isinstance(request, compute.SetIamPolicyNodeGroupRequest): request = compute.SetIamPolicyNodeGroupRequest(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: @@ -1594,7 +1558,6 @@ def set_node_template( This corresponds to the ``node_groups_set_node_template_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. @@ -1648,10 +1611,8 @@ def set_node_template( # there are no flattened fields. if not isinstance(request, compute.SetNodeTemplateNodeGroupRequest): request = compute.SetNodeTemplateNodeGroupRequest(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: @@ -1717,7 +1678,6 @@ def test_iam_permissions( 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. @@ -1746,10 +1706,8 @@ def test_iam_permissions( # there are no flattened fields. if not isinstance(request, compute.TestIamPermissionsNodeGroupRequest): request = compute.TestIamPermissionsNodeGroupRequest(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: diff --git a/google/cloud/compute_v1/services/node_groups/pagers.py b/google/cloud/compute_v1/services/node_groups/pagers.py index 3bedd0f97..f372a3a7d 100644 --- a/google/cloud/compute_v1/services/node_groups/pagers.py +++ b/google/cloud/compute_v1/services/node_groups/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/node_groups/transports/__init__.py b/google/cloud/compute_v1/services/node_groups/transports/__init__.py index 2b4261d86..861920c82 100644 --- a/google/cloud/compute_v1/services/node_groups/transports/__init__.py +++ b/google/cloud/compute_v1/services/node_groups/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/node_groups/transports/base.py b/google/cloud/compute_v1/services/node_groups/transports/base.py index 78d222b8a..7b3378467 100644 --- a/google/cloud/compute_v1/services/node_groups/transports/base.py +++ b/google/cloud/compute_v1/services/node_groups/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class NodeGroupsTransport(abc.ABC): """Abstract transport class for NodeGroups.""" @@ -44,21 +54,24 @@ class NodeGroupsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -153,20 +213,19 @@ def _prep_wrapped_messages(self, client_info): @property def add_nodes( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AddNodesNodeGroupRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListNodeGroupsRequest], - typing.Union[ - compute.NodeGroupAggregatedList, - typing.Awaitable[compute.NodeGroupAggregatedList], + Union[ + compute.NodeGroupAggregatedList, Awaitable[compute.NodeGroupAggregatedList] ], ]: raise NotImplementedError() @@ -174,103 +233,100 @@ def aggregated_list( @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteNodeGroupRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def delete_nodes( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteNodesNodeGroupRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetNodeGroupRequest], - typing.Union[compute.NodeGroup, typing.Awaitable[compute.NodeGroup]], + Union[compute.NodeGroup, Awaitable[compute.NodeGroup]], ]: raise NotImplementedError() @property def get_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetIamPolicyNodeGroupRequest], - typing.Union[compute.Policy, typing.Awaitable[compute.Policy]], + Union[compute.Policy, Awaitable[compute.Policy]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertNodeGroupRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListNodeGroupsRequest], - typing.Union[compute.NodeGroupList, typing.Awaitable[compute.NodeGroupList]], + Union[compute.NodeGroupList, Awaitable[compute.NodeGroupList]], ]: raise NotImplementedError() @property def list_nodes( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListNodesNodeGroupsRequest], - typing.Union[ - compute.NodeGroupsListNodes, typing.Awaitable[compute.NodeGroupsListNodes] - ], + Union[compute.NodeGroupsListNodes, Awaitable[compute.NodeGroupsListNodes]], ]: raise NotImplementedError() @property def patch( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchNodeGroupRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetIamPolicyNodeGroupRequest], - typing.Union[compute.Policy, typing.Awaitable[compute.Policy]], + Union[compute.Policy, Awaitable[compute.Policy]], ]: raise NotImplementedError() @property def set_node_template( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetNodeTemplateNodeGroupRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.TestIamPermissionsNodeGroupRequest], - typing.Union[ - compute.TestPermissionsResponse, - typing.Awaitable[compute.TestPermissionsResponse], + Union[ + compute.TestPermissionsResponse, Awaitable[compute.TestPermissionsResponse] ], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/node_groups/transports/rest.py b/google/cloud/compute_v1/services/node_groups/transports/rest.py index 24ac14073..9a865a09b 100644 --- a/google/cloud/compute_v1/services/node_groups/transports/rest.py +++ b/google/cloud/compute_v1/services/node_groups/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 NodeGroupsTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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_nodes( self, @@ -103,8 +103,7 @@ def add_nodes( Args: request (~.compute.AddNodesNodeGroupRequest): - The request object. - A request message for + The request object. A request message for NodeGroups.AddNodes. See the method description for details. @@ -162,15 +161,14 @@ def add_nodes( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.AddNodesNodeGroupRequest.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() if v - ] + 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 @@ -192,8 +190,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListNodeGroupsRequest): - The request object. - A request message for + The request object. A request message for NodeGroups.AggregatedList. See the method description for details. @@ -213,24 +210,28 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListNodeGroupsRequest.filter in request: + query_params["filter"] = request.filter + if compute.AggregatedListNodeGroupsRequest.include_all_scopes in request: + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListNodeGroupsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListNodeGroupsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListNodeGroupsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.AggregatedListNodeGroupsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -250,8 +251,7 @@ def delete( Args: request (~.compute.DeleteNodeGroupRequest): - The request object. - A request message for + The request object. A request message for NodeGroups.Delete. See the method description for details. @@ -302,19 +302,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteNodeGroupRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -332,8 +331,7 @@ def delete_nodes( Args: request (~.compute.DeleteNodesNodeGroupRequest): - The request object. - A request message for + The request object. A request message for NodeGroups.DeleteNodes. See the method description for details. @@ -391,15 +389,14 @@ def delete_nodes( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteNodesNodeGroupRequest.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() if v - ] + 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 @@ -421,8 +418,7 @@ def get( Args: request (~.compute.GetNodeGroupRequest): - The request object. - A request message for NodeGroups.Get. + The request object. A request message for NodeGroups.Get. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -454,16 +450,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -481,8 +476,7 @@ def get_iam_policy( Args: request (~.compute.GetIamPolicyNodeGroupRequest): - The request object. - A request message for + The request object. A request message for NodeGroups.GetIamPolicy. See the method description for details. @@ -555,19 +549,23 @@ def get_iam_policy( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "optionsRequestedPolicyVersion": request.options_requested_policy_version, - } + query_params = {} + if ( + compute.GetIamPolicyNodeGroupRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -585,8 +583,7 @@ def insert( Args: request (~.compute.InsertNodeGroupRequest): - The request object. - A request message for + The request object. A request message for NodeGroups.Insert. See the method description for details. @@ -641,16 +638,16 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "initialNodeCount": request.initial_node_count, - "requestId": request.request_id, - } + query_params = {} + if request.initial_node_count: + query_params["initialNodeCount"] = request.initial_node_count + if compute.InsertNodeGroupRequest.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() if v - ] + 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 @@ -672,8 +669,7 @@ def list( Args: request (~.compute.ListNodeGroupsRequest): - The request object. - A request message for + The request object. A request message for NodeGroups.List. See the method description for details. @@ -693,23 +689,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListNodeGroupsRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListNodeGroupsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListNodeGroupsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListNodeGroupsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListNodeGroupsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -729,8 +728,7 @@ def list_nodes( Args: request (~.compute.ListNodesNodeGroupsRequest): - The request object. - A request message for + The request object. A request message for NodeGroups.ListNodes. See the method description for details. @@ -753,23 +751,26 @@ def list_nodes( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListNodesNodeGroupsRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListNodesNodeGroupsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListNodesNodeGroupsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListNodesNodeGroupsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListNodesNodeGroupsRequest.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() if v - ] + 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 - response = self._session.post(url) + response = self._session.post(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -789,8 +790,7 @@ def patch( Args: request (~.compute.PatchNodeGroupRequest): - The request object. - A request message for + The request object. A request message for NodeGroups.Patch. See the method description for details. @@ -848,15 +848,14 @@ def patch( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.PatchNodeGroupRequest.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() if v - ] + 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 @@ -878,8 +877,7 @@ def set_iam_policy( Args: request (~.compute.SetIamPolicyNodeGroupRequest): - The request object. - A request message for + The request object. A request message for NodeGroups.SetIamPolicy. See the method description for details. @@ -960,12 +958,11 @@ def set_iam_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() if v - ] + 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 @@ -987,8 +984,7 @@ def set_node_template( Args: request (~.compute.SetNodeTemplateNodeGroupRequest): - The request object. - A request message for + The request object. A request message for NodeGroups.SetNodeTemplate. See the method description for details. @@ -1046,15 +1042,14 @@ def set_node_template( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetNodeTemplateNodeGroupRequest.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() if v - ] + 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 @@ -1076,8 +1071,7 @@ def test_iam_permissions( Args: request (~.compute.TestIamPermissionsNodeGroupRequest): - The request object. - A request message for + The request object. A request message for NodeGroups.TestIamPermissions. See the method description for details. @@ -1108,12 +1102,11 @@ def test_iam_permissions( # 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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/node_templates/__init__.py b/google/cloud/compute_v1/services/node_templates/__init__.py index 525ca2698..6ee72bfaa 100644 --- a/google/cloud/compute_v1/services/node_templates/__init__.py +++ b/google/cloud/compute_v1/services/node_templates/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import NodeTemplatesClient __all__ = ("NodeTemplatesClient",) diff --git a/google/cloud/compute_v1/services/node_templates/client.py b/google/cloud/compute_v1/services/node_templates/client.py index 27bff6713..3fb0c8ae5 100644 --- a/google/cloud/compute_v1/services/node_templates/client.py +++ b/google/cloud/compute_v1/services/node_templates/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.node_templates import pagers from google.cloud.compute_v1.types import compute - from .transports.base import NodeTemplatesTransport, DEFAULT_CLIENT_INFO from .transports.rest import NodeTemplatesRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, NodeTemplatesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -344,7 +341,6 @@ def aggregated_list( 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. @@ -374,10 +370,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListNodeTemplatesRequest): request = compute.AggregatedListNodeTemplatesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -434,7 +428,6 @@ def delete( This corresponds to the ``node_template`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -486,10 +479,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteNodeTemplateRequest): request = compute.DeleteNodeTemplateRequest(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: @@ -543,7 +534,6 @@ def get( This corresponds to the ``node_template`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -576,10 +566,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetNodeTemplateRequest): request = compute.GetNodeTemplateRequest(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: @@ -635,7 +623,6 @@ def get_iam_policy( 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. @@ -713,10 +700,8 @@ def get_iam_policy( # there are no flattened fields. if not isinstance(request, compute.GetIamPolicyNodeTemplateRequest): request = compute.GetIamPolicyNodeTemplateRequest(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: @@ -770,7 +755,6 @@ def insert( This corresponds to the ``node_template_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. @@ -822,10 +806,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertNodeTemplateRequest): request = compute.InsertNodeTemplateRequest(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: @@ -873,7 +855,6 @@ def list( 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. @@ -904,10 +885,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListNodeTemplatesRequest): request = compute.ListNodeTemplatesRequest(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: @@ -973,7 +952,6 @@ def set_iam_policy( This corresponds to the ``region_set_policy_request_resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1053,10 +1031,8 @@ def set_iam_policy( # there are no flattened fields. if not isinstance(request, compute.SetIamPolicyNodeTemplateRequest): request = compute.SetIamPolicyNodeTemplateRequest(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: @@ -1122,7 +1098,6 @@ def test_iam_permissions( 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. @@ -1151,10 +1126,8 @@ def test_iam_permissions( # there are no flattened fields. if not isinstance(request, compute.TestIamPermissionsNodeTemplateRequest): request = compute.TestIamPermissionsNodeTemplateRequest(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: diff --git a/google/cloud/compute_v1/services/node_templates/pagers.py b/google/cloud/compute_v1/services/node_templates/pagers.py index 16570a828..2e9f52ed7 100644 --- a/google/cloud/compute_v1/services/node_templates/pagers.py +++ b/google/cloud/compute_v1/services/node_templates/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/node_templates/transports/__init__.py b/google/cloud/compute_v1/services/node_templates/transports/__init__.py index 3773982ea..8fd2f7782 100644 --- a/google/cloud/compute_v1/services/node_templates/transports/__init__.py +++ b/google/cloud/compute_v1/services/node_templates/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/node_templates/transports/base.py b/google/cloud/compute_v1/services/node_templates/transports/base.py index e4b72382f..151433b6a 100644 --- a/google/cloud/compute_v1/services/node_templates/transports/base.py +++ b/google/cloud/compute_v1/services/node_templates/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class NodeTemplatesTransport(abc.ABC): """Abstract transport class for NodeTemplates.""" @@ -44,21 +54,24 @@ class NodeTemplatesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -138,11 +198,11 @@ def _prep_wrapped_messages(self, client_info): @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListNodeTemplatesRequest], - typing.Union[ + Union[ compute.NodeTemplateAggregatedList, - typing.Awaitable[compute.NodeTemplateAggregatedList], + Awaitable[compute.NodeTemplateAggregatedList], ], ]: raise NotImplementedError() @@ -150,67 +210,64 @@ def aggregated_list( @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteNodeTemplateRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetNodeTemplateRequest], - typing.Union[compute.NodeTemplate, typing.Awaitable[compute.NodeTemplate]], + Union[compute.NodeTemplate, Awaitable[compute.NodeTemplate]], ]: raise NotImplementedError() @property def get_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetIamPolicyNodeTemplateRequest], - typing.Union[compute.Policy, typing.Awaitable[compute.Policy]], + Union[compute.Policy, Awaitable[compute.Policy]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertNodeTemplateRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListNodeTemplatesRequest], - typing.Union[ - compute.NodeTemplateList, typing.Awaitable[compute.NodeTemplateList] - ], + Union[compute.NodeTemplateList, Awaitable[compute.NodeTemplateList]], ]: raise NotImplementedError() @property def set_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetIamPolicyNodeTemplateRequest], - typing.Union[compute.Policy, typing.Awaitable[compute.Policy]], + Union[compute.Policy, Awaitable[compute.Policy]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.TestIamPermissionsNodeTemplateRequest], - typing.Union[ - compute.TestPermissionsResponse, - typing.Awaitable[compute.TestPermissionsResponse], + Union[ + compute.TestPermissionsResponse, Awaitable[compute.TestPermissionsResponse] ], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/node_templates/transports/rest.py b/google/cloud/compute_v1/services/node_templates/transports/rest.py index 14e4adf78..157e41d94 100644 --- a/google/cloud/compute_v1/services/node_templates/transports/rest.py +++ b/google/cloud/compute_v1/services/node_templates/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 NodeTemplatesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListNodeTemplatesRequest): - The request object. - A request message for + The request object. A request message for NodeTemplates.AggregatedList. See the method description for details. @@ -124,24 +123,28 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListNodeTemplatesRequest.filter in request: + query_params["filter"] = request.filter + if compute.AggregatedListNodeTemplatesRequest.include_all_scopes in request: + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListNodeTemplatesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListNodeTemplatesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListNodeTemplatesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.AggregatedListNodeTemplatesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -161,8 +164,7 @@ def delete( Args: request (~.compute.DeleteNodeTemplateRequest): - The request object. - A request message for + The request object. A request message for NodeTemplates.Delete. See the method description for details. @@ -213,19 +215,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteNodeTemplateRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -243,8 +244,7 @@ def get( Args: request (~.compute.GetNodeTemplateRequest): - The request object. - A request message for + The request object. A request message for NodeTemplates.Get. See the method description for details. @@ -274,16 +274,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -303,8 +302,7 @@ def get_iam_policy( Args: request (~.compute.GetIamPolicyNodeTemplateRequest): - The request object. - A request message for + The request object. A request message for NodeTemplates.GetIamPolicy. See the method description for details. @@ -377,19 +375,23 @@ def get_iam_policy( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "optionsRequestedPolicyVersion": request.options_requested_policy_version, - } + query_params = {} + if ( + compute.GetIamPolicyNodeTemplateRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -407,8 +409,7 @@ def insert( Args: request (~.compute.InsertNodeTemplateRequest): - The request object. - A request message for + The request object. A request message for NodeTemplates.Insert. See the method description for details. @@ -463,15 +464,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertNodeTemplateRequest.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() if v - ] + 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 @@ -493,8 +493,7 @@ def list( Args: request (~.compute.ListNodeTemplatesRequest): - The request object. - A request message for + The request object. A request message for NodeTemplates.List. See the method description for details. @@ -514,23 +513,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListNodeTemplatesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListNodeTemplatesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListNodeTemplatesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListNodeTemplatesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListNodeTemplatesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -550,8 +552,7 @@ def set_iam_policy( Args: request (~.compute.SetIamPolicyNodeTemplateRequest): - The request object. - A request message for + The request object. A request message for NodeTemplates.SetIamPolicy. See the method description for details. @@ -632,12 +633,11 @@ def set_iam_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() if v - ] + 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 @@ -659,8 +659,7 @@ def test_iam_permissions( Args: request (~.compute.TestIamPermissionsNodeTemplateRequest): - The request object. - A request message for + The request object. A request message for NodeTemplates.TestIamPermissions. See the method description for details. @@ -691,12 +690,11 @@ def test_iam_permissions( # 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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/node_types/__init__.py b/google/cloud/compute_v1/services/node_types/__init__.py index a33bec481..2269d734e 100644 --- a/google/cloud/compute_v1/services/node_types/__init__.py +++ b/google/cloud/compute_v1/services/node_types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import NodeTypesClient __all__ = ("NodeTypesClient",) diff --git a/google/cloud/compute_v1/services/node_types/client.py b/google/cloud/compute_v1/services/node_types/client.py index c33817efb..8e15b2a23 100644 --- a/google/cloud/compute_v1/services/node_types/client.py +++ b/google/cloud/compute_v1/services/node_types/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.node_types import pagers from google.cloud.compute_v1.types import compute - from .transports.base import NodeTypesTransport, DEFAULT_CLIENT_INFO from .transports.rest import NodeTypesRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, NodeTypesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -344,7 +341,6 @@ def aggregated_list( 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. @@ -374,10 +370,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListNodeTypesRequest): request = compute.AggregatedListNodeTypesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -432,7 +426,6 @@ def get( This corresponds to the ``node_type`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -468,10 +461,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetNodeTypeRequest): request = compute.GetNodeTypeRequest(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: @@ -518,7 +509,6 @@ def list( This corresponds to the ``zone`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -549,10 +539,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListNodeTypesRequest): request = compute.ListNodeTypesRequest(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: diff --git a/google/cloud/compute_v1/services/node_types/pagers.py b/google/cloud/compute_v1/services/node_types/pagers.py index 1c5849e80..37318acc4 100644 --- a/google/cloud/compute_v1/services/node_types/pagers.py +++ b/google/cloud/compute_v1/services/node_types/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/node_types/transports/__init__.py b/google/cloud/compute_v1/services/node_types/transports/__init__.py index cb1af17bd..7004d8d58 100644 --- a/google/cloud/compute_v1/services/node_types/transports/__init__.py +++ b/google/cloud/compute_v1/services/node_types/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/node_types/transports/base.py b/google/cloud/compute_v1/services/node_types/transports/base.py index 3efcd6166..e0e78ae1c 100644 --- a/google/cloud/compute_v1/services/node_types/transports/base.py +++ b/google/cloud/compute_v1/services/node_types/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class NodeTypesTransport(abc.ABC): """Abstract transport class for NodeTypes.""" @@ -45,21 +55,24 @@ class NodeTypesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -68,13 +81,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -82,28 +95,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -122,11 +182,10 @@ def _prep_wrapped_messages(self, client_info): @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListNodeTypesRequest], - typing.Union[ - compute.NodeTypeAggregatedList, - typing.Awaitable[compute.NodeTypeAggregatedList], + Union[ + compute.NodeTypeAggregatedList, Awaitable[compute.NodeTypeAggregatedList] ], ]: raise NotImplementedError() @@ -134,18 +193,18 @@ def aggregated_list( @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetNodeTypeRequest], - typing.Union[compute.NodeType, typing.Awaitable[compute.NodeType]], + Union[compute.NodeType, Awaitable[compute.NodeType]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListNodeTypesRequest], - typing.Union[compute.NodeTypeList, typing.Awaitable[compute.NodeTypeList]], + Union[compute.NodeTypeList, Awaitable[compute.NodeTypeList]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/node_types/transports/rest.py b/google/cloud/compute_v1/services/node_types/transports/rest.py index f6fd58338..52b733176 100644 --- a/google/cloud/compute_v1/services/node_types/transports/rest.py +++ b/google/cloud/compute_v1/services/node_types/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 NodeTypesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListNodeTypesRequest): - The request object. - A request message for + The request object. A request message for NodeTypes.AggregatedList. See the method description for details. @@ -124,24 +123,28 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListNodeTypesRequest.filter in request: + query_params["filter"] = request.filter + if compute.AggregatedListNodeTypesRequest.include_all_scopes in request: + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListNodeTypesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListNodeTypesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListNodeTypesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.AggregatedListNodeTypesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -161,8 +164,7 @@ def get( Args: request (~.compute.GetNodeTypeRequest): - The request object. - A request message for NodeTypes.Get. + The request object. A request message for NodeTypes.Get. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -194,16 +196,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -221,8 +222,7 @@ def list( Args: request (~.compute.ListNodeTypesRequest): - The request object. - A request message for NodeTypes.List. + The request object. A request message for NodeTypes.List. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -241,23 +241,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListNodeTypesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListNodeTypesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListNodeTypesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListNodeTypesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListNodeTypesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() diff --git a/google/cloud/compute_v1/services/packet_mirrorings/__init__.py b/google/cloud/compute_v1/services/packet_mirrorings/__init__.py index 1d99b0fb4..69ad3ff80 100644 --- a/google/cloud/compute_v1/services/packet_mirrorings/__init__.py +++ b/google/cloud/compute_v1/services/packet_mirrorings/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import PacketMirroringsClient __all__ = ("PacketMirroringsClient",) diff --git a/google/cloud/compute_v1/services/packet_mirrorings/client.py b/google/cloud/compute_v1/services/packet_mirrorings/client.py index 620631092..7fd15879e 100644 --- a/google/cloud/compute_v1/services/packet_mirrorings/client.py +++ b/google/cloud/compute_v1/services/packet_mirrorings/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.packet_mirrorings import pagers from google.cloud.compute_v1.types import compute - from .transports.base import PacketMirroringsTransport, DEFAULT_CLIENT_INFO from .transports.rest import PacketMirroringsRestTransport @@ -215,7 +212,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, PacketMirroringsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -346,7 +343,6 @@ def aggregated_list( 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. @@ -377,10 +373,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListPacketMirroringsRequest): request = compute.AggregatedListPacketMirroringsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -435,7 +429,6 @@ def delete( This corresponds to the ``packet_mirroring`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -487,10 +480,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeletePacketMirroringRequest): request = compute.DeletePacketMirroringRequest(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: @@ -543,7 +534,6 @@ def get( This corresponds to the ``packet_mirroring`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -580,10 +570,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetPacketMirroringRequest): request = compute.GetPacketMirroringRequest(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: @@ -636,7 +624,6 @@ def insert( This corresponds to the ``packet_mirroring_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. @@ -688,10 +675,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertPacketMirroringRequest): request = compute.InsertPacketMirroringRequest(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: @@ -737,7 +722,6 @@ def list( 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. @@ -769,10 +753,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListPacketMirroringsRequest): request = compute.ListPacketMirroringsRequest(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: @@ -838,7 +820,6 @@ def patch( This corresponds to the ``packet_mirroring_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. @@ -892,10 +873,8 @@ def patch( # there are no flattened fields. if not isinstance(request, compute.PatchPacketMirroringRequest): request = compute.PatchPacketMirroringRequest(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: @@ -959,7 +938,6 @@ def test_iam_permissions( 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. @@ -988,10 +966,8 @@ def test_iam_permissions( # there are no flattened fields. if not isinstance(request, compute.TestIamPermissionsPacketMirroringRequest): request = compute.TestIamPermissionsPacketMirroringRequest(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: diff --git a/google/cloud/compute_v1/services/packet_mirrorings/pagers.py b/google/cloud/compute_v1/services/packet_mirrorings/pagers.py index 40b54f2d3..ace55727c 100644 --- a/google/cloud/compute_v1/services/packet_mirrorings/pagers.py +++ b/google/cloud/compute_v1/services/packet_mirrorings/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/packet_mirrorings/transports/__init__.py b/google/cloud/compute_v1/services/packet_mirrorings/transports/__init__.py index 71e6d70d8..942f56581 100644 --- a/google/cloud/compute_v1/services/packet_mirrorings/transports/__init__.py +++ b/google/cloud/compute_v1/services/packet_mirrorings/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/packet_mirrorings/transports/base.py b/google/cloud/compute_v1/services/packet_mirrorings/transports/base.py index 30e68ad6a..09440be1d 100644 --- a/google/cloud/compute_v1/services/packet_mirrorings/transports/base.py +++ b/google/cloud/compute_v1/services/packet_mirrorings/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class PacketMirroringsTransport(abc.ABC): """Abstract transport class for PacketMirrorings.""" @@ -44,21 +54,24 @@ class PacketMirroringsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -135,11 +195,11 @@ def _prep_wrapped_messages(self, client_info): @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListPacketMirroringsRequest], - typing.Union[ + Union[ compute.PacketMirroringAggregatedList, - typing.Awaitable[compute.PacketMirroringAggregatedList], + Awaitable[compute.PacketMirroringAggregatedList], ], ]: raise NotImplementedError() @@ -147,60 +207,55 @@ def aggregated_list( @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeletePacketMirroringRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetPacketMirroringRequest], - typing.Union[ - compute.PacketMirroring, typing.Awaitable[compute.PacketMirroring] - ], + Union[compute.PacketMirroring, Awaitable[compute.PacketMirroring]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertPacketMirroringRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListPacketMirroringsRequest], - typing.Union[ - compute.PacketMirroringList, typing.Awaitable[compute.PacketMirroringList] - ], + Union[compute.PacketMirroringList, Awaitable[compute.PacketMirroringList]], ]: raise NotImplementedError() @property def patch( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchPacketMirroringRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.TestIamPermissionsPacketMirroringRequest], - typing.Union[ - compute.TestPermissionsResponse, - typing.Awaitable[compute.TestPermissionsResponse], + Union[ + compute.TestPermissionsResponse, Awaitable[compute.TestPermissionsResponse] ], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/packet_mirrorings/transports/rest.py b/google/cloud/compute_v1/services/packet_mirrorings/transports/rest.py index a7935411c..67e5eaf88 100644 --- a/google/cloud/compute_v1/services/packet_mirrorings/transports/rest.py +++ b/google/cloud/compute_v1/services/packet_mirrorings/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 PacketMirroringsTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListPacketMirroringsRequest): - The request object. - A request message for + The request object. A request message for PacketMirrorings.AggregatedList. See the method description for details. @@ -124,24 +123,31 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListPacketMirroringsRequest.filter in request: + query_params["filter"] = request.filter + if compute.AggregatedListPacketMirroringsRequest.include_all_scopes in request: + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListPacketMirroringsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListPacketMirroringsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListPacketMirroringsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if ( + compute.AggregatedListPacketMirroringsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -161,8 +167,7 @@ def delete( Args: request (~.compute.DeletePacketMirroringRequest): - The request object. - A request message for + The request object. A request message for PacketMirrorings.Delete. See the method description for details. @@ -213,19 +218,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeletePacketMirroringRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -243,8 +247,7 @@ def get( Args: request (~.compute.GetPacketMirroringRequest): - The request object. - A request message for + The request object. A request message for PacketMirrorings.Get. See the method description for details. @@ -277,16 +280,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -306,8 +308,7 @@ def insert( Args: request (~.compute.InsertPacketMirroringRequest): - The request object. - A request message for + The request object. A request message for PacketMirrorings.Insert. See the method description for details. @@ -362,15 +363,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertPacketMirroringRequest.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() if v - ] + 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 @@ -392,8 +392,7 @@ def list( Args: request (~.compute.ListPacketMirroringsRequest): - The request object. - A request message for + The request object. A request message for PacketMirrorings.List. See the method description for details. @@ -415,23 +414,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListPacketMirroringsRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListPacketMirroringsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListPacketMirroringsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListPacketMirroringsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListPacketMirroringsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -451,8 +453,7 @@ def patch( Args: request (~.compute.PatchPacketMirroringRequest): - The request object. - A request message for + The request object. A request message for PacketMirrorings.Patch. See the method description for details. @@ -510,15 +511,14 @@ def patch( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.PatchPacketMirroringRequest.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() if v - ] + 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 @@ -540,8 +540,7 @@ def test_iam_permissions( Args: request (~.compute.TestIamPermissionsPacketMirroringRequest): - The request object. - A request message for + The request object. A request message for PacketMirrorings.TestIamPermissions. See the method description for details. @@ -572,12 +571,11 @@ def test_iam_permissions( # 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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/projects/__init__.py b/google/cloud/compute_v1/services/projects/__init__.py index 5ed58990f..0c840fc01 100644 --- a/google/cloud/compute_v1/services/projects/__init__.py +++ b/google/cloud/compute_v1/services/projects/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import ProjectsClient __all__ = ("ProjectsClient",) diff --git a/google/cloud/compute_v1/services/projects/client.py b/google/cloud/compute_v1/services/projects/client.py index d8105efb1..96af8e934 100644 --- a/google/cloud/compute_v1/services/projects/client.py +++ b/google/cloud/compute_v1/services/projects/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.projects import pagers from google.cloud.compute_v1.types import compute - from .transports.base import ProjectsTransport, DEFAULT_CLIENT_INFO from .transports.rest import ProjectsRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ProjectsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -344,7 +341,6 @@ def disable_xpn_host( 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. @@ -396,10 +392,8 @@ def disable_xpn_host( # there are no flattened fields. if not isinstance(request, compute.DisableXpnHostProjectRequest): request = compute.DisableXpnHostProjectRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -441,7 +435,6 @@ def disable_xpn_resource( This corresponds to the ``projects_disable_xpn_resource_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. @@ -495,10 +488,8 @@ def disable_xpn_resource( # there are no flattened fields. if not isinstance(request, compute.DisableXpnResourceProjectRequest): request = compute.DisableXpnResourceProjectRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if projects_disable_xpn_resource_request_resource is not None: @@ -537,7 +528,6 @@ def enable_xpn_host( 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. @@ -589,10 +579,8 @@ def enable_xpn_host( # there are no flattened fields. if not isinstance(request, compute.EnableXpnHostProjectRequest): request = compute.EnableXpnHostProjectRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -635,7 +623,6 @@ def enable_xpn_resource( This corresponds to the ``projects_enable_xpn_resource_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. @@ -689,10 +676,8 @@ def enable_xpn_resource( # there are no flattened fields. if not isinstance(request, compute.EnableXpnResourceProjectRequest): request = compute.EnableXpnResourceProjectRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if projects_enable_xpn_resource_request_resource is not None: @@ -730,7 +715,6 @@ def get( 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. @@ -763,10 +747,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetProjectRequest): request = compute.GetProjectRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -802,7 +784,6 @@ def get_xpn_host( 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. @@ -835,10 +816,8 @@ def get_xpn_host( # there are no flattened fields. if not isinstance(request, compute.GetXpnHostProjectRequest): request = compute.GetXpnHostProjectRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -874,7 +853,6 @@ def get_xpn_resources( 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. @@ -904,10 +882,8 @@ def get_xpn_resources( # there are no flattened fields. if not isinstance(request, compute.GetXpnResourcesProjectsRequest): request = compute.GetXpnResourcesProjectsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -955,7 +931,6 @@ def list_xpn_hosts( This corresponds to the ``projects_list_xpn_hosts_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. @@ -985,10 +960,8 @@ def list_xpn_hosts( # there are no flattened fields. if not isinstance(request, compute.ListXpnHostsProjectsRequest): request = compute.ListXpnHostsProjectsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if projects_list_xpn_hosts_request_resource is not None: @@ -1039,7 +1012,6 @@ def move_disk( This corresponds to the ``disk_move_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. @@ -1091,10 +1063,8 @@ def move_disk( # there are no flattened fields. if not isinstance(request, compute.MoveDiskProjectRequest): request = compute.MoveDiskProjectRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if disk_move_request_resource is not None: @@ -1138,7 +1108,6 @@ def move_instance( This corresponds to the ``instance_move_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. @@ -1190,10 +1159,8 @@ def move_instance( # there are no flattened fields. if not isinstance(request, compute.MoveInstanceProjectRequest): request = compute.MoveInstanceProjectRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if instance_move_request_resource is not None: @@ -1238,7 +1205,6 @@ def set_common_instance_metadata( This corresponds to the ``metadata_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. @@ -1290,10 +1256,8 @@ def set_common_instance_metadata( # there are no flattened fields. if not isinstance(request, compute.SetCommonInstanceMetadataProjectRequest): request = compute.SetCommonInstanceMetadataProjectRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if metadata_resource is not None: @@ -1341,7 +1305,6 @@ def set_default_network_tier( This corresponds to the ``projects_set_default_network_tier_request_resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1395,10 +1358,8 @@ def set_default_network_tier( # there are no flattened fields. if not isinstance(request, compute.SetDefaultNetworkTierProjectRequest): request = compute.SetDefaultNetworkTierProjectRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if projects_set_default_network_tier_request_resource is not None: @@ -1446,7 +1407,6 @@ def set_usage_export_bucket( This corresponds to the ``usage_export_location_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. @@ -1498,10 +1458,8 @@ def set_usage_export_bucket( # there are no flattened fields. if not isinstance(request, compute.SetUsageExportBucketProjectRequest): request = compute.SetUsageExportBucketProjectRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if usage_export_location_resource is not None: diff --git a/google/cloud/compute_v1/services/projects/pagers.py b/google/cloud/compute_v1/services/projects/pagers.py index f94918d85..e0d6689ef 100644 --- a/google/cloud/compute_v1/services/projects/pagers.py +++ b/google/cloud/compute_v1/services/projects/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/projects/transports/__init__.py b/google/cloud/compute_v1/services/projects/transports/__init__.py index 7e7f17052..c732ee16e 100644 --- a/google/cloud/compute_v1/services/projects/transports/__init__.py +++ b/google/cloud/compute_v1/services/projects/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/projects/transports/base.py b/google/cloud/compute_v1/services/projects/transports/base.py index 39d10edb6..e97556da0 100644 --- a/google/cloud/compute_v1/services/projects/transports/base.py +++ b/google/cloud/compute_v1/services/projects/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class ProjectsTransport(abc.ABC): """Abstract transport class for Projects.""" @@ -44,21 +54,24 @@ class ProjectsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -159,65 +219,63 @@ def _prep_wrapped_messages(self, client_info): @property def disable_xpn_host( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DisableXpnHostProjectRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def disable_xpn_resource( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DisableXpnResourceProjectRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def enable_xpn_host( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.EnableXpnHostProjectRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def enable_xpn_resource( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.EnableXpnResourceProjectRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ - [compute.GetProjectRequest], - typing.Union[compute.Project, typing.Awaitable[compute.Project]], + ) -> Callable[ + [compute.GetProjectRequest], Union[compute.Project, Awaitable[compute.Project]] ]: raise NotImplementedError() @property def get_xpn_host( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetXpnHostProjectRequest], - typing.Union[compute.Project, typing.Awaitable[compute.Project]], + Union[compute.Project, Awaitable[compute.Project]], ]: raise NotImplementedError() @property def get_xpn_resources( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetXpnResourcesProjectsRequest], - typing.Union[ - compute.ProjectsGetXpnResources, - typing.Awaitable[compute.ProjectsGetXpnResources], + Union[ + compute.ProjectsGetXpnResources, Awaitable[compute.ProjectsGetXpnResources] ], ]: raise NotImplementedError() @@ -225,54 +283,54 @@ def get_xpn_resources( @property def list_xpn_hosts( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListXpnHostsProjectsRequest], - typing.Union[compute.XpnHostList, typing.Awaitable[compute.XpnHostList]], + Union[compute.XpnHostList, Awaitable[compute.XpnHostList]], ]: raise NotImplementedError() @property def move_disk( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.MoveDiskProjectRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def move_instance( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.MoveInstanceProjectRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_common_instance_metadata( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetCommonInstanceMetadataProjectRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_default_network_tier( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetDefaultNetworkTierProjectRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_usage_export_bucket( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetUsageExportBucketProjectRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/projects/transports/rest.py b/google/cloud/compute_v1/services/projects/transports/rest.py index 5ea6661d4..7c793c9da 100644 --- a/google/cloud/compute_v1/services/projects/transports/rest.py +++ b/google/cloud/compute_v1/services/projects/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 ProjectsTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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 disable_xpn_host( self, @@ -103,8 +103,7 @@ def disable_xpn_host( Args: request (~.compute.DisableXpnHostProjectRequest): - The request object. - A request message for + The request object. A request message for Projects.DisableXpnHost. See the method description for details. @@ -152,19 +151,18 @@ def disable_xpn_host( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DisableXpnHostProjectRequest.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() if v - ] + 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 - response = self._session.post(url) + response = self._session.post(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -182,8 +180,7 @@ def disable_xpn_resource( Args: request (~.compute.DisableXpnResourceProjectRequest): - The request object. - A request message for + The request object. A request message for Projects.DisableXpnResource. See the method description for details. @@ -238,15 +235,14 @@ def disable_xpn_resource( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DisableXpnResourceProjectRequest.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() if v - ] + 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 @@ -268,8 +264,7 @@ def enable_xpn_host( Args: request (~.compute.EnableXpnHostProjectRequest): - The request object. - A request message for + The request object. A request message for Projects.EnableXpnHost. See the method description for details. @@ -317,19 +312,18 @@ def enable_xpn_host( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.EnableXpnHostProjectRequest.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() if v - ] + 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 - response = self._session.post(url) + response = self._session.post(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -347,8 +341,7 @@ def enable_xpn_resource( Args: request (~.compute.EnableXpnResourceProjectRequest): - The request object. - A request message for + The request object. A request message for Projects.EnableXpnResource. See the method description for details. @@ -403,15 +396,14 @@ def enable_xpn_resource( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.EnableXpnResourceProjectRequest.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() if v - ] + 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 @@ -433,8 +425,7 @@ def get( Args: request (~.compute.GetProjectRequest): - The request object. - A request message for Projects.Get. + The request object. A request message for Projects.Get. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -460,16 +451,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -487,8 +477,7 @@ def get_xpn_host( Args: request (~.compute.GetXpnHostProjectRequest): - The request object. - A request message for + The request object. A request message for Projects.GetXpnHost. See the method description for details. @@ -515,16 +504,15 @@ def get_xpn_host( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -542,8 +530,7 @@ def get_xpn_resources( Args: request (~.compute.GetXpnResourcesProjectsRequest): - The request object. - A request message for + The request object. A request message for Projects.GetXpnResources. See the method description for details. @@ -563,23 +550,26 @@ def get_xpn_resources( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.GetXpnResourcesProjectsRequest.filter in request: + query_params["filter"] = request.filter + if compute.GetXpnResourcesProjectsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.GetXpnResourcesProjectsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.GetXpnResourcesProjectsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.GetXpnResourcesProjectsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -599,8 +589,7 @@ def list_xpn_hosts( Args: request (~.compute.ListXpnHostsProjectsRequest): - The request object. - A request message for + The request object. A request message for Projects.ListXpnHosts. See the method description for details. @@ -627,19 +616,22 @@ def list_xpn_hosts( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListXpnHostsProjectsRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListXpnHostsProjectsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListXpnHostsProjectsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListXpnHostsProjectsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListXpnHostsProjectsRequest.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() if v - ] + 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 @@ -663,8 +655,7 @@ def move_disk( Args: request (~.compute.MoveDiskProjectRequest): - The request object. - A request message for + The request object. A request message for Projects.MoveDisk. See the method description for details. @@ -719,15 +710,14 @@ def move_disk( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.MoveDiskProjectRequest.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() if v - ] + 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 @@ -749,8 +739,7 @@ def move_instance( Args: request (~.compute.MoveInstanceProjectRequest): - The request object. - A request message for + The request object. A request message for Projects.MoveInstance. See the method description for details. @@ -805,15 +794,14 @@ def move_instance( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.MoveInstanceProjectRequest.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() if v - ] + 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 @@ -836,8 +824,7 @@ def set_common_instance_metadata( Args: request (~.compute.SetCommonInstanceMetadataProjectRequest): - The request object. - A request message for + The request object. A request message for Projects.SetCommonInstanceMetadata. See the method description for details. @@ -892,15 +879,14 @@ def set_common_instance_metadata( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetCommonInstanceMetadataProjectRequest.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() if v - ] + 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 @@ -922,8 +908,7 @@ def set_default_network_tier( Args: request (~.compute.SetDefaultNetworkTierProjectRequest): - The request object. - A request message for + The request object. A request message for Projects.SetDefaultNetworkTier. See the method description for details. @@ -978,15 +963,14 @@ def set_default_network_tier( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetDefaultNetworkTierProjectRequest.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() if v - ] + 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 @@ -1008,8 +992,7 @@ def set_usage_export_bucket( Args: request (~.compute.SetUsageExportBucketProjectRequest): - The request object. - A request message for + The request object. A request message for Projects.SetUsageExportBucket. See the method description for details. @@ -1064,15 +1047,14 @@ def set_usage_export_bucket( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetUsageExportBucketProjectRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/region_autoscalers/__init__.py b/google/cloud/compute_v1/services/region_autoscalers/__init__.py index 99110e23e..f35520200 100644 --- a/google/cloud/compute_v1/services/region_autoscalers/__init__.py +++ b/google/cloud/compute_v1/services/region_autoscalers/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import RegionAutoscalersClient __all__ = ("RegionAutoscalersClient",) diff --git a/google/cloud/compute_v1/services/region_autoscalers/client.py b/google/cloud/compute_v1/services/region_autoscalers/client.py index 8f0d64cab..8904a951a 100644 --- a/google/cloud/compute_v1/services/region_autoscalers/client.py +++ b/google/cloud/compute_v1/services/region_autoscalers/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.region_autoscalers import pagers from google.cloud.compute_v1.types import compute - from .transports.base import RegionAutoscalersTransport, DEFAULT_CLIENT_INFO from .transports.rest import RegionAutoscalersRestTransport @@ -217,7 +214,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, RegionAutoscalersTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -362,7 +359,6 @@ def delete( This corresponds to the ``autoscaler`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -414,10 +410,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteRegionAutoscalerRequest): request = compute.DeleteRegionAutoscalerRequest(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: @@ -470,7 +464,6 @@ def get( This corresponds to the ``autoscaler`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -517,10 +510,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetRegionAutoscalerRequest): request = compute.GetRegionAutoscalerRequest(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: @@ -574,7 +565,6 @@ def insert( This corresponds to the ``autoscaler_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. @@ -626,10 +616,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertRegionAutoscalerRequest): request = compute.InsertRegionAutoscalerRequest(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: @@ -677,7 +665,6 @@ def list( 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. @@ -708,10 +695,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListRegionAutoscalersRequest): request = compute.ListRegionAutoscalersRequest(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: @@ -771,7 +756,6 @@ def patch( This corresponds to the ``autoscaler_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. @@ -823,10 +807,8 @@ def patch( # there are no flattened fields. if not isinstance(request, compute.PatchRegionAutoscalerRequest): request = compute.PatchRegionAutoscalerRequest(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: @@ -880,7 +862,6 @@ def update( This corresponds to the ``autoscaler_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. @@ -932,10 +913,8 @@ def update( # there are no flattened fields. if not isinstance(request, compute.UpdateRegionAutoscalerRequest): request = compute.UpdateRegionAutoscalerRequest(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: diff --git a/google/cloud/compute_v1/services/region_autoscalers/pagers.py b/google/cloud/compute_v1/services/region_autoscalers/pagers.py index 6b12d3baf..9eadae3fc 100644 --- a/google/cloud/compute_v1/services/region_autoscalers/pagers.py +++ b/google/cloud/compute_v1/services/region_autoscalers/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/region_autoscalers/transports/__init__.py b/google/cloud/compute_v1/services/region_autoscalers/transports/__init__.py index bd0acfb81..ed644943b 100644 --- a/google/cloud/compute_v1/services/region_autoscalers/transports/__init__.py +++ b/google/cloud/compute_v1/services/region_autoscalers/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/region_autoscalers/transports/base.py b/google/cloud/compute_v1/services/region_autoscalers/transports/base.py index c6ad6f112..ad3c9cc87 100644 --- a/google/cloud/compute_v1/services/region_autoscalers/transports/base.py +++ b/google/cloud/compute_v1/services/region_autoscalers/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class RegionAutoscalersTransport(abc.ABC): """Abstract transport class for RegionAutoscalers.""" @@ -44,21 +54,24 @@ class RegionAutoscalersTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -130,56 +190,54 @@ def _prep_wrapped_messages(self, client_info): @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteRegionAutoscalerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetRegionAutoscalerRequest], - typing.Union[compute.Autoscaler, typing.Awaitable[compute.Autoscaler]], + Union[compute.Autoscaler, Awaitable[compute.Autoscaler]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertRegionAutoscalerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListRegionAutoscalersRequest], - typing.Union[ - compute.RegionAutoscalerList, typing.Awaitable[compute.RegionAutoscalerList] - ], + Union[compute.RegionAutoscalerList, Awaitable[compute.RegionAutoscalerList]], ]: raise NotImplementedError() @property def patch( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchRegionAutoscalerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def update( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.UpdateRegionAutoscalerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/region_autoscalers/transports/rest.py b/google/cloud/compute_v1/services/region_autoscalers/transports/rest.py index f49e288e2..ac44641ef 100644 --- a/google/cloud/compute_v1/services/region_autoscalers/transports/rest.py +++ b/google/cloud/compute_v1/services/region_autoscalers/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 RegionAutoscalersTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def delete( Args: request (~.compute.DeleteRegionAutoscalerRequest): - The request object. - A request message for + The request object. A request message for RegionAutoscalers.Delete. See the method description for details. @@ -155,19 +154,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteRegionAutoscalerRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -185,8 +183,7 @@ def get( Args: request (~.compute.GetRegionAutoscalerRequest): - The request object. - A request message for + The request object. A request message for RegionAutoscalers.Get. See the method description for details. @@ -230,16 +227,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -259,8 +255,7 @@ def insert( Args: request (~.compute.InsertRegionAutoscalerRequest): - The request object. - A request message for + The request object. A request message for RegionAutoscalers.Insert. See the method description for details. @@ -315,15 +310,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertRegionAutoscalerRequest.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() if v - ] + 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 @@ -345,8 +339,7 @@ def list( Args: request (~.compute.ListRegionAutoscalersRequest): - The request object. - A request message for + The request object. A request message for RegionAutoscalers.List. See the method description for details. @@ -366,23 +359,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListRegionAutoscalersRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListRegionAutoscalersRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListRegionAutoscalersRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListRegionAutoscalersRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListRegionAutoscalersRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -402,8 +398,7 @@ def patch( Args: request (~.compute.PatchRegionAutoscalerRequest): - The request object. - A request message for + The request object. A request message for RegionAutoscalers.Patch. See the method description for details. @@ -458,16 +453,16 @@ def patch( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "autoscaler": request.autoscaler, - "requestId": request.request_id, - } + query_params = {} + if compute.PatchRegionAutoscalerRequest.autoscaler in request: + query_params["autoscaler"] = request.autoscaler + if compute.PatchRegionAutoscalerRequest.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() if v - ] + 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 @@ -489,8 +484,7 @@ def update( Args: request (~.compute.UpdateRegionAutoscalerRequest): - The request object. - A request message for + The request object. A request message for RegionAutoscalers.Update. See the method description for details. @@ -545,16 +539,16 @@ def update( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "autoscaler": request.autoscaler, - "requestId": request.request_id, - } + query_params = {} + if compute.UpdateRegionAutoscalerRequest.autoscaler in request: + query_params["autoscaler"] = request.autoscaler + if compute.UpdateRegionAutoscalerRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/region_backend_services/__init__.py b/google/cloud/compute_v1/services/region_backend_services/__init__.py index 2ee7fc824..a6bf888fc 100644 --- a/google/cloud/compute_v1/services/region_backend_services/__init__.py +++ b/google/cloud/compute_v1/services/region_backend_services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import RegionBackendServicesClient __all__ = ("RegionBackendServicesClient",) diff --git a/google/cloud/compute_v1/services/region_backend_services/client.py b/google/cloud/compute_v1/services/region_backend_services/client.py index 7f0d5ab14..2afe38b44 100644 --- a/google/cloud/compute_v1/services/region_backend_services/client.py +++ b/google/cloud/compute_v1/services/region_backend_services/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.region_backend_services import pagers from google.cloud.compute_v1.types import compute - from .transports.base import RegionBackendServicesTransport, DEFAULT_CLIENT_INFO from .transports.rest import RegionBackendServicesRestTransport @@ -217,7 +214,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, RegionBackendServicesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -365,7 +362,6 @@ def delete( This corresponds to the ``backend_service`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -417,10 +413,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteRegionBackendServiceRequest): request = compute.DeleteRegionBackendServiceRequest(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: @@ -476,7 +470,6 @@ def get( This corresponds to the ``backend_service`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -525,10 +518,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetRegionBackendServiceRequest): request = compute.GetRegionBackendServiceRequest(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: @@ -590,7 +581,6 @@ def get_health( This corresponds to the ``resource_group_reference_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. @@ -619,10 +609,8 @@ def get_health( # there are no flattened fields. if not isinstance(request, compute.GetHealthRegionBackendServiceRequest): request = compute.GetHealthRegionBackendServiceRequest(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: @@ -682,7 +670,6 @@ def insert( This corresponds to the ``backend_service_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. @@ -734,10 +721,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertRegionBackendServiceRequest): request = compute.InsertRegionBackendServiceRequest(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: @@ -786,7 +771,6 @@ def list( 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. @@ -818,10 +802,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListRegionBackendServicesRequest): request = compute.ListRegionBackendServicesRequest(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: @@ -890,7 +872,6 @@ def patch( This corresponds to the ``backend_service_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. @@ -944,10 +925,8 @@ def patch( # there are no flattened fields. if not isinstance(request, compute.PatchRegionBackendServiceRequest): request = compute.PatchRegionBackendServiceRequest(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: @@ -1012,7 +991,6 @@ def update( This corresponds to the ``backend_service_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. @@ -1066,10 +1044,8 @@ def update( # there are no flattened fields. if not isinstance(request, compute.UpdateRegionBackendServiceRequest): request = compute.UpdateRegionBackendServiceRequest(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: diff --git a/google/cloud/compute_v1/services/region_backend_services/pagers.py b/google/cloud/compute_v1/services/region_backend_services/pagers.py index df369b0ca..c26346ce6 100644 --- a/google/cloud/compute_v1/services/region_backend_services/pagers.py +++ b/google/cloud/compute_v1/services/region_backend_services/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/region_backend_services/transports/__init__.py b/google/cloud/compute_v1/services/region_backend_services/transports/__init__.py index e30c0e9e0..c9e22058c 100644 --- a/google/cloud/compute_v1/services/region_backend_services/transports/__init__.py +++ b/google/cloud/compute_v1/services/region_backend_services/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/region_backend_services/transports/base.py b/google/cloud/compute_v1/services/region_backend_services/transports/base.py index c48f6fbf8..108410d60 100644 --- a/google/cloud/compute_v1/services/region_backend_services/transports/base.py +++ b/google/cloud/compute_v1/services/region_backend_services/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class RegionBackendServicesTransport(abc.ABC): """Abstract transport class for RegionBackendServices.""" @@ -44,21 +54,24 @@ class RegionBackendServicesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -133,29 +193,29 @@ def _prep_wrapped_messages(self, client_info): @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteRegionBackendServiceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetRegionBackendServiceRequest], - typing.Union[compute.BackendService, typing.Awaitable[compute.BackendService]], + Union[compute.BackendService, Awaitable[compute.BackendService]], ]: raise NotImplementedError() @property def get_health( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetHealthRegionBackendServiceRequest], - typing.Union[ + Union[ compute.BackendServiceGroupHealth, - typing.Awaitable[compute.BackendServiceGroupHealth], + Awaitable[compute.BackendServiceGroupHealth], ], ]: raise NotImplementedError() @@ -163,38 +223,36 @@ def get_health( @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertRegionBackendServiceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListRegionBackendServicesRequest], - typing.Union[ - compute.BackendServiceList, typing.Awaitable[compute.BackendServiceList] - ], + Union[compute.BackendServiceList, Awaitable[compute.BackendServiceList]], ]: raise NotImplementedError() @property def patch( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchRegionBackendServiceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def update( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.UpdateRegionBackendServiceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/region_backend_services/transports/rest.py b/google/cloud/compute_v1/services/region_backend_services/transports/rest.py index 267627dbb..efc88e0ee 100644 --- a/google/cloud/compute_v1/services/region_backend_services/transports/rest.py +++ b/google/cloud/compute_v1/services/region_backend_services/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 RegionBackendServicesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def delete( Args: request (~.compute.DeleteRegionBackendServiceRequest): - The request object. - A request message for + The request object. A request message for RegionBackendServices.Delete. See the method description for details. @@ -155,19 +154,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteRegionBackendServiceRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -185,8 +183,7 @@ def get( Args: request (~.compute.GetRegionBackendServiceRequest): - The request object. - A request message for + The request object. A request message for RegionBackendServices.Get. See the method description for details. @@ -232,16 +229,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -261,8 +257,7 @@ def get_health( Args: request (~.compute.GetHealthRegionBackendServiceRequest): - The request object. - A request message for + The request object. A request message for RegionBackendServices.GetHealth. See the method description for details. @@ -293,12 +288,11 @@ def get_health( # 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() if v - ] + 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 @@ -322,8 +316,7 @@ def insert( Args: request (~.compute.InsertRegionBackendServiceRequest): - The request object. - A request message for + The request object. A request message for RegionBackendServices.Insert. See the method description for details. @@ -378,15 +371,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertRegionBackendServiceRequest.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() if v - ] + 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 @@ -408,8 +400,7 @@ def list( Args: request (~.compute.ListRegionBackendServicesRequest): - The request object. - A request message for + The request object. A request message for RegionBackendServices.List. See the method description for details. @@ -431,23 +422,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListRegionBackendServicesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListRegionBackendServicesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListRegionBackendServicesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListRegionBackendServicesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListRegionBackendServicesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -467,8 +461,7 @@ def patch( Args: request (~.compute.PatchRegionBackendServiceRequest): - The request object. - A request message for + The request object. A request message for RegionBackendServices.Patch. See the method description for details. @@ -526,15 +519,14 @@ def patch( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.PatchRegionBackendServiceRequest.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() if v - ] + 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 @@ -556,8 +548,7 @@ def update( Args: request (~.compute.UpdateRegionBackendServiceRequest): - The request object. - A request message for + The request object. A request message for RegionBackendServices.Update. See the method description for details. @@ -615,15 +606,14 @@ def update( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.UpdateRegionBackendServiceRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/region_commitments/__init__.py b/google/cloud/compute_v1/services/region_commitments/__init__.py index e80b2cb88..5471605f7 100644 --- a/google/cloud/compute_v1/services/region_commitments/__init__.py +++ b/google/cloud/compute_v1/services/region_commitments/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import RegionCommitmentsClient __all__ = ("RegionCommitmentsClient",) diff --git a/google/cloud/compute_v1/services/region_commitments/client.py b/google/cloud/compute_v1/services/region_commitments/client.py index 37cb7eaa2..723aa8140 100644 --- a/google/cloud/compute_v1/services/region_commitments/client.py +++ b/google/cloud/compute_v1/services/region_commitments/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.region_commitments import pagers from google.cloud.compute_v1.types import compute - from .transports.base import RegionCommitmentsTransport, DEFAULT_CLIENT_INFO from .transports.rest import RegionCommitmentsRestTransport @@ -217,7 +214,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, RegionCommitmentsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -348,7 +345,6 @@ def aggregated_list( 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. @@ -378,10 +374,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListRegionCommitmentsRequest): request = compute.AggregatedListRegionCommitmentsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -436,7 +430,6 @@ def get( This corresponds to the ``commitment`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -472,10 +465,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetRegionCommitmentRequest): request = compute.GetRegionCommitmentRequest(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: @@ -527,7 +518,6 @@ def insert( This corresponds to the ``commitment_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. @@ -579,10 +569,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertRegionCommitmentRequest): request = compute.InsertRegionCommitmentRequest(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: @@ -628,7 +616,6 @@ def list( 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. @@ -660,10 +647,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListRegionCommitmentsRequest): request = compute.ListRegionCommitmentsRequest(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: diff --git a/google/cloud/compute_v1/services/region_commitments/pagers.py b/google/cloud/compute_v1/services/region_commitments/pagers.py index 54dc0eb1c..b33d259fe 100644 --- a/google/cloud/compute_v1/services/region_commitments/pagers.py +++ b/google/cloud/compute_v1/services/region_commitments/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/region_commitments/transports/__init__.py b/google/cloud/compute_v1/services/region_commitments/transports/__init__.py index 1b3058b6c..604f9c686 100644 --- a/google/cloud/compute_v1/services/region_commitments/transports/__init__.py +++ b/google/cloud/compute_v1/services/region_commitments/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/region_commitments/transports/base.py b/google/cloud/compute_v1/services/region_commitments/transports/base.py index 95d578a50..af6ec798e 100644 --- a/google/cloud/compute_v1/services/region_commitments/transports/base.py +++ b/google/cloud/compute_v1/services/region_commitments/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class RegionCommitmentsTransport(abc.ABC): """Abstract transport class for RegionCommitments.""" @@ -44,21 +54,24 @@ class RegionCommitmentsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -124,11 +184,11 @@ def _prep_wrapped_messages(self, client_info): @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListRegionCommitmentsRequest], - typing.Union[ + Union[ compute.CommitmentAggregatedList, - typing.Awaitable[compute.CommitmentAggregatedList], + Awaitable[compute.CommitmentAggregatedList], ], ]: raise NotImplementedError() @@ -136,27 +196,27 @@ def aggregated_list( @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetRegionCommitmentRequest], - typing.Union[compute.Commitment, typing.Awaitable[compute.Commitment]], + Union[compute.Commitment, Awaitable[compute.Commitment]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertRegionCommitmentRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListRegionCommitmentsRequest], - typing.Union[compute.CommitmentList, typing.Awaitable[compute.CommitmentList]], + Union[compute.CommitmentList, Awaitable[compute.CommitmentList]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/region_commitments/transports/rest.py b/google/cloud/compute_v1/services/region_commitments/transports/rest.py index 00649a860..2e10851f4 100644 --- a/google/cloud/compute_v1/services/region_commitments/transports/rest.py +++ b/google/cloud/compute_v1/services/region_commitments/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 RegionCommitmentsTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListRegionCommitmentsRequest): - The request object. - A request message for + The request object. A request message for RegionCommitments.AggregatedList. See the method description for details. @@ -124,24 +123,31 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListRegionCommitmentsRequest.filter in request: + query_params["filter"] = request.filter + if compute.AggregatedListRegionCommitmentsRequest.include_all_scopes in request: + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListRegionCommitmentsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListRegionCommitmentsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListRegionCommitmentsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if ( + compute.AggregatedListRegionCommitmentsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -161,8 +167,7 @@ def get( Args: request (~.compute.GetRegionCommitmentRequest): - The request object. - A request message for + The request object. A request message for RegionCommitments.Get. See the method description for details. @@ -195,16 +200,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -224,8 +228,7 @@ def insert( Args: request (~.compute.InsertRegionCommitmentRequest): - The request object. - A request message for + The request object. A request message for RegionCommitments.Insert. See the method description for details. @@ -280,15 +283,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertRegionCommitmentRequest.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() if v - ] + 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 @@ -310,8 +312,7 @@ def list( Args: request (~.compute.ListRegionCommitmentsRequest): - The request object. - A request message for + The request object. A request message for RegionCommitments.List. See the method description for details. @@ -333,23 +334,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListRegionCommitmentsRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListRegionCommitmentsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListRegionCommitmentsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListRegionCommitmentsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListRegionCommitmentsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() diff --git a/google/cloud/compute_v1/services/region_disk_types/__init__.py b/google/cloud/compute_v1/services/region_disk_types/__init__.py index 4f6e2c2b8..d06de92d8 100644 --- a/google/cloud/compute_v1/services/region_disk_types/__init__.py +++ b/google/cloud/compute_v1/services/region_disk_types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import RegionDiskTypesClient __all__ = ("RegionDiskTypesClient",) diff --git a/google/cloud/compute_v1/services/region_disk_types/client.py b/google/cloud/compute_v1/services/region_disk_types/client.py index 101d8eada..5e8ca89b2 100644 --- a/google/cloud/compute_v1/services/region_disk_types/client.py +++ b/google/cloud/compute_v1/services/region_disk_types/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.region_disk_types import pagers from google.cloud.compute_v1.types import compute - from .transports.base import RegionDiskTypesTransport, DEFAULT_CLIENT_INFO from .transports.rest import RegionDiskTypesRestTransport @@ -215,7 +212,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, RegionDiskTypesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -361,7 +358,6 @@ def get( This corresponds to the ``disk_type`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -409,10 +405,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetRegionDiskTypeRequest): request = compute.GetRegionDiskTypeRequest(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: @@ -460,7 +454,6 @@ def list( 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. @@ -490,10 +483,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListRegionDiskTypesRequest): request = compute.ListRegionDiskTypesRequest(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: diff --git a/google/cloud/compute_v1/services/region_disk_types/pagers.py b/google/cloud/compute_v1/services/region_disk_types/pagers.py index a0ca2f635..3a283a8ac 100644 --- a/google/cloud/compute_v1/services/region_disk_types/pagers.py +++ b/google/cloud/compute_v1/services/region_disk_types/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/region_disk_types/transports/__init__.py b/google/cloud/compute_v1/services/region_disk_types/transports/__init__.py index 872c0e693..900a974f3 100644 --- a/google/cloud/compute_v1/services/region_disk_types/transports/__init__.py +++ b/google/cloud/compute_v1/services/region_disk_types/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/region_disk_types/transports/base.py b/google/cloud/compute_v1/services/region_disk_types/transports/base.py index b14495a00..830873fba 100644 --- a/google/cloud/compute_v1/services/region_disk_types/transports/base.py +++ b/google/cloud/compute_v1/services/region_disk_types/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class RegionDiskTypesTransport(abc.ABC): """Abstract transport class for RegionDiskTypes.""" @@ -45,21 +55,24 @@ class RegionDiskTypesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -68,13 +81,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -82,28 +95,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -119,20 +179,18 @@ def _prep_wrapped_messages(self, client_info): @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetRegionDiskTypeRequest], - typing.Union[compute.DiskType, typing.Awaitable[compute.DiskType]], + Union[compute.DiskType, Awaitable[compute.DiskType]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListRegionDiskTypesRequest], - typing.Union[ - compute.RegionDiskTypeList, typing.Awaitable[compute.RegionDiskTypeList] - ], + Union[compute.RegionDiskTypeList, Awaitable[compute.RegionDiskTypeList]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/region_disk_types/transports/rest.py b/google/cloud/compute_v1/services/region_disk_types/transports/rest.py index 1c49dc89a..02ef58e2b 100644 --- a/google/cloud/compute_v1/services/region_disk_types/transports/rest.py +++ b/google/cloud/compute_v1/services/region_disk_types/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 RegionDiskTypesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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 get( self, @@ -103,8 +103,7 @@ def get( Args: request (~.compute.GetRegionDiskTypeRequest): - The request object. - A request message for + The request object. A request message for RegionDiskTypes.Get. See the method description for details. @@ -148,16 +147,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -175,8 +173,7 @@ def list( Args: request (~.compute.ListRegionDiskTypesRequest): - The request object. - A request message for + The request object. A request message for RegionDiskTypes.List. See the method description for details. @@ -196,23 +193,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListRegionDiskTypesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListRegionDiskTypesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListRegionDiskTypesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListRegionDiskTypesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListRegionDiskTypesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() diff --git a/google/cloud/compute_v1/services/region_disks/__init__.py b/google/cloud/compute_v1/services/region_disks/__init__.py index e06151303..f86758f1e 100644 --- a/google/cloud/compute_v1/services/region_disks/__init__.py +++ b/google/cloud/compute_v1/services/region_disks/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import RegionDisksClient __all__ = ("RegionDisksClient",) diff --git a/google/cloud/compute_v1/services/region_disks/client.py b/google/cloud/compute_v1/services/region_disks/client.py index c75fe341e..719a56747 100644 --- a/google/cloud/compute_v1/services/region_disks/client.py +++ b/google/cloud/compute_v1/services/region_disks/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.region_disks import pagers from google.cloud.compute_v1.types import compute - from .transports.base import RegionDisksTransport, DEFAULT_CLIENT_INFO from .transports.rest import RegionDisksRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, RegionDisksTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -366,7 +363,6 @@ def add_resource_policies( This corresponds to the ``region_disks_add_resource_policies_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. @@ -420,10 +416,8 @@ def add_resource_policies( # there are no flattened fields. if not isinstance(request, compute.AddResourcePoliciesRegionDiskRequest): request = compute.AddResourcePoliciesRegionDiskRequest(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: @@ -486,7 +480,6 @@ def create_snapshot( This corresponds to the ``snapshot_resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -538,10 +531,8 @@ def create_snapshot( # there are no flattened fields. if not isinstance(request, compute.CreateSnapshotRegionDiskRequest): request = compute.CreateSnapshotRegionDiskRequest(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: @@ -600,7 +591,6 @@ def delete( This corresponds to the ``disk`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -652,10 +642,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteRegionDiskRequest): request = compute.DeleteRegionDiskRequest(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: @@ -707,7 +695,6 @@ def get( This corresponds to the ``disk`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -756,10 +743,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetRegionDiskRequest): request = compute.GetRegionDiskRequest(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: @@ -815,7 +800,6 @@ def get_iam_policy( 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. @@ -893,10 +877,8 @@ def get_iam_policy( # there are no flattened fields. if not isinstance(request, compute.GetIamPolicyRegionDiskRequest): request = compute.GetIamPolicyRegionDiskRequest(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: @@ -948,7 +930,6 @@ def insert( This corresponds to the ``disk_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. @@ -1000,10 +981,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertRegionDiskRequest): request = compute.InsertRegionDiskRequest(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: @@ -1049,7 +1028,6 @@ def list( 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. @@ -1080,10 +1058,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListRegionDisksRequest): request = compute.ListRegionDisksRequest(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: @@ -1146,7 +1122,6 @@ def remove_resource_policies( This corresponds to the ``region_disks_remove_resource_policies_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. @@ -1205,10 +1180,8 @@ def remove_resource_policies( # there are no flattened fields. if not isinstance(request, compute.RemoveResourcePoliciesRegionDiskRequest): request = compute.RemoveResourcePoliciesRegionDiskRequest(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: @@ -1269,7 +1242,6 @@ def resize( This corresponds to the ``region_disks_resize_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. @@ -1323,10 +1295,8 @@ def resize( # there are no flattened fields. if not isinstance(request, compute.ResizeRegionDiskRequest): request = compute.ResizeRegionDiskRequest(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: @@ -1392,7 +1362,6 @@ def set_iam_policy( This corresponds to the ``region_set_policy_request_resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1472,10 +1441,8 @@ def set_iam_policy( # there are no flattened fields. if not isinstance(request, compute.SetIamPolicyRegionDiskRequest): request = compute.SetIamPolicyRegionDiskRequest(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: @@ -1538,7 +1505,6 @@ def set_labels( 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. @@ -1592,10 +1558,8 @@ def set_labels( # there are no flattened fields. if not isinstance(request, compute.SetLabelsRegionDiskRequest): request = compute.SetLabelsRegionDiskRequest(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: @@ -1661,7 +1625,6 @@ def test_iam_permissions( 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. @@ -1690,10 +1653,8 @@ def test_iam_permissions( # there are no flattened fields. if not isinstance(request, compute.TestIamPermissionsRegionDiskRequest): request = compute.TestIamPermissionsRegionDiskRequest(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: diff --git a/google/cloud/compute_v1/services/region_disks/pagers.py b/google/cloud/compute_v1/services/region_disks/pagers.py index e370537fa..1b0fa465a 100644 --- a/google/cloud/compute_v1/services/region_disks/pagers.py +++ b/google/cloud/compute_v1/services/region_disks/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/region_disks/transports/__init__.py b/google/cloud/compute_v1/services/region_disks/transports/__init__.py index 96fac69a9..bc5c5bfa4 100644 --- a/google/cloud/compute_v1/services/region_disks/transports/__init__.py +++ b/google/cloud/compute_v1/services/region_disks/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/region_disks/transports/base.py b/google/cloud/compute_v1/services/region_disks/transports/base.py index 6170024b9..3e504f738 100644 --- a/google/cloud/compute_v1/services/region_disks/transports/base.py +++ b/google/cloud/compute_v1/services/region_disks/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class RegionDisksTransport(abc.ABC): """Abstract transport class for RegionDisks.""" @@ -44,21 +54,24 @@ class RegionDisksTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -154,110 +214,108 @@ def _prep_wrapped_messages(self, client_info): @property def add_resource_policies( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AddResourcePoliciesRegionDiskRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def create_snapshot( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.CreateSnapshotRegionDiskRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteRegionDiskRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ - [compute.GetRegionDiskRequest], - typing.Union[compute.Disk, typing.Awaitable[compute.Disk]], + ) -> Callable[ + [compute.GetRegionDiskRequest], Union[compute.Disk, Awaitable[compute.Disk]] ]: raise NotImplementedError() @property def get_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetIamPolicyRegionDiskRequest], - typing.Union[compute.Policy, typing.Awaitable[compute.Policy]], + Union[compute.Policy, Awaitable[compute.Policy]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertRegionDiskRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListRegionDisksRequest], - typing.Union[compute.DiskList, typing.Awaitable[compute.DiskList]], + Union[compute.DiskList, Awaitable[compute.DiskList]], ]: raise NotImplementedError() @property def remove_resource_policies( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.RemoveResourcePoliciesRegionDiskRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def resize( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ResizeRegionDiskRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetIamPolicyRegionDiskRequest], - typing.Union[compute.Policy, typing.Awaitable[compute.Policy]], + Union[compute.Policy, Awaitable[compute.Policy]], ]: raise NotImplementedError() @property def set_labels( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetLabelsRegionDiskRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.TestIamPermissionsRegionDiskRequest], - typing.Union[ - compute.TestPermissionsResponse, - typing.Awaitable[compute.TestPermissionsResponse], + Union[ + compute.TestPermissionsResponse, Awaitable[compute.TestPermissionsResponse] ], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/region_disks/transports/rest.py b/google/cloud/compute_v1/services/region_disks/transports/rest.py index 297326dd4..d6bc0a83f 100644 --- a/google/cloud/compute_v1/services/region_disks/transports/rest.py +++ b/google/cloud/compute_v1/services/region_disks/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 RegionDisksTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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_resource_policies( self, @@ -103,8 +103,7 @@ def add_resource_policies( Args: request (~.compute.AddResourcePoliciesRegionDiskRequest): - The request object. - A request message for + The request object. A request message for RegionDisks.AddResourcePolicies. See the method description for details. @@ -162,15 +161,14 @@ def add_resource_policies( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.AddResourcePoliciesRegionDiskRequest.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() if v - ] + 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 @@ -192,8 +190,7 @@ def create_snapshot( Args: request (~.compute.CreateSnapshotRegionDiskRequest): - The request object. - A request message for + The request object. A request message for RegionDisks.CreateSnapshot. See the method description for details. @@ -251,15 +248,14 @@ def create_snapshot( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.CreateSnapshotRegionDiskRequest.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() if v - ] + 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 @@ -281,8 +277,7 @@ def delete( Args: request (~.compute.DeleteRegionDiskRequest): - The request object. - A request message for + The request object. A request message for RegionDisks.Delete. See the method description for details. @@ -333,19 +328,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteRegionDiskRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -363,8 +357,7 @@ def get( Args: request (~.compute.GetRegionDiskRequest): - The request object. - A request message for + The request object. A request message for RegionDisks.Get. See the method description for details. @@ -408,16 +401,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -435,8 +427,7 @@ def get_iam_policy( Args: request (~.compute.GetIamPolicyRegionDiskRequest): - The request object. - A request message for + The request object. A request message for RegionDisks.GetIamPolicy. See the method description for details. @@ -509,19 +500,23 @@ def get_iam_policy( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "optionsRequestedPolicyVersion": request.options_requested_policy_version, - } + query_params = {} + if ( + compute.GetIamPolicyRegionDiskRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -539,8 +534,7 @@ def insert( Args: request (~.compute.InsertRegionDiskRequest): - The request object. - A request message for + The request object. A request message for RegionDisks.Insert. See the method description for details. @@ -595,16 +589,16 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - "sourceImage": request.source_image, - } + query_params = {} + if compute.InsertRegionDiskRequest.request_id in request: + query_params["requestId"] = request.request_id + if compute.InsertRegionDiskRequest.source_image in request: + query_params["sourceImage"] = request.source_image + # 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() if v - ] + 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 @@ -626,8 +620,7 @@ def list( Args: request (~.compute.ListRegionDisksRequest): - The request object. - A request message for + The request object. A request message for RegionDisks.List. See the method description for details. @@ -647,23 +640,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListRegionDisksRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListRegionDisksRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListRegionDisksRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListRegionDisksRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListRegionDisksRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -681,8 +677,7 @@ def remove_resource_policies( Args: request (~.compute.RemoveResourcePoliciesRegionDiskRequest): - The request object. - A request message for + The request object. A request message for RegionDisks.RemoveResourcePolicies. See the method description for details. @@ -740,15 +735,14 @@ def remove_resource_policies( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.RemoveResourcePoliciesRegionDiskRequest.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() if v - ] + 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 @@ -770,8 +764,7 @@ def resize( Args: request (~.compute.ResizeRegionDiskRequest): - The request object. - A request message for + The request object. A request message for RegionDisks.Resize. See the method description for details. @@ -829,15 +822,14 @@ def resize( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.ResizeRegionDiskRequest.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() if v - ] + 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 @@ -859,8 +851,7 @@ def set_iam_policy( Args: request (~.compute.SetIamPolicyRegionDiskRequest): - The request object. - A request message for + The request object. A request message for RegionDisks.SetIamPolicy. See the method description for details. @@ -941,12 +932,11 @@ def set_iam_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() if v - ] + 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 @@ -968,8 +958,7 @@ def set_labels( Args: request (~.compute.SetLabelsRegionDiskRequest): - The request object. - A request message for + The request object. A request message for RegionDisks.SetLabels. See the method description for details. @@ -1027,15 +1016,14 @@ def set_labels( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetLabelsRegionDiskRequest.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() if v - ] + 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 @@ -1057,8 +1045,7 @@ def test_iam_permissions( Args: request (~.compute.TestIamPermissionsRegionDiskRequest): - The request object. - A request message for + The request object. A request message for RegionDisks.TestIamPermissions. See the method description for details. @@ -1089,12 +1076,11 @@ def test_iam_permissions( # 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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/region_health_check_services/__init__.py b/google/cloud/compute_v1/services/region_health_check_services/__init__.py index 9c8502fce..b1521af88 100644 --- a/google/cloud/compute_v1/services/region_health_check_services/__init__.py +++ b/google/cloud/compute_v1/services/region_health_check_services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import RegionHealthCheckServicesClient __all__ = ("RegionHealthCheckServicesClient",) diff --git a/google/cloud/compute_v1/services/region_health_check_services/client.py b/google/cloud/compute_v1/services/region_health_check_services/client.py index 28a58ad0a..b5b472678 100644 --- a/google/cloud/compute_v1/services/region_health_check_services/client.py +++ b/google/cloud/compute_v1/services/region_health_check_services/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.region_health_check_services import pagers from google.cloud.compute_v1.types import compute - from .transports.base import RegionHealthCheckServicesTransport, DEFAULT_CLIENT_INFO from .transports.rest import RegionHealthCheckServicesRestTransport @@ -217,7 +214,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, RegionHealthCheckServicesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -365,7 +362,6 @@ def delete( This corresponds to the ``health_check_service`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -417,10 +413,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteRegionHealthCheckServiceRequest): request = compute.DeleteRegionHealthCheckServiceRequest(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: @@ -477,7 +471,6 @@ def get( This corresponds to the ``health_check_service`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -508,10 +501,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetRegionHealthCheckServiceRequest): request = compute.GetRegionHealthCheckServiceRequest(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: @@ -566,7 +557,6 @@ def insert( This corresponds to the ``health_check_service_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. @@ -618,10 +608,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertRegionHealthCheckServiceRequest): request = compute.InsertRegionHealthCheckServiceRequest(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: @@ -670,7 +658,6 @@ def list( 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. @@ -700,10 +687,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListRegionHealthCheckServicesRequest): request = compute.ListRegionHealthCheckServicesRequest(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: @@ -772,7 +757,6 @@ def patch( This corresponds to the ``health_check_service_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. @@ -826,10 +810,8 @@ def patch( # there are no flattened fields. if not isinstance(request, compute.PatchRegionHealthCheckServiceRequest): request = compute.PatchRegionHealthCheckServiceRequest(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: diff --git a/google/cloud/compute_v1/services/region_health_check_services/pagers.py b/google/cloud/compute_v1/services/region_health_check_services/pagers.py index b0fd2a06b..b01067872 100644 --- a/google/cloud/compute_v1/services/region_health_check_services/pagers.py +++ b/google/cloud/compute_v1/services/region_health_check_services/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/region_health_check_services/transports/__init__.py b/google/cloud/compute_v1/services/region_health_check_services/transports/__init__.py index fb553ebd6..4e08dafdb 100644 --- a/google/cloud/compute_v1/services/region_health_check_services/transports/__init__.py +++ b/google/cloud/compute_v1/services/region_health_check_services/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/region_health_check_services/transports/base.py b/google/cloud/compute_v1/services/region_health_check_services/transports/base.py index e28ac7eea..3e5810421 100644 --- a/google/cloud/compute_v1/services/region_health_check_services/transports/base.py +++ b/google/cloud/compute_v1/services/region_health_check_services/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class RegionHealthCheckServicesTransport(abc.ABC): """Abstract transport class for RegionHealthCheckServices.""" @@ -44,21 +54,24 @@ class RegionHealthCheckServicesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -127,40 +187,37 @@ def _prep_wrapped_messages(self, client_info): @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteRegionHealthCheckServiceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetRegionHealthCheckServiceRequest], - typing.Union[ - compute.HealthCheckService, typing.Awaitable[compute.HealthCheckService] - ], + Union[compute.HealthCheckService, Awaitable[compute.HealthCheckService]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertRegionHealthCheckServiceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListRegionHealthCheckServicesRequest], - typing.Union[ - compute.HealthCheckServicesList, - typing.Awaitable[compute.HealthCheckServicesList], + Union[ + compute.HealthCheckServicesList, Awaitable[compute.HealthCheckServicesList] ], ]: raise NotImplementedError() @@ -168,9 +225,9 @@ def list( @property def patch( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchRegionHealthCheckServiceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/region_health_check_services/transports/rest.py b/google/cloud/compute_v1/services/region_health_check_services/transports/rest.py index e81624516..dbeeb2446 100644 --- a/google/cloud/compute_v1/services/region_health_check_services/transports/rest.py +++ b/google/cloud/compute_v1/services/region_health_check_services/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 RegionHealthCheckServicesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def delete( Args: request (~.compute.DeleteRegionHealthCheckServiceRequest): - The request object. - A request message for + The request object. A request message for RegionHealthCheckServices.Delete. See the method description for details. @@ -155,19 +154,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteRegionHealthCheckServiceRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -185,8 +183,7 @@ def get( Args: request (~.compute.GetRegionHealthCheckServiceRequest): - The request object. - A request message for + The request object. A request message for RegionHealthCheckServices.Get. See the method description for details. @@ -214,16 +211,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -243,8 +239,7 @@ def insert( Args: request (~.compute.InsertRegionHealthCheckServiceRequest): - The request object. - A request message for + The request object. A request message for RegionHealthCheckServices.Insert. See the method description for details. @@ -299,15 +294,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertRegionHealthCheckServiceRequest.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() if v - ] + 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 @@ -329,8 +323,7 @@ def list( Args: request (~.compute.ListRegionHealthCheckServicesRequest): - The request object. - A request message for + The request object. A request message for RegionHealthCheckServices.List. See the method description for details. @@ -350,23 +343,29 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListRegionHealthCheckServicesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListRegionHealthCheckServicesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListRegionHealthCheckServicesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListRegionHealthCheckServicesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if ( + compute.ListRegionHealthCheckServicesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -386,8 +385,7 @@ def patch( Args: request (~.compute.PatchRegionHealthCheckServiceRequest): - The request object. - A request message for + The request object. A request message for RegionHealthCheckServices.Patch. See the method description for details. @@ -445,15 +443,14 @@ def patch( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.PatchRegionHealthCheckServiceRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/region_health_checks/__init__.py b/google/cloud/compute_v1/services/region_health_checks/__init__.py index a70bf2502..d9214368e 100644 --- a/google/cloud/compute_v1/services/region_health_checks/__init__.py +++ b/google/cloud/compute_v1/services/region_health_checks/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import RegionHealthChecksClient __all__ = ("RegionHealthChecksClient",) diff --git a/google/cloud/compute_v1/services/region_health_checks/client.py b/google/cloud/compute_v1/services/region_health_checks/client.py index d0a49b903..d51e9dc99 100644 --- a/google/cloud/compute_v1/services/region_health_checks/client.py +++ b/google/cloud/compute_v1/services/region_health_checks/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.region_health_checks import pagers from google.cloud.compute_v1.types import compute - from .transports.base import RegionHealthChecksTransport, DEFAULT_CLIENT_INFO from .transports.rest import RegionHealthChecksRestTransport @@ -217,7 +214,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, RegionHealthChecksTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -364,7 +361,6 @@ def delete( This corresponds to the ``health_check`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -416,10 +412,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteRegionHealthCheckRequest): request = compute.DeleteRegionHealthCheckRequest(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: @@ -476,7 +470,6 @@ def get( This corresponds to the ``health_check`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -531,10 +524,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetRegionHealthCheckRequest): request = compute.GetRegionHealthCheckRequest(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: @@ -588,7 +579,6 @@ def insert( This corresponds to the ``health_check_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. @@ -640,10 +630,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertRegionHealthCheckRequest): request = compute.InsertRegionHealthCheckRequest(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: @@ -691,7 +679,6 @@ def list( 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. @@ -723,10 +710,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListRegionHealthChecksRequest): request = compute.ListRegionHealthChecksRequest(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: @@ -794,7 +779,6 @@ def patch( This corresponds to the ``health_check_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. @@ -848,10 +832,8 @@ def patch( # there are no flattened fields. if not isinstance(request, compute.PatchRegionHealthCheckRequest): request = compute.PatchRegionHealthCheckRequest(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: @@ -915,7 +897,6 @@ def update( This corresponds to the ``health_check_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. @@ -969,10 +950,8 @@ def update( # there are no flattened fields. if not isinstance(request, compute.UpdateRegionHealthCheckRequest): request = compute.UpdateRegionHealthCheckRequest(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: diff --git a/google/cloud/compute_v1/services/region_health_checks/pagers.py b/google/cloud/compute_v1/services/region_health_checks/pagers.py index 8e65a25b1..a11b8fc26 100644 --- a/google/cloud/compute_v1/services/region_health_checks/pagers.py +++ b/google/cloud/compute_v1/services/region_health_checks/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/region_health_checks/transports/__init__.py b/google/cloud/compute_v1/services/region_health_checks/transports/__init__.py index 4aebeccbc..693981b34 100644 --- a/google/cloud/compute_v1/services/region_health_checks/transports/__init__.py +++ b/google/cloud/compute_v1/services/region_health_checks/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/region_health_checks/transports/base.py b/google/cloud/compute_v1/services/region_health_checks/transports/base.py index cc72d550d..54928faea 100644 --- a/google/cloud/compute_v1/services/region_health_checks/transports/base.py +++ b/google/cloud/compute_v1/services/region_health_checks/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class RegionHealthChecksTransport(abc.ABC): """Abstract transport class for RegionHealthChecks.""" @@ -44,21 +54,24 @@ class RegionHealthChecksTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -130,56 +190,54 @@ def _prep_wrapped_messages(self, client_info): @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteRegionHealthCheckRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetRegionHealthCheckRequest], - typing.Union[compute.HealthCheck, typing.Awaitable[compute.HealthCheck]], + Union[compute.HealthCheck, Awaitable[compute.HealthCheck]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertRegionHealthCheckRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListRegionHealthChecksRequest], - typing.Union[ - compute.HealthCheckList, typing.Awaitable[compute.HealthCheckList] - ], + Union[compute.HealthCheckList, Awaitable[compute.HealthCheckList]], ]: raise NotImplementedError() @property def patch( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchRegionHealthCheckRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def update( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.UpdateRegionHealthCheckRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/region_health_checks/transports/rest.py b/google/cloud/compute_v1/services/region_health_checks/transports/rest.py index 57a27f08c..d30e690fc 100644 --- a/google/cloud/compute_v1/services/region_health_checks/transports/rest.py +++ b/google/cloud/compute_v1/services/region_health_checks/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 RegionHealthChecksTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def delete( Args: request (~.compute.DeleteRegionHealthCheckRequest): - The request object. - A request message for + The request object. A request message for RegionHealthChecks.Delete. See the method description for details. @@ -155,19 +154,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteRegionHealthCheckRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -185,8 +183,7 @@ def get( Args: request (~.compute.GetRegionHealthCheckRequest): - The request object. - A request message for + The request object. A request message for RegionHealthChecks.Get. See the method description for details. @@ -238,16 +235,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -267,8 +263,7 @@ def insert( Args: request (~.compute.InsertRegionHealthCheckRequest): - The request object. - A request message for + The request object. A request message for RegionHealthChecks.Insert. See the method description for details. @@ -323,15 +318,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertRegionHealthCheckRequest.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() if v - ] + 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 @@ -353,8 +347,7 @@ def list( Args: request (~.compute.ListRegionHealthChecksRequest): - The request object. - A request message for + The request object. A request message for RegionHealthChecks.List. See the method description for details. @@ -376,23 +369,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListRegionHealthChecksRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListRegionHealthChecksRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListRegionHealthChecksRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListRegionHealthChecksRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListRegionHealthChecksRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -412,8 +408,7 @@ def patch( Args: request (~.compute.PatchRegionHealthCheckRequest): - The request object. - A request message for + The request object. A request message for RegionHealthChecks.Patch. See the method description for details. @@ -471,15 +466,14 @@ def patch( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.PatchRegionHealthCheckRequest.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() if v - ] + 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 @@ -501,8 +495,7 @@ def update( Args: request (~.compute.UpdateRegionHealthCheckRequest): - The request object. - A request message for + The request object. A request message for RegionHealthChecks.Update. See the method description for details. @@ -560,15 +553,14 @@ def update( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.UpdateRegionHealthCheckRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/region_instance_group_managers/__init__.py b/google/cloud/compute_v1/services/region_instance_group_managers/__init__.py index fdc08dadd..e2c1a861b 100644 --- a/google/cloud/compute_v1/services/region_instance_group_managers/__init__.py +++ b/google/cloud/compute_v1/services/region_instance_group_managers/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import RegionInstanceGroupManagersClient __all__ = ("RegionInstanceGroupManagersClient",) diff --git a/google/cloud/compute_v1/services/region_instance_group_managers/client.py b/google/cloud/compute_v1/services/region_instance_group_managers/client.py index 6e97236e4..33a67273c 100644 --- a/google/cloud/compute_v1/services/region_instance_group_managers/client.py +++ b/google/cloud/compute_v1/services/region_instance_group_managers/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.region_instance_group_managers import pagers from google.cloud.compute_v1.types import compute - from .transports.base import RegionInstanceGroupManagersTransport, DEFAULT_CLIENT_INFO from .transports.rest import RegionInstanceGroupManagersRestTransport @@ -219,7 +216,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, RegionInstanceGroupManagersTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -386,7 +383,6 @@ def abandon_instances( This corresponds to the ``region_instance_group_managers_abandon_instances_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. @@ -447,10 +443,8 @@ def abandon_instances( request, compute.AbandonInstancesRegionInstanceGroupManagerRequest ): request = compute.AbandonInstancesRegionInstanceGroupManagerRequest(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: @@ -519,7 +513,6 @@ def apply_updates_to_instances( This corresponds to the ``region_instance_group_managers_apply_updates_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. @@ -582,10 +575,8 @@ def apply_updates_to_instances( request = compute.ApplyUpdatesToInstancesRegionInstanceGroupManagerRequest( 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: @@ -663,7 +654,6 @@ def create_instances( This corresponds to the ``region_instance_group_managers_create_instances_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. @@ -724,10 +714,8 @@ def create_instances( request, compute.CreateInstancesRegionInstanceGroupManagerRequest ): request = compute.CreateInstancesRegionInstanceGroupManagerRequest(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: @@ -790,7 +778,6 @@ def delete( This corresponds to the ``instance_group_manager`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -842,10 +829,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteRegionInstanceGroupManagerRequest): request = compute.DeleteRegionInstanceGroupManagerRequest(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: @@ -919,7 +904,6 @@ def delete_instances( This corresponds to the ``region_instance_group_managers_delete_instances_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. @@ -980,10 +964,8 @@ def delete_instances( request, compute.DeleteInstancesRegionInstanceGroupManagerRequest ): request = compute.DeleteInstancesRegionInstanceGroupManagerRequest(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: @@ -1052,7 +1034,6 @@ def delete_per_instance_configs( This corresponds to the ``region_instance_group_manager_delete_instance_config_req_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. @@ -1115,10 +1096,8 @@ def delete_per_instance_configs( request = compute.DeletePerInstanceConfigsRegionInstanceGroupManagerRequest( 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: @@ -1183,7 +1162,6 @@ def get( This corresponds to the ``instance_group_manager`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1224,10 +1202,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetRegionInstanceGroupManagerRequest): request = compute.GetRegionInstanceGroupManagerRequest(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: @@ -1289,7 +1265,6 @@ def insert( This corresponds to the ``instance_group_manager_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. @@ -1341,10 +1316,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertRegionInstanceGroupManagerRequest): request = compute.InsertRegionInstanceGroupManagerRequest(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: @@ -1394,7 +1367,6 @@ def list( 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. @@ -1426,10 +1398,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListRegionInstanceGroupManagersRequest): request = compute.ListRegionInstanceGroupManagersRequest(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: @@ -1492,7 +1462,6 @@ def list_errors( This corresponds to the ``instance_group_manager`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1524,10 +1493,8 @@ def list_errors( request, compute.ListErrorsRegionInstanceGroupManagersRequest ): request = compute.ListErrorsRegionInstanceGroupManagersRequest(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: @@ -1592,7 +1559,6 @@ def list_managed_instances( This corresponds to the ``instance_group_manager`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1626,10 +1592,8 @@ def list_managed_instances( request = compute.ListManagedInstancesRegionInstanceGroupManagersRequest( 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: @@ -1692,7 +1656,6 @@ def list_per_instance_configs( This corresponds to the ``instance_group_manager`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1726,10 +1689,8 @@ def list_per_instance_configs( request = compute.ListPerInstanceConfigsRegionInstanceGroupManagersRequest( 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: @@ -1806,7 +1767,6 @@ def patch( This corresponds to the ``instance_group_manager_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. @@ -1860,10 +1820,8 @@ def patch( # there are no flattened fields. if not isinstance(request, compute.PatchRegionInstanceGroupManagerRequest): request = compute.PatchRegionInstanceGroupManagerRequest(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: @@ -1931,7 +1889,6 @@ def patch_per_instance_configs( This corresponds to the ``region_instance_group_manager_patch_instance_config_req_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. @@ -1994,10 +1951,8 @@ def patch_per_instance_configs( request = compute.PatchPerInstanceConfigsRegionInstanceGroupManagerRequest( 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: @@ -2078,7 +2033,6 @@ def recreate_instances( This corresponds to the ``region_instance_group_managers_recreate_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. @@ -2141,10 +2095,8 @@ def recreate_instances( request = compute.RecreateInstancesRegionInstanceGroupManagerRequest( 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: @@ -2221,7 +2173,6 @@ def resize( This corresponds to the ``size`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2273,10 +2224,8 @@ def resize( # there are no flattened fields. if not isinstance(request, compute.ResizeRegionInstanceGroupManagerRequest): request = compute.ResizeRegionInstanceGroupManagerRequest(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: @@ -2341,7 +2290,6 @@ def set_instance_template( This corresponds to the ``region_instance_group_managers_set_template_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. @@ -2404,10 +2352,8 @@ def set_instance_template( request = compute.SetInstanceTemplateRegionInstanceGroupManagerRequest( 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: @@ -2472,7 +2418,6 @@ def set_target_pools( This corresponds to the ``region_instance_group_managers_set_target_pools_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. @@ -2533,10 +2478,8 @@ def set_target_pools( request, compute.SetTargetPoolsRegionInstanceGroupManagerRequest ): request = compute.SetTargetPoolsRegionInstanceGroupManagerRequest(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: @@ -2607,7 +2550,6 @@ def update_per_instance_configs( This corresponds to the ``region_instance_group_manager_update_instance_config_req_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. @@ -2670,10 +2612,8 @@ def update_per_instance_configs( request = compute.UpdatePerInstanceConfigsRegionInstanceGroupManagerRequest( 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: diff --git a/google/cloud/compute_v1/services/region_instance_group_managers/pagers.py b/google/cloud/compute_v1/services/region_instance_group_managers/pagers.py index 190a93fd7..df30d924d 100644 --- a/google/cloud/compute_v1/services/region_instance_group_managers/pagers.py +++ b/google/cloud/compute_v1/services/region_instance_group_managers/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/region_instance_group_managers/transports/__init__.py b/google/cloud/compute_v1/services/region_instance_group_managers/transports/__init__.py index d65bc4fad..b6a112bef 100644 --- a/google/cloud/compute_v1/services/region_instance_group_managers/transports/__init__.py +++ b/google/cloud/compute_v1/services/region_instance_group_managers/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/region_instance_group_managers/transports/base.py b/google/cloud/compute_v1/services/region_instance_group_managers/transports/base.py index 08572cfd8..a4f785236 100644 --- a/google/cloud/compute_v1/services/region_instance_group_managers/transports/base.py +++ b/google/cloud/compute_v1/services/region_instance_group_managers/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class RegionInstanceGroupManagersTransport(abc.ABC): """Abstract transport class for RegionInstanceGroupManagers.""" @@ -44,21 +54,24 @@ class RegionInstanceGroupManagersTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -183,85 +243,83 @@ def _prep_wrapped_messages(self, client_info): @property def abandon_instances( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AbandonInstancesRegionInstanceGroupManagerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def apply_updates_to_instances( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ApplyUpdatesToInstancesRegionInstanceGroupManagerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def create_instances( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.CreateInstancesRegionInstanceGroupManagerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteRegionInstanceGroupManagerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def delete_instances( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteInstancesRegionInstanceGroupManagerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def delete_per_instance_configs( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeletePerInstanceConfigsRegionInstanceGroupManagerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetRegionInstanceGroupManagerRequest], - typing.Union[ - compute.InstanceGroupManager, typing.Awaitable[compute.InstanceGroupManager] - ], + Union[compute.InstanceGroupManager, Awaitable[compute.InstanceGroupManager]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertRegionInstanceGroupManagerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListRegionInstanceGroupManagersRequest], - typing.Union[ + Union[ compute.RegionInstanceGroupManagerList, - typing.Awaitable[compute.RegionInstanceGroupManagerList], + Awaitable[compute.RegionInstanceGroupManagerList], ], ]: raise NotImplementedError() @@ -269,11 +327,11 @@ def list( @property def list_errors( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListErrorsRegionInstanceGroupManagersRequest], - typing.Union[ + Union[ compute.RegionInstanceGroupManagersListErrorsResponse, - typing.Awaitable[compute.RegionInstanceGroupManagersListErrorsResponse], + Awaitable[compute.RegionInstanceGroupManagersListErrorsResponse], ], ]: raise NotImplementedError() @@ -281,11 +339,11 @@ def list_errors( @property def list_managed_instances( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListManagedInstancesRegionInstanceGroupManagersRequest], - typing.Union[ + Union[ compute.RegionInstanceGroupManagersListInstancesResponse, - typing.Awaitable[compute.RegionInstanceGroupManagersListInstancesResponse], + Awaitable[compute.RegionInstanceGroupManagersListInstancesResponse], ], ]: raise NotImplementedError() @@ -293,13 +351,11 @@ def list_managed_instances( @property def list_per_instance_configs( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListPerInstanceConfigsRegionInstanceGroupManagersRequest], - typing.Union[ + Union[ compute.RegionInstanceGroupManagersListInstanceConfigsResp, - typing.Awaitable[ - compute.RegionInstanceGroupManagersListInstanceConfigsResp - ], + Awaitable[compute.RegionInstanceGroupManagersListInstanceConfigsResp], ], ]: raise NotImplementedError() @@ -307,63 +363,63 @@ def list_per_instance_configs( @property def patch( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchRegionInstanceGroupManagerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def patch_per_instance_configs( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchPerInstanceConfigsRegionInstanceGroupManagerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def recreate_instances( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.RecreateInstancesRegionInstanceGroupManagerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def resize( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ResizeRegionInstanceGroupManagerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_instance_template( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetInstanceTemplateRegionInstanceGroupManagerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_target_pools( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetTargetPoolsRegionInstanceGroupManagerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def update_per_instance_configs( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.UpdatePerInstanceConfigsRegionInstanceGroupManagerRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/region_instance_group_managers/transports/rest.py b/google/cloud/compute_v1/services/region_instance_group_managers/transports/rest.py index a6d45afa1..88f581b7b 100644 --- a/google/cloud/compute_v1/services/region_instance_group_managers/transports/rest.py +++ b/google/cloud/compute_v1/services/region_instance_group_managers/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 RegionInstanceGroupManagersTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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 abandon_instances( self, @@ -103,8 +103,7 @@ def abandon_instances( Args: request (~.compute.AbandonInstancesRegionInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for RegionInstanceGroupManagers.AbandonInstances. See the method description for details. @@ -162,15 +161,17 @@ def abandon_instances( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if ( + compute.AbandonInstancesRegionInstanceGroupManagerRequest.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() if v - ] + 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 @@ -193,8 +194,7 @@ def apply_updates_to_instances( Args: request (~.compute.ApplyUpdatesToInstancesRegionInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for RegionInstanceGroupManagers.ApplyUpdatesToInstances. See the method description for details. @@ -253,12 +253,11 @@ def apply_updates_to_instances( # 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() if v - ] + 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 @@ -280,8 +279,7 @@ def create_instances( Args: request (~.compute.CreateInstancesRegionInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for RegionInstanceGroupManagers.CreateInstances. See the method description for details. @@ -339,15 +337,17 @@ def create_instances( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if ( + compute.CreateInstancesRegionInstanceGroupManagerRequest.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() if v - ] + 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 @@ -369,8 +369,7 @@ def delete( Args: request (~.compute.DeleteRegionInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for RegionInstanceGroupManagers.Delete. See the method description for details. @@ -421,19 +420,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteRegionInstanceGroupManagerRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -451,8 +449,7 @@ def delete_instances( Args: request (~.compute.DeleteInstancesRegionInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for RegionInstanceGroupManagers.DeleteInstances. See the method description for details. @@ -510,15 +507,17 @@ def delete_instances( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if ( + compute.DeleteInstancesRegionInstanceGroupManagerRequest.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() if v - ] + 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 @@ -541,8 +540,7 @@ def delete_per_instance_configs( Args: request (~.compute.DeletePerInstanceConfigsRegionInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for RegionInstanceGroupManagers.DeletePerInstanceConfigs. See the method description for details. @@ -601,12 +599,11 @@ def delete_per_instance_configs( # 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() if v - ] + 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 @@ -628,8 +625,7 @@ def get( Args: request (~.compute.GetRegionInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for RegionInstanceGroupManagers.Get. See the method description for details. @@ -667,16 +663,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -696,8 +691,7 @@ def insert( Args: request (~.compute.InsertRegionInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for RegionInstanceGroupManagers.Insert. See the method description for details. @@ -752,15 +746,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertRegionInstanceGroupManagerRequest.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() if v - ] + 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 @@ -782,8 +775,7 @@ def list( Args: request (~.compute.ListRegionInstanceGroupManagersRequest): - The request object. - A request message for + The request object. A request message for RegionInstanceGroupManagers.List. See the method description for details. @@ -805,23 +797,29 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListRegionInstanceGroupManagersRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListRegionInstanceGroupManagersRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListRegionInstanceGroupManagersRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListRegionInstanceGroupManagersRequest.page_token in request: + query_params["pageToken"] = request.page_token + if ( + compute.ListRegionInstanceGroupManagersRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -841,8 +839,7 @@ def list_errors( Args: request (~.compute.ListErrorsRegionInstanceGroupManagersRequest): - The request object. - A request message for + The request object. A request message for RegionInstanceGroupManagers.ListErrors. See the method description for details. @@ -865,23 +862,29 @@ def list_errors( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListErrorsRegionInstanceGroupManagersRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListErrorsRegionInstanceGroupManagersRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListErrorsRegionInstanceGroupManagersRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListErrorsRegionInstanceGroupManagersRequest.page_token in request: + query_params["pageToken"] = request.page_token + if ( + compute.ListErrorsRegionInstanceGroupManagersRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -901,8 +904,7 @@ def list_managed_instances( Args: request (~.compute.ListManagedInstancesRegionInstanceGroupManagersRequest): - The request object. - A request message for + The request object. A request message for RegionInstanceGroupManagers.ListManagedInstances. See the method description for details. @@ -925,23 +927,41 @@ def list_managed_instances( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if ( + compute.ListManagedInstancesRegionInstanceGroupManagersRequest.filter + in request + ): + query_params["filter"] = request.filter + if ( + compute.ListManagedInstancesRegionInstanceGroupManagersRequest.max_results + in request + ): + query_params["maxResults"] = request.max_results + if ( + compute.ListManagedInstancesRegionInstanceGroupManagersRequest.order_by + in request + ): + query_params["orderBy"] = request.order_by + if ( + compute.ListManagedInstancesRegionInstanceGroupManagersRequest.page_token + in request + ): + query_params["pageToken"] = request.page_token + if ( + compute.ListManagedInstancesRegionInstanceGroupManagersRequest.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() if v - ] + 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 - response = self._session.post(url) + response = self._session.post(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -961,8 +981,7 @@ def list_per_instance_configs( Args: request (~.compute.ListPerInstanceConfigsRegionInstanceGroupManagersRequest): - The request object. - A request message for + The request object. A request message for RegionInstanceGroupManagers.ListPerInstanceConfigs. See the method description for details. @@ -985,23 +1004,41 @@ def list_per_instance_configs( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if ( + compute.ListPerInstanceConfigsRegionInstanceGroupManagersRequest.filter + in request + ): + query_params["filter"] = request.filter + if ( + compute.ListPerInstanceConfigsRegionInstanceGroupManagersRequest.max_results + in request + ): + query_params["maxResults"] = request.max_results + if ( + compute.ListPerInstanceConfigsRegionInstanceGroupManagersRequest.order_by + in request + ): + query_params["orderBy"] = request.order_by + if ( + compute.ListPerInstanceConfigsRegionInstanceGroupManagersRequest.page_token + in request + ): + query_params["pageToken"] = request.page_token + if ( + compute.ListPerInstanceConfigsRegionInstanceGroupManagersRequest.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() if v - ] + 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 - response = self._session.post(url) + response = self._session.post(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -1021,8 +1058,7 @@ def patch( Args: request (~.compute.PatchRegionInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for RegionInstanceGroupManagers.Patch. See the method description for details. @@ -1080,15 +1116,14 @@ def patch( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.PatchRegionInstanceGroupManagerRequest.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() if v - ] + 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 @@ -1111,8 +1146,7 @@ def patch_per_instance_configs( Args: request (~.compute.PatchPerInstanceConfigsRegionInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for RegionInstanceGroupManagers.PatchPerInstanceConfigs. See the method description for details. @@ -1170,15 +1204,17 @@ def patch_per_instance_configs( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if ( + compute.PatchPerInstanceConfigsRegionInstanceGroupManagerRequest.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() if v - ] + 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 @@ -1200,8 +1236,7 @@ def recreate_instances( Args: request (~.compute.RecreateInstancesRegionInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for RegionInstanceGroupManagers.RecreateInstances. See the method description for details. @@ -1259,15 +1294,17 @@ def recreate_instances( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if ( + compute.RecreateInstancesRegionInstanceGroupManagerRequest.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() if v - ] + 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 @@ -1289,8 +1326,7 @@ def resize( Args: request (~.compute.ResizeRegionInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for RegionInstanceGroupManagers.Resize. See the method description for details. @@ -1341,20 +1377,20 @@ def resize( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - "size": request.size, - } + query_params = {} + if compute.ResizeRegionInstanceGroupManagerRequest.request_id in request: + query_params["requestId"] = request.request_id + if request.size: + query_params["size"] = request.size + # 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() if v - ] + 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 - response = self._session.post(url) + response = self._session.post(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -1372,8 +1408,7 @@ def set_instance_template( Args: request (~.compute.SetInstanceTemplateRegionInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for RegionInstanceGroupManagers.SetInstanceTemplate. See the method description for details. @@ -1431,15 +1466,17 @@ def set_instance_template( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if ( + compute.SetInstanceTemplateRegionInstanceGroupManagerRequest.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() if v - ] + 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 @@ -1461,8 +1498,7 @@ def set_target_pools( Args: request (~.compute.SetTargetPoolsRegionInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for RegionInstanceGroupManagers.SetTargetPools. See the method description for details. @@ -1520,15 +1556,17 @@ def set_target_pools( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if ( + compute.SetTargetPoolsRegionInstanceGroupManagerRequest.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() if v - ] + 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 @@ -1551,8 +1589,7 @@ def update_per_instance_configs( Args: request (~.compute.UpdatePerInstanceConfigsRegionInstanceGroupManagerRequest): - The request object. - A request message for + The request object. A request message for RegionInstanceGroupManagers.UpdatePerInstanceConfigs. See the method description for details. @@ -1610,15 +1647,17 @@ def update_per_instance_configs( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if ( + compute.UpdatePerInstanceConfigsRegionInstanceGroupManagerRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/region_instance_groups/__init__.py b/google/cloud/compute_v1/services/region_instance_groups/__init__.py index 22160d5f0..98253b2f4 100644 --- a/google/cloud/compute_v1/services/region_instance_groups/__init__.py +++ b/google/cloud/compute_v1/services/region_instance_groups/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import RegionInstanceGroupsClient __all__ = ("RegionInstanceGroupsClient",) diff --git a/google/cloud/compute_v1/services/region_instance_groups/client.py b/google/cloud/compute_v1/services/region_instance_groups/client.py index 7e5a877d7..a6e73ef21 100644 --- a/google/cloud/compute_v1/services/region_instance_groups/client.py +++ b/google/cloud/compute_v1/services/region_instance_groups/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.region_instance_groups import pagers from google.cloud.compute_v1.types import compute - from .transports.base import RegionInstanceGroupsTransport, DEFAULT_CLIENT_INFO from .transports.rest import RegionInstanceGroupsRestTransport @@ -217,7 +214,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, RegionInstanceGroupsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -364,7 +361,6 @@ def get( This corresponds to the ``instance_group`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -413,10 +409,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetRegionInstanceGroupRequest): request = compute.GetRegionInstanceGroupRequest(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: @@ -464,7 +458,6 @@ def list( 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. @@ -496,10 +489,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListRegionInstanceGroupsRequest): request = compute.ListRegionInstanceGroupsRequest(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: @@ -568,7 +559,6 @@ def list_instances( This corresponds to the ``region_instance_groups_list_instances_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. @@ -605,10 +595,8 @@ def list_instances( # there are no flattened fields. if not isinstance(request, compute.ListInstancesRegionInstanceGroupsRequest): request = compute.ListInstancesRegionInstanceGroupsRequest(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: @@ -680,7 +668,6 @@ def set_named_ports( This corresponds to the ``region_instance_groups_set_named_ports_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. @@ -739,10 +726,8 @@ def set_named_ports( # there are no flattened fields. if not isinstance(request, compute.SetNamedPortsRegionInstanceGroupRequest): request = compute.SetNamedPortsRegionInstanceGroupRequest(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: diff --git a/google/cloud/compute_v1/services/region_instance_groups/pagers.py b/google/cloud/compute_v1/services/region_instance_groups/pagers.py index 99e176e4b..544b821d9 100644 --- a/google/cloud/compute_v1/services/region_instance_groups/pagers.py +++ b/google/cloud/compute_v1/services/region_instance_groups/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/region_instance_groups/transports/__init__.py b/google/cloud/compute_v1/services/region_instance_groups/transports/__init__.py index 181ec950d..4734ee709 100644 --- a/google/cloud/compute_v1/services/region_instance_groups/transports/__init__.py +++ b/google/cloud/compute_v1/services/region_instance_groups/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/region_instance_groups/transports/base.py b/google/cloud/compute_v1/services/region_instance_groups/transports/base.py index 18a82546c..96a16a3a4 100644 --- a/google/cloud/compute_v1/services/region_instance_groups/transports/base.py +++ b/google/cloud/compute_v1/services/region_instance_groups/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class RegionInstanceGroupsTransport(abc.ABC): """Abstract transport class for RegionInstanceGroups.""" @@ -44,21 +54,24 @@ class RegionInstanceGroupsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -124,20 +184,19 @@ def _prep_wrapped_messages(self, client_info): @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetRegionInstanceGroupRequest], - typing.Union[compute.InstanceGroup, typing.Awaitable[compute.InstanceGroup]], + Union[compute.InstanceGroup, Awaitable[compute.InstanceGroup]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListRegionInstanceGroupsRequest], - typing.Union[ - compute.RegionInstanceGroupList, - typing.Awaitable[compute.RegionInstanceGroupList], + Union[ + compute.RegionInstanceGroupList, Awaitable[compute.RegionInstanceGroupList] ], ]: raise NotImplementedError() @@ -145,11 +204,11 @@ def list( @property def list_instances( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListInstancesRegionInstanceGroupsRequest], - typing.Union[ + Union[ compute.RegionInstanceGroupsListInstances, - typing.Awaitable[compute.RegionInstanceGroupsListInstances], + Awaitable[compute.RegionInstanceGroupsListInstances], ], ]: raise NotImplementedError() @@ -157,9 +216,9 @@ def list_instances( @property def set_named_ports( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetNamedPortsRegionInstanceGroupRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/region_instance_groups/transports/rest.py b/google/cloud/compute_v1/services/region_instance_groups/transports/rest.py index 93d71f00a..df88fbd4f 100644 --- a/google/cloud/compute_v1/services/region_instance_groups/transports/rest.py +++ b/google/cloud/compute_v1/services/region_instance_groups/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 RegionInstanceGroupsTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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 get( self, @@ -103,8 +103,7 @@ def get( Args: request (~.compute.GetRegionInstanceGroupRequest): - The request object. - A request message for + The request object. A request message for RegionInstanceGroups.Get. See the method description for details. @@ -148,16 +147,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -177,8 +175,7 @@ def list( Args: request (~.compute.ListRegionInstanceGroupsRequest): - The request object. - A request message for + The request object. A request message for RegionInstanceGroups.List. See the method description for details. @@ -200,23 +197,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListRegionInstanceGroupsRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListRegionInstanceGroupsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListRegionInstanceGroupsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListRegionInstanceGroupsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListRegionInstanceGroupsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -236,8 +236,7 @@ def list_instances( Args: request (~.compute.ListInstancesRegionInstanceGroupsRequest): - The request object. - A request message for + The request object. A request message for RegionInstanceGroups.ListInstances. See the method description for details. @@ -267,19 +266,25 @@ def list_instances( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListInstancesRegionInstanceGroupsRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListInstancesRegionInstanceGroupsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListInstancesRegionInstanceGroupsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListInstancesRegionInstanceGroupsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if ( + compute.ListInstancesRegionInstanceGroupsRequest.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() if v - ] + 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 @@ -303,8 +308,7 @@ def set_named_ports( Args: request (~.compute.SetNamedPortsRegionInstanceGroupRequest): - The request object. - A request message for + The request object. A request message for RegionInstanceGroups.SetNamedPorts. See the method description for details. @@ -362,15 +366,14 @@ def set_named_ports( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetNamedPortsRegionInstanceGroupRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/region_network_endpoint_groups/__init__.py b/google/cloud/compute_v1/services/region_network_endpoint_groups/__init__.py index 595df32e4..e894239ff 100644 --- a/google/cloud/compute_v1/services/region_network_endpoint_groups/__init__.py +++ b/google/cloud/compute_v1/services/region_network_endpoint_groups/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import RegionNetworkEndpointGroupsClient __all__ = ("RegionNetworkEndpointGroupsClient",) diff --git a/google/cloud/compute_v1/services/region_network_endpoint_groups/client.py b/google/cloud/compute_v1/services/region_network_endpoint_groups/client.py index 5d97de418..339a56287 100644 --- a/google/cloud/compute_v1/services/region_network_endpoint_groups/client.py +++ b/google/cloud/compute_v1/services/region_network_endpoint_groups/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.region_network_endpoint_groups import pagers from google.cloud.compute_v1.types import compute - from .transports.base import RegionNetworkEndpointGroupsTransport, DEFAULT_CLIENT_INFO from .transports.rest import RegionNetworkEndpointGroupsRestTransport @@ -219,7 +216,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, RegionNetworkEndpointGroupsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -370,7 +367,6 @@ def delete( This corresponds to the ``network_endpoint_group`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -422,10 +418,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteRegionNetworkEndpointGroupRequest): request = compute.DeleteRegionNetworkEndpointGroupRequest(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: @@ -483,7 +477,6 @@ def get( This corresponds to the ``network_endpoint_group`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -524,10 +517,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetRegionNetworkEndpointGroupRequest): request = compute.GetRegionNetworkEndpointGroupRequest(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: @@ -583,7 +574,6 @@ def insert( This corresponds to the ``network_endpoint_group_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. @@ -635,10 +625,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertRegionNetworkEndpointGroupRequest): request = compute.InsertRegionNetworkEndpointGroupRequest(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: @@ -690,7 +678,6 @@ def list( 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. @@ -720,10 +707,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListRegionNetworkEndpointGroupsRequest): request = compute.ListRegionNetworkEndpointGroupsRequest(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: diff --git a/google/cloud/compute_v1/services/region_network_endpoint_groups/pagers.py b/google/cloud/compute_v1/services/region_network_endpoint_groups/pagers.py index 66fb6aa05..8781f8db1 100644 --- a/google/cloud/compute_v1/services/region_network_endpoint_groups/pagers.py +++ b/google/cloud/compute_v1/services/region_network_endpoint_groups/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/region_network_endpoint_groups/transports/__init__.py b/google/cloud/compute_v1/services/region_network_endpoint_groups/transports/__init__.py index 0c8e7324c..0b24fe337 100644 --- a/google/cloud/compute_v1/services/region_network_endpoint_groups/transports/__init__.py +++ b/google/cloud/compute_v1/services/region_network_endpoint_groups/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/region_network_endpoint_groups/transports/base.py b/google/cloud/compute_v1/services/region_network_endpoint_groups/transports/base.py index 45e0ae0cc..f16144a08 100644 --- a/google/cloud/compute_v1/services/region_network_endpoint_groups/transports/base.py +++ b/google/cloud/compute_v1/services/region_network_endpoint_groups/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class RegionNetworkEndpointGroupsTransport(abc.ABC): """Abstract transport class for RegionNetworkEndpointGroups.""" @@ -44,21 +54,24 @@ class RegionNetworkEndpointGroupsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -124,40 +184,38 @@ def _prep_wrapped_messages(self, client_info): @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteRegionNetworkEndpointGroupRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetRegionNetworkEndpointGroupRequest], - typing.Union[ - compute.NetworkEndpointGroup, typing.Awaitable[compute.NetworkEndpointGroup] - ], + Union[compute.NetworkEndpointGroup, Awaitable[compute.NetworkEndpointGroup]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertRegionNetworkEndpointGroupRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListRegionNetworkEndpointGroupsRequest], - typing.Union[ + Union[ compute.NetworkEndpointGroupList, - typing.Awaitable[compute.NetworkEndpointGroupList], + Awaitable[compute.NetworkEndpointGroupList], ], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/region_network_endpoint_groups/transports/rest.py b/google/cloud/compute_v1/services/region_network_endpoint_groups/transports/rest.py index 5992e7ef5..36d9cb098 100644 --- a/google/cloud/compute_v1/services/region_network_endpoint_groups/transports/rest.py +++ b/google/cloud/compute_v1/services/region_network_endpoint_groups/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 RegionNetworkEndpointGroupsTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def delete( Args: request (~.compute.DeleteRegionNetworkEndpointGroupRequest): - The request object. - A request message for + The request object. A request message for RegionNetworkEndpointGroups.Delete. See the method description for details. @@ -155,19 +154,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteRegionNetworkEndpointGroupRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -185,8 +183,7 @@ def get( Args: request (~.compute.GetRegionNetworkEndpointGroupRequest): - The request object. - A request message for + The request object. A request message for RegionNetworkEndpointGroups.Get. See the method description for details. @@ -223,16 +220,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -252,8 +248,7 @@ def insert( Args: request (~.compute.InsertRegionNetworkEndpointGroupRequest): - The request object. - A request message for + The request object. A request message for RegionNetworkEndpointGroups.Insert. See the method description for details. @@ -308,15 +303,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertRegionNetworkEndpointGroupRequest.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() if v - ] + 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 @@ -338,8 +332,7 @@ def list( Args: request (~.compute.ListRegionNetworkEndpointGroupsRequest): - The request object. - A request message for + The request object. A request message for RegionNetworkEndpointGroups.List. See the method description for details. @@ -359,23 +352,29 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListRegionNetworkEndpointGroupsRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListRegionNetworkEndpointGroupsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListRegionNetworkEndpointGroupsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListRegionNetworkEndpointGroupsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if ( + compute.ListRegionNetworkEndpointGroupsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() diff --git a/google/cloud/compute_v1/services/region_notification_endpoints/__init__.py b/google/cloud/compute_v1/services/region_notification_endpoints/__init__.py index 2f2cd158e..375094a12 100644 --- a/google/cloud/compute_v1/services/region_notification_endpoints/__init__.py +++ b/google/cloud/compute_v1/services/region_notification_endpoints/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import RegionNotificationEndpointsClient __all__ = ("RegionNotificationEndpointsClient",) diff --git a/google/cloud/compute_v1/services/region_notification_endpoints/client.py b/google/cloud/compute_v1/services/region_notification_endpoints/client.py index 45bb0d59a..21cf85ae1 100644 --- a/google/cloud/compute_v1/services/region_notification_endpoints/client.py +++ b/google/cloud/compute_v1/services/region_notification_endpoints/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.region_notification_endpoints import pagers from google.cloud.compute_v1.types import compute - from .transports.base import RegionNotificationEndpointsTransport, DEFAULT_CLIENT_INFO from .transports.rest import RegionNotificationEndpointsRestTransport @@ -219,7 +216,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, RegionNotificationEndpointsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -367,7 +364,6 @@ def delete( This corresponds to the ``notification_endpoint`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -419,10 +415,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteRegionNotificationEndpointRequest): request = compute.DeleteRegionNotificationEndpointRequest(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: @@ -478,7 +472,6 @@ def get( This corresponds to the ``notification_endpoint`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -516,10 +509,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetRegionNotificationEndpointRequest): request = compute.GetRegionNotificationEndpointRequest(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: @@ -574,7 +565,6 @@ def insert( This corresponds to the ``notification_endpoint_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. @@ -626,10 +616,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertRegionNotificationEndpointRequest): request = compute.InsertRegionNotificationEndpointRequest(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: @@ -677,7 +665,6 @@ def list( 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. @@ -707,10 +694,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListRegionNotificationEndpointsRequest): request = compute.ListRegionNotificationEndpointsRequest(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: diff --git a/google/cloud/compute_v1/services/region_notification_endpoints/pagers.py b/google/cloud/compute_v1/services/region_notification_endpoints/pagers.py index dc3331ed7..231e421a7 100644 --- a/google/cloud/compute_v1/services/region_notification_endpoints/pagers.py +++ b/google/cloud/compute_v1/services/region_notification_endpoints/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/region_notification_endpoints/transports/__init__.py b/google/cloud/compute_v1/services/region_notification_endpoints/transports/__init__.py index ac83d3358..c5b9d2a7b 100644 --- a/google/cloud/compute_v1/services/region_notification_endpoints/transports/__init__.py +++ b/google/cloud/compute_v1/services/region_notification_endpoints/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/region_notification_endpoints/transports/base.py b/google/cloud/compute_v1/services/region_notification_endpoints/transports/base.py index 3b124fb0f..af575760b 100644 --- a/google/cloud/compute_v1/services/region_notification_endpoints/transports/base.py +++ b/google/cloud/compute_v1/services/region_notification_endpoints/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class RegionNotificationEndpointsTransport(abc.ABC): """Abstract transport class for RegionNotificationEndpoints.""" @@ -44,21 +54,24 @@ class RegionNotificationEndpointsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -124,40 +184,38 @@ def _prep_wrapped_messages(self, client_info): @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteRegionNotificationEndpointRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetRegionNotificationEndpointRequest], - typing.Union[ - compute.NotificationEndpoint, typing.Awaitable[compute.NotificationEndpoint] - ], + Union[compute.NotificationEndpoint, Awaitable[compute.NotificationEndpoint]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertRegionNotificationEndpointRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListRegionNotificationEndpointsRequest], - typing.Union[ + Union[ compute.NotificationEndpointList, - typing.Awaitable[compute.NotificationEndpointList], + Awaitable[compute.NotificationEndpointList], ], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/region_notification_endpoints/transports/rest.py b/google/cloud/compute_v1/services/region_notification_endpoints/transports/rest.py index 57e1f587f..af411a4b0 100644 --- a/google/cloud/compute_v1/services/region_notification_endpoints/transports/rest.py +++ b/google/cloud/compute_v1/services/region_notification_endpoints/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 RegionNotificationEndpointsTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def delete( Args: request (~.compute.DeleteRegionNotificationEndpointRequest): - The request object. - A request message for + The request object. A request message for RegionNotificationEndpoints.Delete. See the method description for details. @@ -155,19 +154,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteRegionNotificationEndpointRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -185,8 +183,7 @@ def get( Args: request (~.compute.GetRegionNotificationEndpointRequest): - The request object. - A request message for + The request object. A request message for RegionNotificationEndpoints.Get. See the method description for details. @@ -220,16 +217,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -249,8 +245,7 @@ def insert( Args: request (~.compute.InsertRegionNotificationEndpointRequest): - The request object. - A request message for + The request object. A request message for RegionNotificationEndpoints.Insert. See the method description for details. @@ -305,15 +300,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertRegionNotificationEndpointRequest.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() if v - ] + 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 @@ -335,8 +329,7 @@ def list( Args: request (~.compute.ListRegionNotificationEndpointsRequest): - The request object. - A request message for + The request object. A request message for RegionNotificationEndpoints.List. See the method description for details. @@ -356,23 +349,29 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListRegionNotificationEndpointsRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListRegionNotificationEndpointsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListRegionNotificationEndpointsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListRegionNotificationEndpointsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if ( + compute.ListRegionNotificationEndpointsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() diff --git a/google/cloud/compute_v1/services/region_operations/__init__.py b/google/cloud/compute_v1/services/region_operations/__init__.py index 521705e62..045d6ef1f 100644 --- a/google/cloud/compute_v1/services/region_operations/__init__.py +++ b/google/cloud/compute_v1/services/region_operations/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import RegionOperationsClient __all__ = ("RegionOperationsClient",) diff --git a/google/cloud/compute_v1/services/region_operations/client.py b/google/cloud/compute_v1/services/region_operations/client.py index 98fa6d571..fa80494fc 100644 --- a/google/cloud/compute_v1/services/region_operations/client.py +++ b/google/cloud/compute_v1/services/region_operations/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.region_operations import pagers from google.cloud.compute_v1.types import compute - from .transports.base import RegionOperationsTransport, DEFAULT_CLIENT_INFO from .transports.rest import RegionOperationsRestTransport @@ -215,7 +212,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, RegionOperationsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -361,7 +358,6 @@ def delete( This corresponds to the ``operation`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -391,10 +387,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteRegionOperationRequest): request = compute.DeleteRegionOperationRequest(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: @@ -448,7 +442,6 @@ def get( This corresponds to the ``operation`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -500,10 +493,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetRegionOperationRequest): request = compute.GetRegionOperationRequest(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: @@ -549,7 +540,6 @@ def list( 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. @@ -581,10 +571,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListRegionOperationsRequest): request = compute.ListRegionOperationsRequest(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: @@ -655,7 +643,6 @@ def wait( This corresponds to the ``operation`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -707,10 +694,8 @@ def wait( # there are no flattened fields. if not isinstance(request, compute.WaitRegionOperationRequest): request = compute.WaitRegionOperationRequest(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: diff --git a/google/cloud/compute_v1/services/region_operations/pagers.py b/google/cloud/compute_v1/services/region_operations/pagers.py index fc7a72dc0..15966eabd 100644 --- a/google/cloud/compute_v1/services/region_operations/pagers.py +++ b/google/cloud/compute_v1/services/region_operations/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/region_operations/transports/__init__.py b/google/cloud/compute_v1/services/region_operations/transports/__init__.py index dadd9e49b..f30f1f516 100644 --- a/google/cloud/compute_v1/services/region_operations/transports/__init__.py +++ b/google/cloud/compute_v1/services/region_operations/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/region_operations/transports/base.py b/google/cloud/compute_v1/services/region_operations/transports/base.py index 31a63d03f..01c86aad2 100644 --- a/google/cloud/compute_v1/services/region_operations/transports/base.py +++ b/google/cloud/compute_v1/services/region_operations/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class RegionOperationsTransport(abc.ABC): """Abstract transport class for RegionOperations.""" @@ -44,21 +54,24 @@ class RegionOperationsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -124,11 +184,11 @@ def _prep_wrapped_messages(self, client_info): @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteRegionOperationRequest], - typing.Union[ + Union[ compute.DeleteRegionOperationResponse, - typing.Awaitable[compute.DeleteRegionOperationResponse], + Awaitable[compute.DeleteRegionOperationResponse], ], ]: raise NotImplementedError() @@ -136,27 +196,27 @@ def delete( @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetRegionOperationRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListRegionOperationsRequest], - typing.Union[compute.OperationList, typing.Awaitable[compute.OperationList]], + Union[compute.OperationList, Awaitable[compute.OperationList]], ]: raise NotImplementedError() @property def wait( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.WaitRegionOperationRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/region_operations/transports/rest.py b/google/cloud/compute_v1/services/region_operations/transports/rest.py index a718d29ef..e2448c28c 100644 --- a/google/cloud/compute_v1/services/region_operations/transports/rest.py +++ b/google/cloud/compute_v1/services/region_operations/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 RegionOperationsTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def delete( Args: request (~.compute.DeleteRegionOperationRequest): - The request object. - A request message for + The request object. A request message for RegionOperations.Delete. See the method description for details. @@ -131,16 +130,15 @@ def delete( # 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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -160,8 +158,7 @@ def get( Args: request (~.compute.GetRegionOperationRequest): - The request object. - A request message for + The request object. A request message for RegionOperations.Get. See the method description for details. @@ -213,16 +210,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -240,8 +236,7 @@ def list( Args: request (~.compute.ListRegionOperationsRequest): - The request object. - A request message for + The request object. A request message for RegionOperations.List. See the method description for details. @@ -263,23 +258,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListRegionOperationsRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListRegionOperationsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListRegionOperationsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListRegionOperationsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListRegionOperationsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -299,8 +297,7 @@ def wait( Args: request (~.compute.WaitRegionOperationRequest): - The request object. - A request message for + The request object. A request message for RegionOperations.Wait. See the method description for details. @@ -352,16 +349,15 @@ def wait( # 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() if v - ] + 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 - response = self._session.post(url) + response = self._session.post(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() diff --git a/google/cloud/compute_v1/services/region_ssl_certificates/__init__.py b/google/cloud/compute_v1/services/region_ssl_certificates/__init__.py index 5fb128e0c..af21c8831 100644 --- a/google/cloud/compute_v1/services/region_ssl_certificates/__init__.py +++ b/google/cloud/compute_v1/services/region_ssl_certificates/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import RegionSslCertificatesClient __all__ = ("RegionSslCertificatesClient",) diff --git a/google/cloud/compute_v1/services/region_ssl_certificates/client.py b/google/cloud/compute_v1/services/region_ssl_certificates/client.py index 3355d6a5a..9a0e99974 100644 --- a/google/cloud/compute_v1/services/region_ssl_certificates/client.py +++ b/google/cloud/compute_v1/services/region_ssl_certificates/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.region_ssl_certificates import pagers from google.cloud.compute_v1.types import compute - from .transports.base import RegionSslCertificatesTransport, DEFAULT_CLIENT_INFO from .transports.rest import RegionSslCertificatesRestTransport @@ -217,7 +214,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, RegionSslCertificatesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -365,7 +362,6 @@ def delete( This corresponds to the ``ssl_certificate`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -417,10 +413,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteRegionSslCertificateRequest): request = compute.DeleteRegionSslCertificateRequest(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: @@ -477,7 +471,6 @@ def get( This corresponds to the ``ssl_certificate`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -529,10 +522,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetRegionSslCertificateRequest): request = compute.GetRegionSslCertificateRequest(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: @@ -587,7 +578,6 @@ def insert( This corresponds to the ``ssl_certificate_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. @@ -639,10 +629,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertRegionSslCertificateRequest): request = compute.InsertRegionSslCertificateRequest(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: @@ -691,7 +679,6 @@ def list( 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. @@ -723,10 +710,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListRegionSslCertificatesRequest): request = compute.ListRegionSslCertificatesRequest(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: diff --git a/google/cloud/compute_v1/services/region_ssl_certificates/pagers.py b/google/cloud/compute_v1/services/region_ssl_certificates/pagers.py index bbe705086..b7d38b271 100644 --- a/google/cloud/compute_v1/services/region_ssl_certificates/pagers.py +++ b/google/cloud/compute_v1/services/region_ssl_certificates/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/region_ssl_certificates/transports/__init__.py b/google/cloud/compute_v1/services/region_ssl_certificates/transports/__init__.py index b80c4bb90..2cb7aebe0 100644 --- a/google/cloud/compute_v1/services/region_ssl_certificates/transports/__init__.py +++ b/google/cloud/compute_v1/services/region_ssl_certificates/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/region_ssl_certificates/transports/base.py b/google/cloud/compute_v1/services/region_ssl_certificates/transports/base.py index 988612572..39ec28d6d 100644 --- a/google/cloud/compute_v1/services/region_ssl_certificates/transports/base.py +++ b/google/cloud/compute_v1/services/region_ssl_certificates/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class RegionSslCertificatesTransport(abc.ABC): """Abstract transport class for RegionSslCertificates.""" @@ -44,21 +54,24 @@ class RegionSslCertificatesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -124,38 +184,36 @@ def _prep_wrapped_messages(self, client_info): @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteRegionSslCertificateRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetRegionSslCertificateRequest], - typing.Union[compute.SslCertificate, typing.Awaitable[compute.SslCertificate]], + Union[compute.SslCertificate, Awaitable[compute.SslCertificate]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertRegionSslCertificateRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListRegionSslCertificatesRequest], - typing.Union[ - compute.SslCertificateList, typing.Awaitable[compute.SslCertificateList] - ], + Union[compute.SslCertificateList, Awaitable[compute.SslCertificateList]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/region_ssl_certificates/transports/rest.py b/google/cloud/compute_v1/services/region_ssl_certificates/transports/rest.py index 9ad60de09..3dbb7fee3 100644 --- a/google/cloud/compute_v1/services/region_ssl_certificates/transports/rest.py +++ b/google/cloud/compute_v1/services/region_ssl_certificates/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 RegionSslCertificatesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def delete( Args: request (~.compute.DeleteRegionSslCertificateRequest): - The request object. - A request message for + The request object. A request message for RegionSslCertificates.Delete. See the method description for details. @@ -155,19 +154,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteRegionSslCertificateRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -185,8 +183,7 @@ def get( Args: request (~.compute.GetRegionSslCertificateRequest): - The request object. - A request message for + The request object. A request message for RegionSslCertificates.Get. See the method description for details. @@ -236,16 +233,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -265,8 +261,7 @@ def insert( Args: request (~.compute.InsertRegionSslCertificateRequest): - The request object. - A request message for + The request object. A request message for RegionSslCertificates.Insert. See the method description for details. @@ -321,15 +316,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertRegionSslCertificateRequest.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() if v - ] + 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 @@ -351,8 +345,7 @@ def list( Args: request (~.compute.ListRegionSslCertificatesRequest): - The request object. - A request message for + The request object. A request message for RegionSslCertificates.List. See the method description for details. @@ -374,23 +367,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListRegionSslCertificatesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListRegionSslCertificatesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListRegionSslCertificatesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListRegionSslCertificatesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListRegionSslCertificatesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() diff --git a/google/cloud/compute_v1/services/region_target_http_proxies/__init__.py b/google/cloud/compute_v1/services/region_target_http_proxies/__init__.py index 126b5799b..c2e8d6a18 100644 --- a/google/cloud/compute_v1/services/region_target_http_proxies/__init__.py +++ b/google/cloud/compute_v1/services/region_target_http_proxies/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import RegionTargetHttpProxiesClient __all__ = ("RegionTargetHttpProxiesClient",) diff --git a/google/cloud/compute_v1/services/region_target_http_proxies/client.py b/google/cloud/compute_v1/services/region_target_http_proxies/client.py index fcd3f671c..244f3d173 100644 --- a/google/cloud/compute_v1/services/region_target_http_proxies/client.py +++ b/google/cloud/compute_v1/services/region_target_http_proxies/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.region_target_http_proxies import pagers from google.cloud.compute_v1.types import compute - from .transports.base import RegionTargetHttpProxiesTransport, DEFAULT_CLIENT_INFO from .transports.rest import RegionTargetHttpProxiesRestTransport @@ -217,7 +214,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, RegionTargetHttpProxiesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -364,7 +361,6 @@ def delete( This corresponds to the ``target_http_proxy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -416,10 +412,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteRegionTargetHttpProxyRequest): request = compute.DeleteRegionTargetHttpProxyRequest(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: @@ -476,7 +470,6 @@ def get( This corresponds to the ``target_http_proxy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -526,10 +519,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetRegionTargetHttpProxyRequest): request = compute.GetRegionTargetHttpProxyRequest(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: @@ -584,7 +575,6 @@ def insert( This corresponds to the ``target_http_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. @@ -636,10 +626,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertRegionTargetHttpProxyRequest): request = compute.InsertRegionTargetHttpProxyRequest(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: @@ -688,7 +676,6 @@ def list( 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. @@ -719,10 +706,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListRegionTargetHttpProxiesRequest): request = compute.ListRegionTargetHttpProxiesRequest(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: @@ -787,7 +772,6 @@ def set_url_map( This corresponds to the ``url_map_reference_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. @@ -841,10 +825,8 @@ def set_url_map( # there are no flattened fields. if not isinstance(request, compute.SetUrlMapRegionTargetHttpProxyRequest): request = compute.SetUrlMapRegionTargetHttpProxyRequest(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: diff --git a/google/cloud/compute_v1/services/region_target_http_proxies/pagers.py b/google/cloud/compute_v1/services/region_target_http_proxies/pagers.py index 25a545b2c..3e9c44a7f 100644 --- a/google/cloud/compute_v1/services/region_target_http_proxies/pagers.py +++ b/google/cloud/compute_v1/services/region_target_http_proxies/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/region_target_http_proxies/transports/__init__.py b/google/cloud/compute_v1/services/region_target_http_proxies/transports/__init__.py index 125b578b4..1e6864999 100644 --- a/google/cloud/compute_v1/services/region_target_http_proxies/transports/__init__.py +++ b/google/cloud/compute_v1/services/region_target_http_proxies/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/region_target_http_proxies/transports/base.py b/google/cloud/compute_v1/services/region_target_http_proxies/transports/base.py index 688a6a7b7..f8c422f73 100644 --- a/google/cloud/compute_v1/services/region_target_http_proxies/transports/base.py +++ b/google/cloud/compute_v1/services/region_target_http_proxies/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class RegionTargetHttpProxiesTransport(abc.ABC): """Abstract transport class for RegionTargetHttpProxies.""" @@ -44,21 +54,24 @@ class RegionTargetHttpProxiesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -127,49 +187,45 @@ def _prep_wrapped_messages(self, client_info): @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteRegionTargetHttpProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetRegionTargetHttpProxyRequest], - typing.Union[ - compute.TargetHttpProxy, typing.Awaitable[compute.TargetHttpProxy] - ], + Union[compute.TargetHttpProxy, Awaitable[compute.TargetHttpProxy]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertRegionTargetHttpProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListRegionTargetHttpProxiesRequest], - typing.Union[ - compute.TargetHttpProxyList, typing.Awaitable[compute.TargetHttpProxyList] - ], + Union[compute.TargetHttpProxyList, Awaitable[compute.TargetHttpProxyList]], ]: raise NotImplementedError() @property def set_url_map( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetUrlMapRegionTargetHttpProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/region_target_http_proxies/transports/rest.py b/google/cloud/compute_v1/services/region_target_http_proxies/transports/rest.py index 253befd20..5413cc717 100644 --- a/google/cloud/compute_v1/services/region_target_http_proxies/transports/rest.py +++ b/google/cloud/compute_v1/services/region_target_http_proxies/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 RegionTargetHttpProxiesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def delete( Args: request (~.compute.DeleteRegionTargetHttpProxyRequest): - The request object. - A request message for + The request object. A request message for RegionTargetHttpProxies.Delete. See the method description for details. @@ -155,19 +154,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteRegionTargetHttpProxyRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -185,8 +183,7 @@ def get( Args: request (~.compute.GetRegionTargetHttpProxyRequest): - The request object. - A request message for + The request object. A request message for RegionTargetHttpProxies.Get. See the method description for details. @@ -233,16 +230,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -262,8 +258,7 @@ def insert( Args: request (~.compute.InsertRegionTargetHttpProxyRequest): - The request object. - A request message for + The request object. A request message for RegionTargetHttpProxies.Insert. See the method description for details. @@ -318,15 +313,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertRegionTargetHttpProxyRequest.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() if v - ] + 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 @@ -348,8 +342,7 @@ def list( Args: request (~.compute.ListRegionTargetHttpProxiesRequest): - The request object. - A request message for + The request object. A request message for RegionTargetHttpProxies.List. See the method description for details. @@ -369,23 +362,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListRegionTargetHttpProxiesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListRegionTargetHttpProxiesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListRegionTargetHttpProxiesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListRegionTargetHttpProxiesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListRegionTargetHttpProxiesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -405,8 +401,7 @@ def set_url_map( Args: request (~.compute.SetUrlMapRegionTargetHttpProxyRequest): - The request object. - A request message for + The request object. A request message for RegionTargetHttpProxies.SetUrlMap. See the method description for details. @@ -464,15 +459,14 @@ def set_url_map( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetUrlMapRegionTargetHttpProxyRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/region_target_https_proxies/__init__.py b/google/cloud/compute_v1/services/region_target_https_proxies/__init__.py index 8bd4a14f6..5fdc9013c 100644 --- a/google/cloud/compute_v1/services/region_target_https_proxies/__init__.py +++ b/google/cloud/compute_v1/services/region_target_https_proxies/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import RegionTargetHttpsProxiesClient __all__ = ("RegionTargetHttpsProxiesClient",) diff --git a/google/cloud/compute_v1/services/region_target_https_proxies/client.py b/google/cloud/compute_v1/services/region_target_https_proxies/client.py index 71935d61f..053f65d4a 100644 --- a/google/cloud/compute_v1/services/region_target_https_proxies/client.py +++ b/google/cloud/compute_v1/services/region_target_https_proxies/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.region_target_https_proxies import pagers from google.cloud.compute_v1.types import compute - from .transports.base import RegionTargetHttpsProxiesTransport, DEFAULT_CLIENT_INFO from .transports.rest import RegionTargetHttpsProxiesRestTransport @@ -217,7 +214,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, RegionTargetHttpsProxiesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -364,7 +361,6 @@ def delete( This corresponds to the ``target_https_proxy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -416,10 +412,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteRegionTargetHttpsProxyRequest): request = compute.DeleteRegionTargetHttpsProxyRequest(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: @@ -476,7 +470,6 @@ def get( This corresponds to the ``target_https_proxy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -526,10 +519,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetRegionTargetHttpsProxyRequest): request = compute.GetRegionTargetHttpsProxyRequest(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: @@ -584,7 +575,6 @@ def insert( 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. @@ -636,10 +626,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertRegionTargetHttpsProxyRequest): request = compute.InsertRegionTargetHttpsProxyRequest(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: @@ -688,7 +676,6 @@ def list( 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. @@ -720,10 +707,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListRegionTargetHttpsProxiesRequest): request = compute.ListRegionTargetHttpsProxiesRequest(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: @@ -788,7 +773,6 @@ def set_ssl_certificates( This corresponds to the ``region_target_https_proxies_set_ssl_certificates_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. @@ -849,10 +833,8 @@ def set_ssl_certificates( request, compute.SetSslCertificatesRegionTargetHttpsProxyRequest ): request = compute.SetSslCertificatesRegionTargetHttpsProxyRequest(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: @@ -920,7 +902,6 @@ def set_url_map( This corresponds to the ``url_map_reference_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. @@ -974,10 +955,8 @@ def set_url_map( # there are no flattened fields. if not isinstance(request, compute.SetUrlMapRegionTargetHttpsProxyRequest): request = compute.SetUrlMapRegionTargetHttpsProxyRequest(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: diff --git a/google/cloud/compute_v1/services/region_target_https_proxies/pagers.py b/google/cloud/compute_v1/services/region_target_https_proxies/pagers.py index 2e38cef7d..6d15ff5c2 100644 --- a/google/cloud/compute_v1/services/region_target_https_proxies/pagers.py +++ b/google/cloud/compute_v1/services/region_target_https_proxies/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/region_target_https_proxies/transports/__init__.py b/google/cloud/compute_v1/services/region_target_https_proxies/transports/__init__.py index d554cc750..3ef61aac0 100644 --- a/google/cloud/compute_v1/services/region_target_https_proxies/transports/__init__.py +++ b/google/cloud/compute_v1/services/region_target_https_proxies/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/region_target_https_proxies/transports/base.py b/google/cloud/compute_v1/services/region_target_https_proxies/transports/base.py index 390e3ac0e..d39837b98 100644 --- a/google/cloud/compute_v1/services/region_target_https_proxies/transports/base.py +++ b/google/cloud/compute_v1/services/region_target_https_proxies/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class RegionTargetHttpsProxiesTransport(abc.ABC): """Abstract transport class for RegionTargetHttpsProxies.""" @@ -44,21 +54,24 @@ class RegionTargetHttpsProxiesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -132,58 +192,54 @@ def _prep_wrapped_messages(self, client_info): @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteRegionTargetHttpsProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetRegionTargetHttpsProxyRequest], - typing.Union[ - compute.TargetHttpsProxy, typing.Awaitable[compute.TargetHttpsProxy] - ], + Union[compute.TargetHttpsProxy, Awaitable[compute.TargetHttpsProxy]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertRegionTargetHttpsProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListRegionTargetHttpsProxiesRequest], - typing.Union[ - compute.TargetHttpsProxyList, typing.Awaitable[compute.TargetHttpsProxyList] - ], + Union[compute.TargetHttpsProxyList, Awaitable[compute.TargetHttpsProxyList]], ]: raise NotImplementedError() @property def set_ssl_certificates( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetSslCertificatesRegionTargetHttpsProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_url_map( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetUrlMapRegionTargetHttpsProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/region_target_https_proxies/transports/rest.py b/google/cloud/compute_v1/services/region_target_https_proxies/transports/rest.py index be05ba83e..258ffc1a7 100644 --- a/google/cloud/compute_v1/services/region_target_https_proxies/transports/rest.py +++ b/google/cloud/compute_v1/services/region_target_https_proxies/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 RegionTargetHttpsProxiesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def delete( Args: request (~.compute.DeleteRegionTargetHttpsProxyRequest): - The request object. - A request message for + The request object. A request message for RegionTargetHttpsProxies.Delete. See the method description for details. @@ -155,19 +154,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteRegionTargetHttpsProxyRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -185,8 +183,7 @@ def get( Args: request (~.compute.GetRegionTargetHttpsProxyRequest): - The request object. - A request message for + The request object. A request message for RegionTargetHttpsProxies.Get. See the method description for details. @@ -232,16 +229,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -261,8 +257,7 @@ def insert( Args: request (~.compute.InsertRegionTargetHttpsProxyRequest): - The request object. - A request message for + The request object. A request message for RegionTargetHttpsProxies.Insert. See the method description for details. @@ -317,15 +312,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertRegionTargetHttpsProxyRequest.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() if v - ] + 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 @@ -347,8 +341,7 @@ def list( Args: request (~.compute.ListRegionTargetHttpsProxiesRequest): - The request object. - A request message for + The request object. A request message for RegionTargetHttpsProxies.List. See the method description for details. @@ -370,23 +363,29 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListRegionTargetHttpsProxiesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListRegionTargetHttpsProxiesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListRegionTargetHttpsProxiesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListRegionTargetHttpsProxiesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if ( + compute.ListRegionTargetHttpsProxiesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -406,8 +405,7 @@ def set_ssl_certificates( Args: request (~.compute.SetSslCertificatesRegionTargetHttpsProxyRequest): - The request object. - A request message for + The request object. A request message for RegionTargetHttpsProxies.SetSslCertificates. See the method description for details. @@ -465,15 +463,17 @@ def set_ssl_certificates( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if ( + compute.SetSslCertificatesRegionTargetHttpsProxyRequest.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() if v - ] + 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 @@ -495,8 +495,7 @@ def set_url_map( Args: request (~.compute.SetUrlMapRegionTargetHttpsProxyRequest): - The request object. - A request message for + The request object. A request message for RegionTargetHttpsProxies.SetUrlMap. See the method description for details. @@ -554,15 +553,14 @@ def set_url_map( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetUrlMapRegionTargetHttpsProxyRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/region_url_maps/__init__.py b/google/cloud/compute_v1/services/region_url_maps/__init__.py index 2f4be5abd..f618b96ca 100644 --- a/google/cloud/compute_v1/services/region_url_maps/__init__.py +++ b/google/cloud/compute_v1/services/region_url_maps/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import RegionUrlMapsClient __all__ = ("RegionUrlMapsClient",) diff --git a/google/cloud/compute_v1/services/region_url_maps/client.py b/google/cloud/compute_v1/services/region_url_maps/client.py index 45b175910..1f5ddd537 100644 --- a/google/cloud/compute_v1/services/region_url_maps/client.py +++ b/google/cloud/compute_v1/services/region_url_maps/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.region_url_maps import pagers from google.cloud.compute_v1.types import compute - from .transports.base import RegionUrlMapsTransport, DEFAULT_CLIENT_INFO from .transports.rest import RegionUrlMapsRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, RegionUrlMapsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -360,7 +357,6 @@ def delete( This corresponds to the ``url_map`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -412,10 +408,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteRegionUrlMapRequest): request = compute.DeleteRegionUrlMapRequest(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: @@ -471,7 +465,6 @@ def get( This corresponds to the ``url_map`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -531,10 +524,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetRegionUrlMapRequest): request = compute.GetRegionUrlMapRequest(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: @@ -588,7 +579,6 @@ def insert( This corresponds to the ``url_map_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. @@ -640,10 +630,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertRegionUrlMapRequest): request = compute.InsertRegionUrlMapRequest(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: @@ -691,7 +679,6 @@ def list( 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. @@ -722,10 +709,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListRegionUrlMapsRequest): request = compute.ListRegionUrlMapsRequest(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: @@ -791,7 +776,6 @@ def patch( This corresponds to the ``url_map_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. @@ -843,10 +827,8 @@ def patch( # there are no flattened fields. if not isinstance(request, compute.PatchRegionUrlMapRequest): request = compute.PatchRegionUrlMapRequest(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: @@ -910,7 +892,6 @@ def update( This corresponds to the ``url_map_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. @@ -962,10 +943,8 @@ def update( # there are no flattened fields. if not isinstance(request, compute.UpdateRegionUrlMapRequest): request = compute.UpdateRegionUrlMapRequest(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: @@ -1030,7 +1009,6 @@ def validate( This corresponds to the ``region_url_maps_validate_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. @@ -1059,10 +1037,8 @@ def validate( # there are no flattened fields. if not isinstance(request, compute.ValidateRegionUrlMapRequest): request = compute.ValidateRegionUrlMapRequest(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: diff --git a/google/cloud/compute_v1/services/region_url_maps/pagers.py b/google/cloud/compute_v1/services/region_url_maps/pagers.py index 132a85b4a..c71549e26 100644 --- a/google/cloud/compute_v1/services/region_url_maps/pagers.py +++ b/google/cloud/compute_v1/services/region_url_maps/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/region_url_maps/transports/__init__.py b/google/cloud/compute_v1/services/region_url_maps/transports/__init__.py index 479e5520f..b3a88db45 100644 --- a/google/cloud/compute_v1/services/region_url_maps/transports/__init__.py +++ b/google/cloud/compute_v1/services/region_url_maps/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/region_url_maps/transports/base.py b/google/cloud/compute_v1/services/region_url_maps/transports/base.py index c5503d640..c35069186 100644 --- a/google/cloud/compute_v1/services/region_url_maps/transports/base.py +++ b/google/cloud/compute_v1/services/region_url_maps/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class RegionUrlMapsTransport(abc.ABC): """Abstract transport class for RegionUrlMaps.""" @@ -44,21 +54,24 @@ class RegionUrlMapsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -133,65 +193,64 @@ def _prep_wrapped_messages(self, client_info): @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteRegionUrlMapRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetRegionUrlMapRequest], - typing.Union[compute.UrlMap, typing.Awaitable[compute.UrlMap]], + Union[compute.UrlMap, Awaitable[compute.UrlMap]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertRegionUrlMapRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListRegionUrlMapsRequest], - typing.Union[compute.UrlMapList, typing.Awaitable[compute.UrlMapList]], + Union[compute.UrlMapList, Awaitable[compute.UrlMapList]], ]: raise NotImplementedError() @property def patch( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchRegionUrlMapRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def update( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.UpdateRegionUrlMapRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def validate( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ValidateRegionUrlMapRequest], - typing.Union[ - compute.UrlMapsValidateResponse, - typing.Awaitable[compute.UrlMapsValidateResponse], + Union[ + compute.UrlMapsValidateResponse, Awaitable[compute.UrlMapsValidateResponse] ], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/region_url_maps/transports/rest.py b/google/cloud/compute_v1/services/region_url_maps/transports/rest.py index 1a57cfdce..5f8fbc185 100644 --- a/google/cloud/compute_v1/services/region_url_maps/transports/rest.py +++ b/google/cloud/compute_v1/services/region_url_maps/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 RegionUrlMapsTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def delete( Args: request (~.compute.DeleteRegionUrlMapRequest): - The request object. - A request message for + The request object. A request message for RegionUrlMaps.Delete. See the method description for details. @@ -155,19 +154,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteRegionUrlMapRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -185,8 +183,7 @@ def get( Args: request (~.compute.GetRegionUrlMapRequest): - The request object. - A request message for + The request object. A request message for RegionUrlMaps.Get. See the method description for details. @@ -242,16 +239,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -269,8 +265,7 @@ def insert( Args: request (~.compute.InsertRegionUrlMapRequest): - The request object. - A request message for + The request object. A request message for RegionUrlMaps.Insert. See the method description for details. @@ -325,15 +320,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertRegionUrlMapRequest.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() if v - ] + 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 @@ -355,8 +349,7 @@ def list( Args: request (~.compute.ListRegionUrlMapsRequest): - The request object. - A request message for + The request object. A request message for RegionUrlMaps.List. See the method description for details. @@ -376,23 +369,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListRegionUrlMapsRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListRegionUrlMapsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListRegionUrlMapsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListRegionUrlMapsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListRegionUrlMapsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -412,8 +408,7 @@ def patch( Args: request (~.compute.PatchRegionUrlMapRequest): - The request object. - A request message for + The request object. A request message for RegionUrlMaps.Patch. See the method description for details. @@ -471,15 +466,14 @@ def patch( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.PatchRegionUrlMapRequest.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() if v - ] + 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 @@ -501,8 +495,7 @@ def update( Args: request (~.compute.UpdateRegionUrlMapRequest): - The request object. - A request message for + The request object. A request message for RegionUrlMaps.Update. See the method description for details. @@ -560,15 +553,14 @@ def update( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.UpdateRegionUrlMapRequest.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() if v - ] + 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 @@ -590,8 +582,7 @@ def validate( Args: request (~.compute.ValidateRegionUrlMapRequest): - The request object. - A request message for + The request object. A request message for RegionUrlMaps.Validate. See the method description for details. @@ -622,12 +613,11 @@ def validate( # 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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/regions/__init__.py b/google/cloud/compute_v1/services/regions/__init__.py index 2ca254cbb..17a96fa8e 100644 --- a/google/cloud/compute_v1/services/regions/__init__.py +++ b/google/cloud/compute_v1/services/regions/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import RegionsClient __all__ = ("RegionsClient",) diff --git a/google/cloud/compute_v1/services/regions/client.py b/google/cloud/compute_v1/services/regions/client.py index 9213cbb0b..6b2436eea 100644 --- a/google/cloud/compute_v1/services/regions/client.py +++ b/google/cloud/compute_v1/services/regions/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.regions import pagers from google.cloud.compute_v1.types import compute - from .transports.base import RegionsTransport, DEFAULT_CLIENT_INFO from .transports.rest import RegionsRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, RegionsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -352,7 +349,6 @@ def get( 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. @@ -384,10 +380,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetRegionRequest): request = compute.GetRegionRequest(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: @@ -424,7 +418,6 @@ def list( 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. @@ -455,10 +448,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListRegionsRequest): request = compute.ListRegionsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project diff --git a/google/cloud/compute_v1/services/regions/pagers.py b/google/cloud/compute_v1/services/regions/pagers.py index 6e0a595aa..1af84b165 100644 --- a/google/cloud/compute_v1/services/regions/pagers.py +++ b/google/cloud/compute_v1/services/regions/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/regions/transports/__init__.py b/google/cloud/compute_v1/services/regions/transports/__init__.py index 4ec9728e5..b8dc86462 100644 --- a/google/cloud/compute_v1/services/regions/transports/__init__.py +++ b/google/cloud/compute_v1/services/regions/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/regions/transports/base.py b/google/cloud/compute_v1/services/regions/transports/base.py index 2e017b263..59b2663fd 100644 --- a/google/cloud/compute_v1/services/regions/transports/base.py +++ b/google/cloud/compute_v1/services/regions/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class RegionsTransport(abc.ABC): """Abstract transport class for Regions.""" @@ -45,21 +55,24 @@ class RegionsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -68,13 +81,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -82,28 +95,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -119,18 +179,17 @@ def _prep_wrapped_messages(self, client_info): @property def get( self, - ) -> typing.Callable[ - [compute.GetRegionRequest], - typing.Union[compute.Region, typing.Awaitable[compute.Region]], + ) -> Callable[ + [compute.GetRegionRequest], Union[compute.Region, Awaitable[compute.Region]] ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListRegionsRequest], - typing.Union[compute.RegionList, typing.Awaitable[compute.RegionList]], + Union[compute.RegionList, Awaitable[compute.RegionList]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/regions/transports/rest.py b/google/cloud/compute_v1/services/regions/transports/rest.py index 616b3ddd4..609d29097 100644 --- a/google/cloud/compute_v1/services/regions/transports/rest.py +++ b/google/cloud/compute_v1/services/regions/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 RegionsTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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 get( self, @@ -103,8 +103,7 @@ def get( Args: request (~.compute.GetRegionRequest): - The request object. - A request message for Regions.Get. + The request object. A request message for Regions.Get. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -129,16 +128,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -156,8 +154,7 @@ def list( Args: request (~.compute.ListRegionsRequest): - The request object. - A request message for Regions.List. + The request object. A request message for Regions.List. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -176,23 +173,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListRegionsRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListRegionsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListRegionsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListRegionsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListRegionsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() diff --git a/google/cloud/compute_v1/services/reservations/__init__.py b/google/cloud/compute_v1/services/reservations/__init__.py index fa3715407..163eafc8b 100644 --- a/google/cloud/compute_v1/services/reservations/__init__.py +++ b/google/cloud/compute_v1/services/reservations/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import ReservationsClient __all__ = ("ReservationsClient",) diff --git a/google/cloud/compute_v1/services/reservations/client.py b/google/cloud/compute_v1/services/reservations/client.py index 0db7fb897..679f436b2 100644 --- a/google/cloud/compute_v1/services/reservations/client.py +++ b/google/cloud/compute_v1/services/reservations/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.reservations import pagers from google.cloud.compute_v1.types import compute - from .transports.base import ReservationsTransport, DEFAULT_CLIENT_INFO from .transports.rest import ReservationsRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ReservationsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -344,7 +341,6 @@ def aggregated_list( 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. @@ -375,10 +371,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListReservationsRequest): request = compute.AggregatedListReservationsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -431,7 +425,6 @@ def delete( This corresponds to the ``reservation`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -483,10 +476,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteReservationRequest): request = compute.DeleteReservationRequest(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: @@ -538,7 +529,6 @@ def get( This corresponds to the ``reservation`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -570,10 +560,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetReservationRequest): request = compute.GetReservationRequest(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: @@ -629,7 +617,6 @@ def get_iam_policy( 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. @@ -707,10 +694,8 @@ def get_iam_policy( # there are no flattened fields. if not isinstance(request, compute.GetIamPolicyReservationRequest): request = compute.GetIamPolicyReservationRequest(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: @@ -762,7 +747,6 @@ def insert( This corresponds to the ``reservation_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. @@ -814,10 +798,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertReservationRequest): request = compute.InsertReservationRequest(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: @@ -863,7 +845,6 @@ def list( This corresponds to the ``zone`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -893,10 +874,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListReservationsRequest): request = compute.ListReservationsRequest(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: @@ -959,7 +938,6 @@ def resize( This corresponds to the ``reservations_resize_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. @@ -1013,10 +991,8 @@ def resize( # there are no flattened fields. if not isinstance(request, compute.ResizeReservationRequest): request = compute.ResizeReservationRequest(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: @@ -1082,7 +1058,6 @@ def set_iam_policy( This corresponds to the ``zone_set_policy_request_resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1162,10 +1137,8 @@ def set_iam_policy( # there are no flattened fields. if not isinstance(request, compute.SetIamPolicyReservationRequest): request = compute.SetIamPolicyReservationRequest(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: @@ -1231,7 +1204,6 @@ def test_iam_permissions( 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. @@ -1260,10 +1232,8 @@ def test_iam_permissions( # there are no flattened fields. if not isinstance(request, compute.TestIamPermissionsReservationRequest): request = compute.TestIamPermissionsReservationRequest(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: diff --git a/google/cloud/compute_v1/services/reservations/pagers.py b/google/cloud/compute_v1/services/reservations/pagers.py index bf1275a2a..a8f5361a3 100644 --- a/google/cloud/compute_v1/services/reservations/pagers.py +++ b/google/cloud/compute_v1/services/reservations/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/reservations/transports/__init__.py b/google/cloud/compute_v1/services/reservations/transports/__init__.py index 7eb5d4487..6b420ae77 100644 --- a/google/cloud/compute_v1/services/reservations/transports/__init__.py +++ b/google/cloud/compute_v1/services/reservations/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/reservations/transports/base.py b/google/cloud/compute_v1/services/reservations/transports/base.py index d2c545d2d..fead04fa4 100644 --- a/google/cloud/compute_v1/services/reservations/transports/base.py +++ b/google/cloud/compute_v1/services/reservations/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class ReservationsTransport(abc.ABC): """Abstract transport class for Reservations.""" @@ -44,21 +54,24 @@ class ReservationsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -141,11 +201,11 @@ def _prep_wrapped_messages(self, client_info): @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListReservationsRequest], - typing.Union[ + Union[ compute.ReservationAggregatedList, - typing.Awaitable[compute.ReservationAggregatedList], + Awaitable[compute.ReservationAggregatedList], ], ]: raise NotImplementedError() @@ -153,76 +213,73 @@ def aggregated_list( @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteReservationRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetReservationRequest], - typing.Union[compute.Reservation, typing.Awaitable[compute.Reservation]], + Union[compute.Reservation, Awaitable[compute.Reservation]], ]: raise NotImplementedError() @property def get_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetIamPolicyReservationRequest], - typing.Union[compute.Policy, typing.Awaitable[compute.Policy]], + Union[compute.Policy, Awaitable[compute.Policy]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertReservationRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListReservationsRequest], - typing.Union[ - compute.ReservationList, typing.Awaitable[compute.ReservationList] - ], + Union[compute.ReservationList, Awaitable[compute.ReservationList]], ]: raise NotImplementedError() @property def resize( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ResizeReservationRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetIamPolicyReservationRequest], - typing.Union[compute.Policy, typing.Awaitable[compute.Policy]], + Union[compute.Policy, Awaitable[compute.Policy]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.TestIamPermissionsReservationRequest], - typing.Union[ - compute.TestPermissionsResponse, - typing.Awaitable[compute.TestPermissionsResponse], + Union[ + compute.TestPermissionsResponse, Awaitable[compute.TestPermissionsResponse] ], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/reservations/transports/rest.py b/google/cloud/compute_v1/services/reservations/transports/rest.py index 29119aeec..806ea2cc5 100644 --- a/google/cloud/compute_v1/services/reservations/transports/rest.py +++ b/google/cloud/compute_v1/services/reservations/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 ReservationsTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListReservationsRequest): - The request object. - A request message for + The request object. A request message for Reservations.AggregatedList. See the method description for details. @@ -124,24 +123,28 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListReservationsRequest.filter in request: + query_params["filter"] = request.filter + if compute.AggregatedListReservationsRequest.include_all_scopes in request: + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListReservationsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListReservationsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListReservationsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.AggregatedListReservationsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -161,8 +164,7 @@ def delete( Args: request (~.compute.DeleteReservationRequest): - The request object. - A request message for + The request object. A request message for Reservations.Delete. See the method description for details. @@ -213,19 +215,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteReservationRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -243,8 +244,7 @@ def get( Args: request (~.compute.GetReservationRequest): - The request object. - A request message for + The request object. A request message for Reservations.Get. See the method description for details. @@ -273,16 +273,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -302,8 +301,7 @@ def get_iam_policy( Args: request (~.compute.GetIamPolicyReservationRequest): - The request object. - A request message for + The request object. A request message for Reservations.GetIamPolicy. See the method description for details. @@ -376,19 +374,23 @@ def get_iam_policy( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "optionsRequestedPolicyVersion": request.options_requested_policy_version, - } + query_params = {} + if ( + compute.GetIamPolicyReservationRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -406,8 +408,7 @@ def insert( Args: request (~.compute.InsertReservationRequest): - The request object. - A request message for + The request object. A request message for Reservations.Insert. See the method description for details. @@ -462,15 +463,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertReservationRequest.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() if v - ] + 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 @@ -492,8 +492,7 @@ def list( Args: request (~.compute.ListReservationsRequest): - The request object. - A request message for + The request object. A request message for Reservations.List. See the method description for details. @@ -513,23 +512,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListReservationsRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListReservationsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListReservationsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListReservationsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListReservationsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -549,8 +551,7 @@ def resize( Args: request (~.compute.ResizeReservationRequest): - The request object. - A request message for + The request object. A request message for Reservations.Resize. See the method description for details. @@ -608,15 +609,14 @@ def resize( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.ResizeReservationRequest.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() if v - ] + 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 @@ -638,8 +638,7 @@ def set_iam_policy( Args: request (~.compute.SetIamPolicyReservationRequest): - The request object. - A request message for + The request object. A request message for Reservations.SetIamPolicy. See the method description for details. @@ -720,12 +719,11 @@ def set_iam_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() if v - ] + 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 @@ -747,8 +745,7 @@ def test_iam_permissions( Args: request (~.compute.TestIamPermissionsReservationRequest): - The request object. - A request message for + The request object. A request message for Reservations.TestIamPermissions. See the method description for details. @@ -779,12 +776,11 @@ def test_iam_permissions( # 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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/resource_policies/__init__.py b/google/cloud/compute_v1/services/resource_policies/__init__.py index f835f313c..0855f682e 100644 --- a/google/cloud/compute_v1/services/resource_policies/__init__.py +++ b/google/cloud/compute_v1/services/resource_policies/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import ResourcePoliciesClient __all__ = ("ResourcePoliciesClient",) diff --git a/google/cloud/compute_v1/services/resource_policies/client.py b/google/cloud/compute_v1/services/resource_policies/client.py index e9e02fcce..3c3b394de 100644 --- a/google/cloud/compute_v1/services/resource_policies/client.py +++ b/google/cloud/compute_v1/services/resource_policies/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.resource_policies import pagers from google.cloud.compute_v1.types import compute - from .transports.base import ResourcePoliciesTransport, DEFAULT_CLIENT_INFO from .transports.rest import ResourcePoliciesRestTransport @@ -215,7 +212,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ResourcePoliciesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -346,7 +343,6 @@ def aggregated_list( 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. @@ -377,10 +373,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListResourcePoliciesRequest): request = compute.AggregatedListResourcePoliciesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -435,7 +429,6 @@ def delete( This corresponds to the ``resource_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. @@ -487,10 +480,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteResourcePolicyRequest): request = compute.DeleteResourcePolicyRequest(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: @@ -544,7 +535,6 @@ def get( This corresponds to the ``resource_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. @@ -577,10 +567,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetResourcePolicyRequest): request = compute.GetResourcePolicyRequest(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: @@ -636,7 +624,6 @@ def get_iam_policy( 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. @@ -714,10 +701,8 @@ def get_iam_policy( # there are no flattened fields. if not isinstance(request, compute.GetIamPolicyResourcePolicyRequest): request = compute.GetIamPolicyResourcePolicyRequest(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: @@ -768,7 +753,6 @@ def insert( This corresponds to the ``resource_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. @@ -820,10 +804,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertResourcePolicyRequest): request = compute.InsertResourcePolicyRequest(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: @@ -870,7 +852,6 @@ def list( 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. @@ -900,10 +881,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListResourcePoliciesRequest): request = compute.ListResourcePoliciesRequest(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: @@ -969,7 +948,6 @@ def set_iam_policy( This corresponds to the ``region_set_policy_request_resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1049,10 +1027,8 @@ def set_iam_policy( # there are no flattened fields. if not isinstance(request, compute.SetIamPolicyResourcePolicyRequest): request = compute.SetIamPolicyResourcePolicyRequest(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: @@ -1118,7 +1094,6 @@ def test_iam_permissions( 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. @@ -1147,10 +1122,8 @@ def test_iam_permissions( # there are no flattened fields. if not isinstance(request, compute.TestIamPermissionsResourcePolicyRequest): request = compute.TestIamPermissionsResourcePolicyRequest(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: diff --git a/google/cloud/compute_v1/services/resource_policies/pagers.py b/google/cloud/compute_v1/services/resource_policies/pagers.py index 79376d997..7cc063099 100644 --- a/google/cloud/compute_v1/services/resource_policies/pagers.py +++ b/google/cloud/compute_v1/services/resource_policies/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/resource_policies/transports/__init__.py b/google/cloud/compute_v1/services/resource_policies/transports/__init__.py index a74a385b4..0de235b42 100644 --- a/google/cloud/compute_v1/services/resource_policies/transports/__init__.py +++ b/google/cloud/compute_v1/services/resource_policies/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/resource_policies/transports/base.py b/google/cloud/compute_v1/services/resource_policies/transports/base.py index 24ec025ef..d1317d007 100644 --- a/google/cloud/compute_v1/services/resource_policies/transports/base.py +++ b/google/cloud/compute_v1/services/resource_policies/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class ResourcePoliciesTransport(abc.ABC): """Abstract transport class for ResourcePolicies.""" @@ -44,21 +54,24 @@ class ResourcePoliciesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -138,11 +198,11 @@ def _prep_wrapped_messages(self, client_info): @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListResourcePoliciesRequest], - typing.Union[ + Union[ compute.ResourcePolicyAggregatedList, - typing.Awaitable[compute.ResourcePolicyAggregatedList], + Awaitable[compute.ResourcePolicyAggregatedList], ], ]: raise NotImplementedError() @@ -150,67 +210,64 @@ def aggregated_list( @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteResourcePolicyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetResourcePolicyRequest], - typing.Union[compute.ResourcePolicy, typing.Awaitable[compute.ResourcePolicy]], + Union[compute.ResourcePolicy, Awaitable[compute.ResourcePolicy]], ]: raise NotImplementedError() @property def get_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetIamPolicyResourcePolicyRequest], - typing.Union[compute.Policy, typing.Awaitable[compute.Policy]], + Union[compute.Policy, Awaitable[compute.Policy]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertResourcePolicyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListResourcePoliciesRequest], - typing.Union[ - compute.ResourcePolicyList, typing.Awaitable[compute.ResourcePolicyList] - ], + Union[compute.ResourcePolicyList, Awaitable[compute.ResourcePolicyList]], ]: raise NotImplementedError() @property def set_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetIamPolicyResourcePolicyRequest], - typing.Union[compute.Policy, typing.Awaitable[compute.Policy]], + Union[compute.Policy, Awaitable[compute.Policy]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.TestIamPermissionsResourcePolicyRequest], - typing.Union[ - compute.TestPermissionsResponse, - typing.Awaitable[compute.TestPermissionsResponse], + Union[ + compute.TestPermissionsResponse, Awaitable[compute.TestPermissionsResponse] ], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/resource_policies/transports/rest.py b/google/cloud/compute_v1/services/resource_policies/transports/rest.py index 805ab2ae4..c69a57e67 100644 --- a/google/cloud/compute_v1/services/resource_policies/transports/rest.py +++ b/google/cloud/compute_v1/services/resource_policies/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 ResourcePoliciesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListResourcePoliciesRequest): - The request object. - A request message for + The request object. A request message for ResourcePolicies.AggregatedList. See the method description for details. @@ -124,24 +123,31 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListResourcePoliciesRequest.filter in request: + query_params["filter"] = request.filter + if compute.AggregatedListResourcePoliciesRequest.include_all_scopes in request: + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListResourcePoliciesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListResourcePoliciesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListResourcePoliciesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if ( + compute.AggregatedListResourcePoliciesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -161,8 +167,7 @@ def delete( Args: request (~.compute.DeleteResourcePolicyRequest): - The request object. - A request message for + The request object. A request message for ResourcePolicies.Delete. See the method description for details. @@ -213,19 +218,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteResourcePolicyRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -243,8 +247,7 @@ def get( Args: request (~.compute.GetResourcePolicyRequest): - The request object. - A request message for + The request object. A request message for ResourcePolicies.Get. See the method description for details. @@ -274,16 +277,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -303,8 +305,7 @@ def get_iam_policy( Args: request (~.compute.GetIamPolicyResourcePolicyRequest): - The request object. - A request message for + The request object. A request message for ResourcePolicies.GetIamPolicy. See the method description for details. @@ -377,19 +378,23 @@ def get_iam_policy( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "optionsRequestedPolicyVersion": request.options_requested_policy_version, - } + query_params = {} + if ( + compute.GetIamPolicyResourcePolicyRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -407,8 +412,7 @@ def insert( Args: request (~.compute.InsertResourcePolicyRequest): - The request object. - A request message for + The request object. A request message for ResourcePolicies.Insert. See the method description for details. @@ -463,15 +467,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertResourcePolicyRequest.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() if v - ] + 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 @@ -493,8 +496,7 @@ def list( Args: request (~.compute.ListResourcePoliciesRequest): - The request object. - A request message for + The request object. A request message for ResourcePolicies.List. See the method description for details. @@ -514,23 +516,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListResourcePoliciesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListResourcePoliciesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListResourcePoliciesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListResourcePoliciesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListResourcePoliciesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -550,8 +555,7 @@ def set_iam_policy( Args: request (~.compute.SetIamPolicyResourcePolicyRequest): - The request object. - A request message for + The request object. A request message for ResourcePolicies.SetIamPolicy. See the method description for details. @@ -632,12 +636,11 @@ def set_iam_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() if v - ] + 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 @@ -659,8 +662,7 @@ def test_iam_permissions( Args: request (~.compute.TestIamPermissionsResourcePolicyRequest): - The request object. - A request message for + The request object. A request message for ResourcePolicies.TestIamPermissions. See the method description for details. @@ -691,12 +693,11 @@ def test_iam_permissions( # 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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/routers/__init__.py b/google/cloud/compute_v1/services/routers/__init__.py index 0cabbc71b..20822d2bf 100644 --- a/google/cloud/compute_v1/services/routers/__init__.py +++ b/google/cloud/compute_v1/services/routers/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import RoutersClient __all__ = ("RoutersClient",) diff --git a/google/cloud/compute_v1/services/routers/client.py b/google/cloud/compute_v1/services/routers/client.py index e7f60dc33..a5f5a35d4 100644 --- a/google/cloud/compute_v1/services/routers/client.py +++ b/google/cloud/compute_v1/services/routers/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.routers import pagers from google.cloud.compute_v1.types import compute - from .transports.base import RoutersTransport, DEFAULT_CLIENT_INFO from .transports.rest import RoutersRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, RoutersTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -344,7 +341,6 @@ def aggregated_list( 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. @@ -375,10 +371,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListRoutersRequest): request = compute.AggregatedListRoutersRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -432,7 +426,6 @@ def delete( This corresponds to the ``router`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -484,10 +477,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteRouterRequest): request = compute.DeleteRouterRequest(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: @@ -540,7 +531,6 @@ def get( This corresponds to the ``router`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -570,10 +560,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetRouterRequest): request = compute.GetRouterRequest(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: @@ -628,7 +616,6 @@ def get_nat_mapping_info( This corresponds to the ``router`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -660,10 +647,8 @@ def get_nat_mapping_info( # there are no flattened fields. if not isinstance(request, compute.GetNatMappingInfoRoutersRequest): request = compute.GetNatMappingInfoRoutersRequest(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: @@ -721,7 +706,6 @@ def get_router_status( This corresponds to the ``router`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -748,10 +732,8 @@ def get_router_status( # there are no flattened fields. if not isinstance(request, compute.GetRouterStatusRouterRequest): request = compute.GetRouterStatusRouterRequest(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: @@ -802,7 +784,6 @@ def insert( This corresponds to the ``router_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. @@ -854,10 +835,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertRouterRequest): request = compute.InsertRouterRequest(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: @@ -902,7 +881,6 @@ def list( 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. @@ -933,10 +911,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListRoutersRequest): request = compute.ListRoutersRequest(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: @@ -999,7 +975,6 @@ def patch( This corresponds to the ``router_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. @@ -1051,10 +1026,8 @@ def patch( # there are no flattened fields. if not isinstance(request, compute.PatchRouterRequest): request = compute.PatchRouterRequest(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: @@ -1114,7 +1087,6 @@ def preview( This corresponds to the ``router_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. @@ -1141,10 +1113,8 @@ def preview( # there are no flattened fields. if not isinstance(request, compute.PreviewRouterRequest): request = compute.PreviewRouterRequest(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: @@ -1209,7 +1179,6 @@ def update( This corresponds to the ``router_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. @@ -1261,10 +1230,8 @@ def update( # there are no flattened fields. if not isinstance(request, compute.UpdateRouterRequest): request = compute.UpdateRouterRequest(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: diff --git a/google/cloud/compute_v1/services/routers/pagers.py b/google/cloud/compute_v1/services/routers/pagers.py index d342a7bc2..fbfba1403 100644 --- a/google/cloud/compute_v1/services/routers/pagers.py +++ b/google/cloud/compute_v1/services/routers/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/routers/transports/__init__.py b/google/cloud/compute_v1/services/routers/transports/__init__.py index 9ea6d4a0c..52ae7eb7c 100644 --- a/google/cloud/compute_v1/services/routers/transports/__init__.py +++ b/google/cloud/compute_v1/services/routers/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/routers/transports/base.py b/google/cloud/compute_v1/services/routers/transports/base.py index 33aee1dd6..df2f3e078 100644 --- a/google/cloud/compute_v1/services/routers/transports/base.py +++ b/google/cloud/compute_v1/services/routers/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class RoutersTransport(abc.ABC): """Abstract transport class for Routers.""" @@ -44,21 +54,24 @@ class RoutersTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -144,40 +204,37 @@ def _prep_wrapped_messages(self, client_info): @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListRoutersRequest], - typing.Union[ - compute.RouterAggregatedList, typing.Awaitable[compute.RouterAggregatedList] - ], + Union[compute.RouterAggregatedList, Awaitable[compute.RouterAggregatedList]], ]: raise NotImplementedError() @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteRouterRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ - [compute.GetRouterRequest], - typing.Union[compute.Router, typing.Awaitable[compute.Router]], + ) -> Callable[ + [compute.GetRouterRequest], Union[compute.Router, Awaitable[compute.Router]] ]: raise NotImplementedError() @property def get_nat_mapping_info( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetNatMappingInfoRoutersRequest], - typing.Union[ + Union[ compute.VmEndpointNatMappingsList, - typing.Awaitable[compute.VmEndpointNatMappingsList], + Awaitable[compute.VmEndpointNatMappingsList], ], ]: raise NotImplementedError() @@ -185,49 +242,46 @@ def get_nat_mapping_info( @property def get_router_status( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetRouterStatusRouterRequest], - typing.Union[ - compute.RouterStatusResponse, typing.Awaitable[compute.RouterStatusResponse] - ], + Union[compute.RouterStatusResponse, Awaitable[compute.RouterStatusResponse]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertRouterRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListRoutersRequest], - typing.Union[compute.RouterList, typing.Awaitable[compute.RouterList]], + Union[compute.RouterList, Awaitable[compute.RouterList]], ]: raise NotImplementedError() @property def patch( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchRouterRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def preview( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PreviewRouterRequest], - typing.Union[ - compute.RoutersPreviewResponse, - typing.Awaitable[compute.RoutersPreviewResponse], + Union[ + compute.RoutersPreviewResponse, Awaitable[compute.RoutersPreviewResponse] ], ]: raise NotImplementedError() @@ -235,9 +289,9 @@ def preview( @property def update( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.UpdateRouterRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/routers/transports/rest.py b/google/cloud/compute_v1/services/routers/transports/rest.py index 57f51f7ae..7e94404df 100644 --- a/google/cloud/compute_v1/services/routers/transports/rest.py +++ b/google/cloud/compute_v1/services/routers/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 RoutersTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListRoutersRequest): - The request object. - A request message for + The request object. A request message for Routers.AggregatedList. See the method description for details. @@ -124,24 +123,28 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListRoutersRequest.filter in request: + query_params["filter"] = request.filter + if compute.AggregatedListRoutersRequest.include_all_scopes in request: + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListRoutersRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListRoutersRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListRoutersRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.AggregatedListRoutersRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -161,8 +164,7 @@ def delete( Args: request (~.compute.DeleteRouterRequest): - The request object. - A request message for Routers.Delete. + The request object. A request message for Routers.Delete. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -212,19 +214,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteRouterRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -242,8 +243,7 @@ def get( Args: request (~.compute.GetRouterRequest): - The request object. - A request message for Routers.Get. + The request object. A request message for Routers.Get. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -269,16 +269,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -296,8 +295,7 @@ def get_nat_mapping_info( Args: request (~.compute.GetNatMappingInfoRoutersRequest): - The request object. - A request message for + The request object. A request message for Routers.GetNatMappingInfo. See the method description for details. @@ -322,23 +320,26 @@ def get_nat_mapping_info( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.GetNatMappingInfoRoutersRequest.filter in request: + query_params["filter"] = request.filter + if compute.GetNatMappingInfoRoutersRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.GetNatMappingInfoRoutersRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.GetNatMappingInfoRoutersRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.GetNatMappingInfoRoutersRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -358,8 +359,7 @@ def get_router_status( Args: request (~.compute.GetRouterStatusRouterRequest): - The request object. - A request message for + The request object. A request message for Routers.GetRouterStatus. See the method description for details. @@ -383,16 +383,15 @@ def get_router_status( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -412,8 +411,7 @@ def insert( Args: request (~.compute.InsertRouterRequest): - The request object. - A request message for Routers.Insert. + The request object. A request message for Routers.Insert. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -467,15 +465,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertRouterRequest.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() if v - ] + 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 @@ -497,8 +494,7 @@ def list( Args: request (~.compute.ListRoutersRequest): - The request object. - A request message for Routers.List. + The request object. A request message for Routers.List. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -517,23 +513,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListRoutersRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListRoutersRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListRoutersRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListRoutersRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListRoutersRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -553,8 +552,7 @@ def patch( Args: request (~.compute.PatchRouterRequest): - The request object. - A request message for Routers.Patch. + The request object. A request message for Routers.Patch. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -611,15 +609,14 @@ def patch( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.PatchRouterRequest.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() if v - ] + 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 @@ -641,8 +638,7 @@ def preview( Args: request (~.compute.PreviewRouterRequest): - The request object. - A request message for + The request object. A request message for Routers.Preview. See the method description for details. @@ -673,12 +669,11 @@ def preview( # 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() if v - ] + 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 @@ -702,8 +697,7 @@ def update( Args: request (~.compute.UpdateRouterRequest): - The request object. - A request message for Routers.Update. + The request object. A request message for Routers.Update. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -760,15 +754,14 @@ def update( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.UpdateRouterRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/routes/__init__.py b/google/cloud/compute_v1/services/routes/__init__.py index e5dc7ca29..56ee93732 100644 --- a/google/cloud/compute_v1/services/routes/__init__.py +++ b/google/cloud/compute_v1/services/routes/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import RoutesClient __all__ = ("RoutesClient",) diff --git a/google/cloud/compute_v1/services/routes/client.py b/google/cloud/compute_v1/services/routes/client.py index fa662b7a5..71867bee0 100644 --- a/google/cloud/compute_v1/services/routes/client.py +++ b/google/cloud/compute_v1/services/routes/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.routes import pagers from google.cloud.compute_v1.types import compute - from .transports.base import RoutesTransport, DEFAULT_CLIENT_INFO from .transports.rest import RoutesRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, RoutesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -349,7 +346,6 @@ def delete( This corresponds to the ``route`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -401,10 +397,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteRouteRequest): request = compute.DeleteRouteRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if route is not None: @@ -447,7 +441,6 @@ def get( This corresponds to the ``route`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -481,10 +474,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetRouteRequest): request = compute.GetRouteRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if route is not None: @@ -527,7 +518,6 @@ def insert( This corresponds to the ``route_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. @@ -579,10 +569,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertRouteRequest): request = compute.InsertRouteRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if route_resource is not None: @@ -619,7 +607,6 @@ def list( 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. @@ -650,10 +637,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListRoutesRequest): request = compute.ListRoutesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project diff --git a/google/cloud/compute_v1/services/routes/pagers.py b/google/cloud/compute_v1/services/routes/pagers.py index 4975a5332..4d998556a 100644 --- a/google/cloud/compute_v1/services/routes/pagers.py +++ b/google/cloud/compute_v1/services/routes/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/routes/transports/__init__.py b/google/cloud/compute_v1/services/routes/transports/__init__.py index c2f448299..61e276e8e 100644 --- a/google/cloud/compute_v1/services/routes/transports/__init__.py +++ b/google/cloud/compute_v1/services/routes/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/routes/transports/base.py b/google/cloud/compute_v1/services/routes/transports/base.py index 4c188bbc2..6b6c6d84c 100644 --- a/google/cloud/compute_v1/services/routes/transports/base.py +++ b/google/cloud/compute_v1/services/routes/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class RoutesTransport(abc.ABC): """Abstract transport class for Routes.""" @@ -44,21 +54,24 @@ class RoutesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -124,36 +184,35 @@ def _prep_wrapped_messages(self, client_info): @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteRouteRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ - [compute.GetRouteRequest], - typing.Union[compute.Route, typing.Awaitable[compute.Route]], + ) -> Callable[ + [compute.GetRouteRequest], Union[compute.Route, Awaitable[compute.Route]] ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertRouteRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListRoutesRequest], - typing.Union[compute.RouteList, typing.Awaitable[compute.RouteList]], + Union[compute.RouteList, Awaitable[compute.RouteList]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/routes/transports/rest.py b/google/cloud/compute_v1/services/routes/transports/rest.py index 51aef96c4..a0f4f9d52 100644 --- a/google/cloud/compute_v1/services/routes/transports/rest.py +++ b/google/cloud/compute_v1/services/routes/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 RoutesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def delete( Args: request (~.compute.DeleteRouteRequest): - The request object. - A request message for Routes.Delete. + The request object. A request message for Routes.Delete. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -151,19 +150,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteRouteRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -181,8 +179,7 @@ def get( Args: request (~.compute.GetRouteRequest): - The request object. - A request message for Routes.Get. See + The request object. A request message for Routes.Get. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -209,16 +206,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -236,8 +232,7 @@ def insert( Args: request (~.compute.InsertRouteRequest): - The request object. - A request message for Routes.Insert. + The request object. A request message for Routes.Insert. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -291,15 +286,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertRouteRequest.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() if v - ] + 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 @@ -321,8 +315,7 @@ def list( Args: request (~.compute.ListRoutesRequest): - The request object. - A request message for Routes.List. + The request object. A request message for Routes.List. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -341,23 +334,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListRoutesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListRoutesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListRoutesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListRoutesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListRoutesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() diff --git a/google/cloud/compute_v1/services/security_policies/__init__.py b/google/cloud/compute_v1/services/security_policies/__init__.py index 6d1f5feb7..9f7da93a3 100644 --- a/google/cloud/compute_v1/services/security_policies/__init__.py +++ b/google/cloud/compute_v1/services/security_policies/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import SecurityPoliciesClient __all__ = ("SecurityPoliciesClient",) diff --git a/google/cloud/compute_v1/services/security_policies/client.py b/google/cloud/compute_v1/services/security_policies/client.py index 17356c0e9..7957504ec 100644 --- a/google/cloud/compute_v1/services/security_policies/client.py +++ b/google/cloud/compute_v1/services/security_policies/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.security_policies import pagers from google.cloud.compute_v1.types import compute - from .transports.base import SecurityPoliciesTransport, DEFAULT_CLIENT_INFO from .transports.rest import SecurityPoliciesRestTransport @@ -215,7 +212,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, SecurityPoliciesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -360,7 +357,6 @@ def add_rule( This corresponds to the ``security_policy_rule_resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -414,10 +410,8 @@ def add_rule( # there are no flattened fields. if not isinstance(request, compute.AddRuleSecurityPolicyRequest): request = compute.AddRuleSecurityPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if security_policy is not None: @@ -464,7 +458,6 @@ def delete( This corresponds to the ``security_policy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -516,10 +509,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteSecurityPolicyRequest): request = compute.DeleteSecurityPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if security_policy is not None: @@ -563,7 +554,6 @@ def get( This corresponds to the ``security_policy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -598,10 +588,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetSecurityPolicyRequest): request = compute.GetSecurityPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if security_policy is not None: @@ -646,7 +634,6 @@ def get_rule( This corresponds to the ``security_policy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -677,10 +664,8 @@ def get_rule( # there are no flattened fields. if not isinstance(request, compute.GetRuleSecurityPolicyRequest): request = compute.GetRuleSecurityPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if security_policy is not None: @@ -724,7 +709,6 @@ def insert( This corresponds to the ``security_policy_resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -776,10 +760,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertSecurityPolicyRequest): request = compute.InsertSecurityPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if security_policy_resource is not None: @@ -817,7 +799,6 @@ def list( 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. @@ -847,10 +828,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListSecurityPoliciesRequest): request = compute.ListSecurityPoliciesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -892,7 +871,6 @@ def list_preconfigured_expression_sets( 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. @@ -923,10 +901,8 @@ def list_preconfigured_expression_sets( request = compute.ListPreconfiguredExpressionSetsSecurityPoliciesRequest( request ) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -980,7 +956,6 @@ def patch( This corresponds to the ``security_policy_resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1032,10 +1007,8 @@ def patch( # there are no flattened fields. if not isinstance(request, compute.PatchSecurityPolicyRequest): request = compute.PatchSecurityPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if security_policy is not None: @@ -1088,7 +1061,6 @@ def patch_rule( This corresponds to the ``security_policy_rule_resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1142,10 +1114,8 @@ def patch_rule( # there are no flattened fields. if not isinstance(request, compute.PatchRuleSecurityPolicyRequest): request = compute.PatchRuleSecurityPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if security_policy is not None: @@ -1192,7 +1162,6 @@ def remove_rule( This corresponds to the ``security_policy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1244,10 +1213,8 @@ def remove_rule( # there are no flattened fields. if not isinstance(request, compute.RemoveRuleSecurityPolicyRequest): request = compute.RemoveRuleSecurityPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if security_policy is not None: diff --git a/google/cloud/compute_v1/services/security_policies/pagers.py b/google/cloud/compute_v1/services/security_policies/pagers.py index 2d5191d8f..b6062c6b6 100644 --- a/google/cloud/compute_v1/services/security_policies/pagers.py +++ b/google/cloud/compute_v1/services/security_policies/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/security_policies/transports/__init__.py b/google/cloud/compute_v1/services/security_policies/transports/__init__.py index 9483c97c5..b217d599c 100644 --- a/google/cloud/compute_v1/services/security_policies/transports/__init__.py +++ b/google/cloud/compute_v1/services/security_policies/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/security_policies/transports/base.py b/google/cloud/compute_v1/services/security_policies/transports/base.py index daa8deeaa..985a99f72 100644 --- a/google/cloud/compute_v1/services/security_policies/transports/base.py +++ b/google/cloud/compute_v1/services/security_policies/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class SecurityPoliciesTransport(abc.ABC): """Abstract transport class for SecurityPolicies.""" @@ -44,21 +54,24 @@ class SecurityPoliciesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -144,71 +204,65 @@ def _prep_wrapped_messages(self, client_info): @property def add_rule( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AddRuleSecurityPolicyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteSecurityPolicyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetSecurityPolicyRequest], - typing.Union[compute.SecurityPolicy, typing.Awaitable[compute.SecurityPolicy]], + Union[compute.SecurityPolicy, Awaitable[compute.SecurityPolicy]], ]: raise NotImplementedError() @property def get_rule( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetRuleSecurityPolicyRequest], - typing.Union[ - compute.SecurityPolicyRule, typing.Awaitable[compute.SecurityPolicyRule] - ], + Union[compute.SecurityPolicyRule, Awaitable[compute.SecurityPolicyRule]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertSecurityPolicyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListSecurityPoliciesRequest], - typing.Union[ - compute.SecurityPolicyList, typing.Awaitable[compute.SecurityPolicyList] - ], + Union[compute.SecurityPolicyList, Awaitable[compute.SecurityPolicyList]], ]: raise NotImplementedError() @property def list_preconfigured_expression_sets( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListPreconfiguredExpressionSetsSecurityPoliciesRequest], - typing.Union[ + Union[ compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse, - typing.Awaitable[ - compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse - ], + Awaitable[compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse], ], ]: raise NotImplementedError() @@ -216,27 +270,27 @@ def list_preconfigured_expression_sets( @property def patch( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchSecurityPolicyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def patch_rule( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchRuleSecurityPolicyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def remove_rule( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.RemoveRuleSecurityPolicyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/security_policies/transports/rest.py b/google/cloud/compute_v1/services/security_policies/transports/rest.py index 0446288ea..8479cb74d 100644 --- a/google/cloud/compute_v1/services/security_policies/transports/rest.py +++ b/google/cloud/compute_v1/services/security_policies/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 SecurityPoliciesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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_rule( self, @@ -103,8 +103,7 @@ def add_rule( Args: request (~.compute.AddRuleSecurityPolicyRequest): - The request object. - A request message for + The request object. A request message for SecurityPolicies.AddRule. See the method description for details. @@ -162,12 +161,11 @@ def add_rule( # 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() if v - ] + 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 @@ -189,8 +187,7 @@ def delete( Args: request (~.compute.DeleteSecurityPolicyRequest): - The request object. - A request message for + The request object. A request message for SecurityPolicies.Delete. See the method description for details. @@ -240,19 +237,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteSecurityPolicyRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -270,8 +266,7 @@ def get( Args: request (~.compute.GetSecurityPolicyRequest): - The request object. - A request message for + The request object. A request message for SecurityPolicies.Get. See the method description for details. @@ -301,16 +296,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -330,8 +324,7 @@ def get_rule( Args: request (~.compute.GetRuleSecurityPolicyRequest): - The request object. - A request message for + The request object. A request message for SecurityPolicies.GetRule. See the method description for details. @@ -357,19 +350,18 @@ def get_rule( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "priority": request.priority, - } + query_params = {} + if compute.GetRuleSecurityPolicyRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -389,8 +381,7 @@ def insert( Args: request (~.compute.InsertSecurityPolicyRequest): - The request object. - A request message for + The request object. A request message for SecurityPolicies.Insert. See the method description for details. @@ -445,15 +436,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertSecurityPolicyRequest.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() if v - ] + 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 @@ -475,8 +465,7 @@ def list( Args: request (~.compute.ListSecurityPoliciesRequest): - The request object. - A request message for + The request object. A request message for SecurityPolicies.List. See the method description for details. @@ -496,23 +485,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListSecurityPoliciesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListSecurityPoliciesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListSecurityPoliciesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListSecurityPoliciesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListSecurityPoliciesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -533,8 +525,7 @@ def list_preconfigured_expression_sets( Args: request (~.compute.ListPreconfiguredExpressionSetsSecurityPoliciesRequest): - The request object. - A request message for + The request object. A request message for SecurityPolicies.ListPreconfiguredExpressionSets. See the method description for details. @@ -554,23 +545,41 @@ def list_preconfigured_expression_sets( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if ( + compute.ListPreconfiguredExpressionSetsSecurityPoliciesRequest.filter + in request + ): + query_params["filter"] = request.filter + if ( + compute.ListPreconfiguredExpressionSetsSecurityPoliciesRequest.max_results + in request + ): + query_params["maxResults"] = request.max_results + if ( + compute.ListPreconfiguredExpressionSetsSecurityPoliciesRequest.order_by + in request + ): + query_params["orderBy"] = request.order_by + if ( + compute.ListPreconfiguredExpressionSetsSecurityPoliciesRequest.page_token + in request + ): + query_params["pageToken"] = request.page_token + if ( + compute.ListPreconfiguredExpressionSetsSecurityPoliciesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -590,8 +599,7 @@ def patch( Args: request (~.compute.PatchSecurityPolicyRequest): - The request object. - A request message for + The request object. A request message for SecurityPolicies.Patch. See the method description for details. @@ -648,15 +656,14 @@ def patch( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.PatchSecurityPolicyRequest.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() if v - ] + 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 @@ -678,8 +685,7 @@ def patch_rule( Args: request (~.compute.PatchRuleSecurityPolicyRequest): - The request object. - A request message for + The request object. A request message for SecurityPolicies.PatchRule. See the method description for details. @@ -736,15 +742,14 @@ def patch_rule( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "priority": request.priority, - } + query_params = {} + if compute.PatchRuleSecurityPolicyRequest.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() if v - ] + 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 @@ -766,8 +771,7 @@ def remove_rule( Args: request (~.compute.RemoveRuleSecurityPolicyRequest): - The request object. - A request message for + The request object. A request message for SecurityPolicies.RemoveRule. See the method description for details. @@ -817,19 +821,18 @@ def remove_rule( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "priority": request.priority, - } + query_params = {} + if compute.RemoveRuleSecurityPolicyRequest.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() if v - ] + 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 - response = self._session.post(url) + response = self._session.post(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() diff --git a/google/cloud/compute_v1/services/snapshots/__init__.py b/google/cloud/compute_v1/services/snapshots/__init__.py index fc4bff8d6..0cf7910d6 100644 --- a/google/cloud/compute_v1/services/snapshots/__init__.py +++ b/google/cloud/compute_v1/services/snapshots/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import SnapshotsClient __all__ = ("SnapshotsClient",) diff --git a/google/cloud/compute_v1/services/snapshots/client.py b/google/cloud/compute_v1/services/snapshots/client.py index 215b9002a..57057c008 100644 --- a/google/cloud/compute_v1/services/snapshots/client.py +++ b/google/cloud/compute_v1/services/snapshots/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.snapshots import pagers from google.cloud.compute_v1.types import compute - from .transports.base import SnapshotsTransport, DEFAULT_CLIENT_INFO from .transports.rest import SnapshotsRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, SnapshotsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -358,7 +355,6 @@ def delete( This corresponds to the ``snapshot`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -410,10 +406,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteSnapshotRequest): request = compute.DeleteSnapshotRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if snapshot is not None: @@ -458,7 +452,6 @@ def get( This corresponds to the ``snapshot`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -491,10 +484,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetSnapshotRequest): request = compute.GetSnapshotRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if snapshot is not None: @@ -540,7 +531,6 @@ def get_iam_policy( 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. @@ -618,10 +608,8 @@ def get_iam_policy( # there are no flattened fields. if not isinstance(request, compute.GetIamPolicySnapshotRequest): request = compute.GetIamPolicySnapshotRequest(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: @@ -658,7 +646,6 @@ def list( 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. @@ -690,10 +677,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListSnapshotsRequest): request = compute.ListSnapshotsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -749,7 +734,6 @@ def set_iam_policy( This corresponds to the ``global_set_policy_request_resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -829,10 +813,8 @@ def set_iam_policy( # there are no flattened fields. if not isinstance(request, compute.SetIamPolicySnapshotRequest): request = compute.SetIamPolicySnapshotRequest(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: @@ -888,7 +870,6 @@ def set_labels( 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. @@ -942,10 +923,8 @@ def set_labels( # there are no flattened fields. if not isinstance(request, compute.SetLabelsSnapshotRequest): request = compute.SetLabelsSnapshotRequest(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: @@ -1001,7 +980,6 @@ def test_iam_permissions( 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. @@ -1030,10 +1008,8 @@ def test_iam_permissions( # there are no flattened fields. if not isinstance(request, compute.TestIamPermissionsSnapshotRequest): request = compute.TestIamPermissionsSnapshotRequest(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: diff --git a/google/cloud/compute_v1/services/snapshots/pagers.py b/google/cloud/compute_v1/services/snapshots/pagers.py index 6a26b39f9..8d9aa9333 100644 --- a/google/cloud/compute_v1/services/snapshots/pagers.py +++ b/google/cloud/compute_v1/services/snapshots/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/snapshots/transports/__init__.py b/google/cloud/compute_v1/services/snapshots/transports/__init__.py index ea6674d73..a58ac8e45 100644 --- a/google/cloud/compute_v1/services/snapshots/transports/__init__.py +++ b/google/cloud/compute_v1/services/snapshots/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/snapshots/transports/base.py b/google/cloud/compute_v1/services/snapshots/transports/base.py index a739a31e3..30c94a21c 100644 --- a/google/cloud/compute_v1/services/snapshots/transports/base.py +++ b/google/cloud/compute_v1/services/snapshots/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class SnapshotsTransport(abc.ABC): """Abstract transport class for Snapshots.""" @@ -44,21 +54,24 @@ class SnapshotsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -135,65 +195,64 @@ def _prep_wrapped_messages(self, client_info): @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteSnapshotRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetSnapshotRequest], - typing.Union[compute.Snapshot, typing.Awaitable[compute.Snapshot]], + Union[compute.Snapshot, Awaitable[compute.Snapshot]], ]: raise NotImplementedError() @property def get_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetIamPolicySnapshotRequest], - typing.Union[compute.Policy, typing.Awaitable[compute.Policy]], + Union[compute.Policy, Awaitable[compute.Policy]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListSnapshotsRequest], - typing.Union[compute.SnapshotList, typing.Awaitable[compute.SnapshotList]], + Union[compute.SnapshotList, Awaitable[compute.SnapshotList]], ]: raise NotImplementedError() @property def set_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetIamPolicySnapshotRequest], - typing.Union[compute.Policy, typing.Awaitable[compute.Policy]], + Union[compute.Policy, Awaitable[compute.Policy]], ]: raise NotImplementedError() @property def set_labels( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetLabelsSnapshotRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.TestIamPermissionsSnapshotRequest], - typing.Union[ - compute.TestPermissionsResponse, - typing.Awaitable[compute.TestPermissionsResponse], + Union[ + compute.TestPermissionsResponse, Awaitable[compute.TestPermissionsResponse] ], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/snapshots/transports/rest.py b/google/cloud/compute_v1/services/snapshots/transports/rest.py index 7d0866c43..f7806d93a 100644 --- a/google/cloud/compute_v1/services/snapshots/transports/rest.py +++ b/google/cloud/compute_v1/services/snapshots/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 SnapshotsTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def delete( Args: request (~.compute.DeleteSnapshotRequest): - The request object. - A request message for + The request object. A request message for Snapshots.Delete. See the method description for details. @@ -152,19 +151,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteSnapshotRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -182,8 +180,7 @@ def get( Args: request (~.compute.GetSnapshotRequest): - The request object. - A request message for Snapshots.Get. + The request object. A request message for Snapshots.Get. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -209,16 +206,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -236,8 +232,7 @@ def get_iam_policy( Args: request (~.compute.GetIamPolicySnapshotRequest): - The request object. - A request message for + The request object. A request message for Snapshots.GetIamPolicy. See the method description for details. @@ -307,19 +302,23 @@ def get_iam_policy( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "optionsRequestedPolicyVersion": request.options_requested_policy_version, - } + query_params = {} + if ( + compute.GetIamPolicySnapshotRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -337,8 +336,7 @@ def list( Args: request (~.compute.ListSnapshotsRequest): - The request object. - A request message for Snapshots.List. + The request object. A request message for Snapshots.List. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -359,23 +357,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListSnapshotsRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListSnapshotsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListSnapshotsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListSnapshotsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListSnapshotsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -395,8 +396,7 @@ def set_iam_policy( Args: request (~.compute.SetIamPolicySnapshotRequest): - The request object. - A request message for + The request object. A request message for Snapshots.SetIamPolicy. See the method description for details. @@ -474,12 +474,11 @@ def set_iam_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() if v - ] + 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 @@ -501,8 +500,7 @@ def set_labels( Args: request (~.compute.SetLabelsSnapshotRequest): - The request object. - A request message for + The request object. A request message for Snapshots.SetLabels. See the method description for details. @@ -558,12 +556,11 @@ def set_labels( # 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() if v - ] + 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 @@ -585,8 +582,7 @@ def test_iam_permissions( Args: request (~.compute.TestIamPermissionsSnapshotRequest): - The request object. - A request message for + The request object. A request message for Snapshots.TestIamPermissions. See the method description for details. @@ -614,12 +610,11 @@ def test_iam_permissions( # 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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/ssl_certificates/__init__.py b/google/cloud/compute_v1/services/ssl_certificates/__init__.py index 192052fac..3d6f92000 100644 --- a/google/cloud/compute_v1/services/ssl_certificates/__init__.py +++ b/google/cloud/compute_v1/services/ssl_certificates/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import SslCertificatesClient __all__ = ("SslCertificatesClient",) diff --git a/google/cloud/compute_v1/services/ssl_certificates/client.py b/google/cloud/compute_v1/services/ssl_certificates/client.py index b65c8d47e..30b62ed9e 100644 --- a/google/cloud/compute_v1/services/ssl_certificates/client.py +++ b/google/cloud/compute_v1/services/ssl_certificates/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.ssl_certificates import pagers from google.cloud.compute_v1.types import compute - from .transports.base import SslCertificatesTransport, DEFAULT_CLIENT_INFO from .transports.rest import SslCertificatesRestTransport @@ -215,7 +212,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, SslCertificatesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -349,7 +346,6 @@ def aggregated_list( 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. @@ -379,10 +375,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListSslCertificatesRequest): request = compute.AggregatedListSslCertificatesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -431,7 +425,6 @@ def delete( This corresponds to the ``ssl_certificate`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -483,10 +476,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteSslCertificateRequest): request = compute.DeleteSslCertificateRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if ssl_certificate is not None: @@ -533,7 +524,6 @@ def get( This corresponds to the ``ssl_certificate`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -585,10 +575,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetSslCertificateRequest): request = compute.GetSslCertificateRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if ssl_certificate is not None: @@ -632,7 +620,6 @@ def insert( This corresponds to the ``ssl_certificate_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. @@ -684,10 +671,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertSslCertificateRequest): request = compute.InsertSslCertificateRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if ssl_certificate_resource is not None: @@ -725,7 +710,6 @@ def list( 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. @@ -757,10 +741,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListSslCertificatesRequest): request = compute.ListSslCertificatesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project diff --git a/google/cloud/compute_v1/services/ssl_certificates/pagers.py b/google/cloud/compute_v1/services/ssl_certificates/pagers.py index 7aab7e108..ee47245a8 100644 --- a/google/cloud/compute_v1/services/ssl_certificates/pagers.py +++ b/google/cloud/compute_v1/services/ssl_certificates/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/ssl_certificates/transports/__init__.py b/google/cloud/compute_v1/services/ssl_certificates/transports/__init__.py index 476db62c6..f0aafb409 100644 --- a/google/cloud/compute_v1/services/ssl_certificates/transports/__init__.py +++ b/google/cloud/compute_v1/services/ssl_certificates/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/ssl_certificates/transports/base.py b/google/cloud/compute_v1/services/ssl_certificates/transports/base.py index fccb62330..b582f1a4e 100644 --- a/google/cloud/compute_v1/services/ssl_certificates/transports/base.py +++ b/google/cloud/compute_v1/services/ssl_certificates/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class SslCertificatesTransport(abc.ABC): """Abstract transport class for SslCertificates.""" @@ -44,21 +54,24 @@ class SslCertificatesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -127,11 +187,11 @@ def _prep_wrapped_messages(self, client_info): @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListSslCertificatesRequest], - typing.Union[ + Union[ compute.SslCertificateAggregatedList, - typing.Awaitable[compute.SslCertificateAggregatedList], + Awaitable[compute.SslCertificateAggregatedList], ], ]: raise NotImplementedError() @@ -139,38 +199,36 @@ def aggregated_list( @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteSslCertificateRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetSslCertificateRequest], - typing.Union[compute.SslCertificate, typing.Awaitable[compute.SslCertificate]], + Union[compute.SslCertificate, Awaitable[compute.SslCertificate]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertSslCertificateRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListSslCertificatesRequest], - typing.Union[ - compute.SslCertificateList, typing.Awaitable[compute.SslCertificateList] - ], + Union[compute.SslCertificateList, Awaitable[compute.SslCertificateList]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/ssl_certificates/transports/rest.py b/google/cloud/compute_v1/services/ssl_certificates/transports/rest.py index ed73ca621..9d36ca619 100644 --- a/google/cloud/compute_v1/services/ssl_certificates/transports/rest.py +++ b/google/cloud/compute_v1/services/ssl_certificates/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 SslCertificatesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListSslCertificatesRequest): - The request object. - A request message for + The request object. A request message for SslCertificates.AggregatedList. See the method description for details. @@ -124,24 +123,31 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListSslCertificatesRequest.filter in request: + query_params["filter"] = request.filter + if compute.AggregatedListSslCertificatesRequest.include_all_scopes in request: + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListSslCertificatesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListSslCertificatesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListSslCertificatesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if ( + compute.AggregatedListSslCertificatesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -161,8 +167,7 @@ def delete( Args: request (~.compute.DeleteSslCertificateRequest): - The request object. - A request message for + The request object. A request message for SslCertificates.Delete. See the method description for details. @@ -212,19 +217,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteSslCertificateRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -242,8 +246,7 @@ def get( Args: request (~.compute.GetSslCertificateRequest): - The request object. - A request message for + The request object. A request message for SslCertificates.Get. See the method description for details. @@ -292,16 +295,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -321,8 +323,7 @@ def insert( Args: request (~.compute.InsertSslCertificateRequest): - The request object. - A request message for + The request object. A request message for SslCertificates.Insert. See the method description for details. @@ -377,15 +378,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertSslCertificateRequest.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() if v - ] + 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 @@ -407,8 +407,7 @@ def list( Args: request (~.compute.ListSslCertificatesRequest): - The request object. - A request message for + The request object. A request message for SslCertificates.List. See the method description for details. @@ -430,23 +429,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListSslCertificatesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListSslCertificatesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListSslCertificatesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListSslCertificatesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListSslCertificatesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() diff --git a/google/cloud/compute_v1/services/ssl_policies/__init__.py b/google/cloud/compute_v1/services/ssl_policies/__init__.py index e550e8391..432027835 100644 --- a/google/cloud/compute_v1/services/ssl_policies/__init__.py +++ b/google/cloud/compute_v1/services/ssl_policies/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import SslPoliciesClient __all__ = ("SslPoliciesClient",) diff --git a/google/cloud/compute_v1/services/ssl_policies/client.py b/google/cloud/compute_v1/services/ssl_policies/client.py index 8baa448c4..837648aff 100644 --- a/google/cloud/compute_v1/services/ssl_policies/client.py +++ b/google/cloud/compute_v1/services/ssl_policies/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.ssl_policies import pagers from google.cloud.compute_v1.types import compute - from .transports.base import SslPoliciesTransport, DEFAULT_CLIENT_INFO from .transports.rest import SslPoliciesRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, SslPoliciesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -355,7 +352,6 @@ def delete( This corresponds to the ``ssl_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. @@ -407,10 +403,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteSslPolicyRequest): request = compute.DeleteSslPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if ssl_policy is not None: @@ -456,7 +450,6 @@ def get( This corresponds to the ``ssl_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. @@ -490,10 +483,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetSslPolicyRequest): request = compute.GetSslPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if ssl_policy is not None: @@ -538,7 +529,6 @@ def insert( This corresponds to the ``ssl_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. @@ -590,10 +580,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertSslPolicyRequest): request = compute.InsertSslPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if ssl_policy_resource is not None: @@ -631,7 +619,6 @@ def list( 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. @@ -661,10 +648,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListSslPoliciesRequest): request = compute.ListSslPoliciesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -706,7 +691,6 @@ def list_available_features( 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. @@ -733,10 +717,8 @@ def list_available_features( # there are no flattened fields. if not isinstance(request, compute.ListAvailableFeaturesSslPoliciesRequest): request = compute.ListAvailableFeaturesSslPoliciesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -787,7 +769,6 @@ def patch( This corresponds to the ``ssl_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. @@ -839,10 +820,8 @@ def patch( # there are no flattened fields. if not isinstance(request, compute.PatchSslPolicyRequest): request = compute.PatchSslPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if ssl_policy is not None: diff --git a/google/cloud/compute_v1/services/ssl_policies/pagers.py b/google/cloud/compute_v1/services/ssl_policies/pagers.py index ac8def99e..e8c88b43b 100644 --- a/google/cloud/compute_v1/services/ssl_policies/pagers.py +++ b/google/cloud/compute_v1/services/ssl_policies/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/ssl_policies/transports/__init__.py b/google/cloud/compute_v1/services/ssl_policies/transports/__init__.py index 72fd51108..9866f4572 100644 --- a/google/cloud/compute_v1/services/ssl_policies/transports/__init__.py +++ b/google/cloud/compute_v1/services/ssl_policies/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/ssl_policies/transports/base.py b/google/cloud/compute_v1/services/ssl_policies/transports/base.py index eed48cbf8..0999ec7ac 100644 --- a/google/cloud/compute_v1/services/ssl_policies/transports/base.py +++ b/google/cloud/compute_v1/services/ssl_policies/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class SslPoliciesTransport(abc.ABC): """Abstract transport class for SslPolicies.""" @@ -44,21 +54,24 @@ class SslPoliciesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -132,49 +192,47 @@ def _prep_wrapped_messages(self, client_info): @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteSslPolicyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetSslPolicyRequest], - typing.Union[compute.SslPolicy, typing.Awaitable[compute.SslPolicy]], + Union[compute.SslPolicy, Awaitable[compute.SslPolicy]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertSslPolicyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListSslPoliciesRequest], - typing.Union[ - compute.SslPoliciesList, typing.Awaitable[compute.SslPoliciesList] - ], + Union[compute.SslPoliciesList, Awaitable[compute.SslPoliciesList]], ]: raise NotImplementedError() @property def list_available_features( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListAvailableFeaturesSslPoliciesRequest], - typing.Union[ + Union[ compute.SslPoliciesListAvailableFeaturesResponse, - typing.Awaitable[compute.SslPoliciesListAvailableFeaturesResponse], + Awaitable[compute.SslPoliciesListAvailableFeaturesResponse], ], ]: raise NotImplementedError() @@ -182,9 +240,9 @@ def list_available_features( @property def patch( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchSslPolicyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/ssl_policies/transports/rest.py b/google/cloud/compute_v1/services/ssl_policies/transports/rest.py index b2b03b60a..ac2e00850 100644 --- a/google/cloud/compute_v1/services/ssl_policies/transports/rest.py +++ b/google/cloud/compute_v1/services/ssl_policies/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 SslPoliciesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def delete( Args: request (~.compute.DeleteSslPolicyRequest): - The request object. - A request message for + The request object. A request message for SslPolicies.Delete. See the method description for details. @@ -152,19 +151,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteSslPolicyRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -182,8 +180,7 @@ def get( Args: request (~.compute.GetSslPolicyRequest): - The request object. - A request message for + The request object. A request message for SslPolicies.Get. See the method description for details. @@ -211,16 +208,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -238,8 +234,7 @@ def insert( Args: request (~.compute.InsertSslPolicyRequest): - The request object. - A request message for + The request object. A request message for SslPolicies.Insert. See the method description for details. @@ -294,15 +289,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertSslPolicyRequest.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() if v - ] + 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 @@ -324,8 +318,7 @@ def list( Args: request (~.compute.ListSslPoliciesRequest): - The request object. - A request message for + The request object. A request message for SslPolicies.List. See the method description for details. @@ -345,23 +338,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListSslPoliciesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListSslPoliciesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListSslPoliciesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListSslPoliciesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListSslPoliciesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -381,8 +377,7 @@ def list_available_features( Args: request (~.compute.ListAvailableFeaturesSslPoliciesRequest): - The request object. - A request message for + The request object. A request message for SslPolicies.ListAvailableFeatures. See the method description for details. @@ -402,23 +397,29 @@ def list_available_features( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListAvailableFeaturesSslPoliciesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListAvailableFeaturesSslPoliciesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListAvailableFeaturesSslPoliciesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListAvailableFeaturesSslPoliciesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if ( + compute.ListAvailableFeaturesSslPoliciesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -438,8 +439,7 @@ def patch( Args: request (~.compute.PatchSslPolicyRequest): - The request object. - A request message for + The request object. A request message for SslPolicies.Patch. See the method description for details. @@ -494,15 +494,14 @@ def patch( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.PatchSslPolicyRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/subnetworks/__init__.py b/google/cloud/compute_v1/services/subnetworks/__init__.py index ed95ac6d3..0a7b44aac 100644 --- a/google/cloud/compute_v1/services/subnetworks/__init__.py +++ b/google/cloud/compute_v1/services/subnetworks/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import SubnetworksClient __all__ = ("SubnetworksClient",) diff --git a/google/cloud/compute_v1/services/subnetworks/client.py b/google/cloud/compute_v1/services/subnetworks/client.py index de8b447e7..02e6a793a 100644 --- a/google/cloud/compute_v1/services/subnetworks/client.py +++ b/google/cloud/compute_v1/services/subnetworks/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.subnetworks import pagers from google.cloud.compute_v1.types import compute - from .transports.base import SubnetworksTransport, DEFAULT_CLIENT_INFO from .transports.rest import SubnetworksRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, SubnetworksTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -344,7 +341,6 @@ def aggregated_list( 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. @@ -374,10 +370,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListSubnetworksRequest): request = compute.AggregatedListSubnetworksRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -434,7 +428,6 @@ def delete( This corresponds to the ``subnetwork`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -486,10 +479,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteSubnetworkRequest): request = compute.DeleteSubnetworkRequest(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: @@ -551,7 +542,6 @@ def expand_ip_cidr_range( This corresponds to the ``subnetworks_expand_ip_cidr_range_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. @@ -610,10 +600,8 @@ def expand_ip_cidr_range( # there are no flattened fields. if not isinstance(request, compute.ExpandIpCidrRangeSubnetworkRequest): request = compute.ExpandIpCidrRangeSubnetworkRequest(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: @@ -672,7 +660,6 @@ def get( This corresponds to the ``subnetwork`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -707,10 +694,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetSubnetworkRequest): request = compute.GetSubnetworkRequest(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: @@ -766,7 +751,6 @@ def get_iam_policy( 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. @@ -844,10 +828,8 @@ def get_iam_policy( # there are no flattened fields. if not isinstance(request, compute.GetIamPolicySubnetworkRequest): request = compute.GetIamPolicySubnetworkRequest(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: @@ -901,7 +883,6 @@ def insert( This corresponds to the ``subnetwork_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. @@ -953,10 +934,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertSubnetworkRequest): request = compute.InsertSubnetworkRequest(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: @@ -1004,7 +983,6 @@ def list( 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. @@ -1036,10 +1014,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListSubnetworksRequest): request = compute.ListSubnetworksRequest(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: @@ -1083,7 +1059,6 @@ def list_usable( 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. @@ -1113,10 +1088,8 @@ def list_usable( # there are no flattened fields. if not isinstance(request, compute.ListUsableSubnetworksRequest): request = compute.ListUsableSubnetworksRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -1183,7 +1156,6 @@ def patch( This corresponds to the ``subnetwork_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. @@ -1235,10 +1207,8 @@ def patch( # there are no flattened fields. if not isinstance(request, compute.PatchSubnetworkRequest): request = compute.PatchSubnetworkRequest(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: @@ -1302,7 +1272,6 @@ def set_iam_policy( This corresponds to the ``region_set_policy_request_resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1382,10 +1351,8 @@ def set_iam_policy( # there are no flattened fields. if not isinstance(request, compute.SetIamPolicySubnetworkRequest): request = compute.SetIamPolicySubnetworkRequest(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: @@ -1450,7 +1417,6 @@ def set_private_ip_google_access( This corresponds to the ``subnetworks_set_private_ip_google_access_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. @@ -1509,10 +1475,8 @@ def set_private_ip_google_access( # there are no flattened fields. if not isinstance(request, compute.SetPrivateIpGoogleAccessSubnetworkRequest): request = compute.SetPrivateIpGoogleAccessSubnetworkRequest(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: @@ -1580,7 +1544,6 @@ def test_iam_permissions( 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. @@ -1609,10 +1572,8 @@ def test_iam_permissions( # there are no flattened fields. if not isinstance(request, compute.TestIamPermissionsSubnetworkRequest): request = compute.TestIamPermissionsSubnetworkRequest(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: diff --git a/google/cloud/compute_v1/services/subnetworks/pagers.py b/google/cloud/compute_v1/services/subnetworks/pagers.py index 294a77a9e..eea55ee21 100644 --- a/google/cloud/compute_v1/services/subnetworks/pagers.py +++ b/google/cloud/compute_v1/services/subnetworks/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/subnetworks/transports/__init__.py b/google/cloud/compute_v1/services/subnetworks/transports/__init__.py index f95d31de5..03b697ae6 100644 --- a/google/cloud/compute_v1/services/subnetworks/transports/__init__.py +++ b/google/cloud/compute_v1/services/subnetworks/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/subnetworks/transports/base.py b/google/cloud/compute_v1/services/subnetworks/transports/base.py index 1209e2a74..e9fc688c4 100644 --- a/google/cloud/compute_v1/services/subnetworks/transports/base.py +++ b/google/cloud/compute_v1/services/subnetworks/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class SubnetworksTransport(abc.ABC): """Abstract transport class for Subnetworks.""" @@ -44,21 +54,24 @@ class SubnetworksTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -154,11 +214,11 @@ def _prep_wrapped_messages(self, client_info): @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListSubnetworksRequest], - typing.Union[ + Union[ compute.SubnetworkAggregatedList, - typing.Awaitable[compute.SubnetworkAggregatedList], + Awaitable[compute.SubnetworkAggregatedList], ], ]: raise NotImplementedError() @@ -166,65 +226,65 @@ def aggregated_list( @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteSubnetworkRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def expand_ip_cidr_range( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ExpandIpCidrRangeSubnetworkRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetSubnetworkRequest], - typing.Union[compute.Subnetwork, typing.Awaitable[compute.Subnetwork]], + Union[compute.Subnetwork, Awaitable[compute.Subnetwork]], ]: raise NotImplementedError() @property def get_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetIamPolicySubnetworkRequest], - typing.Union[compute.Policy, typing.Awaitable[compute.Policy]], + Union[compute.Policy, Awaitable[compute.Policy]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertSubnetworkRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListSubnetworksRequest], - typing.Union[compute.SubnetworkList, typing.Awaitable[compute.SubnetworkList]], + Union[compute.SubnetworkList, Awaitable[compute.SubnetworkList]], ]: raise NotImplementedError() @property def list_usable( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListUsableSubnetworksRequest], - typing.Union[ + Union[ compute.UsableSubnetworksAggregatedList, - typing.Awaitable[compute.UsableSubnetworksAggregatedList], + Awaitable[compute.UsableSubnetworksAggregatedList], ], ]: raise NotImplementedError() @@ -232,38 +292,37 @@ def list_usable( @property def patch( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchSubnetworkRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetIamPolicySubnetworkRequest], - typing.Union[compute.Policy, typing.Awaitable[compute.Policy]], + Union[compute.Policy, Awaitable[compute.Policy]], ]: raise NotImplementedError() @property def set_private_ip_google_access( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetPrivateIpGoogleAccessSubnetworkRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.TestIamPermissionsSubnetworkRequest], - typing.Union[ - compute.TestPermissionsResponse, - typing.Awaitable[compute.TestPermissionsResponse], + Union[ + compute.TestPermissionsResponse, Awaitable[compute.TestPermissionsResponse] ], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/subnetworks/transports/rest.py b/google/cloud/compute_v1/services/subnetworks/transports/rest.py index 7302da405..58cb7744d 100644 --- a/google/cloud/compute_v1/services/subnetworks/transports/rest.py +++ b/google/cloud/compute_v1/services/subnetworks/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 SubnetworksTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListSubnetworksRequest): - The request object. - A request message for + The request object. A request message for Subnetworks.AggregatedList. See the method description for details. @@ -124,24 +123,28 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListSubnetworksRequest.filter in request: + query_params["filter"] = request.filter + if compute.AggregatedListSubnetworksRequest.include_all_scopes in request: + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListSubnetworksRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListSubnetworksRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListSubnetworksRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.AggregatedListSubnetworksRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -161,8 +164,7 @@ def delete( Args: request (~.compute.DeleteSubnetworkRequest): - The request object. - A request message for + The request object. A request message for Subnetworks.Delete. See the method description for details. @@ -213,19 +215,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteSubnetworkRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -243,8 +244,7 @@ def expand_ip_cidr_range( Args: request (~.compute.ExpandIpCidrRangeSubnetworkRequest): - The request object. - A request message for + The request object. A request message for Subnetworks.ExpandIpCidrRange. See the method description for details. @@ -302,15 +302,14 @@ def expand_ip_cidr_range( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.ExpandIpCidrRangeSubnetworkRequest.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() if v - ] + 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 @@ -332,8 +331,7 @@ def get( Args: request (~.compute.GetSubnetworkRequest): - The request object. - A request message for + The request object. A request message for Subnetworks.Get. See the method description for details. @@ -364,16 +362,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -393,8 +390,7 @@ def get_iam_policy( Args: request (~.compute.GetIamPolicySubnetworkRequest): - The request object. - A request message for + The request object. A request message for Subnetworks.GetIamPolicy. See the method description for details. @@ -467,19 +463,23 @@ def get_iam_policy( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "optionsRequestedPolicyVersion": request.options_requested_policy_version, - } + query_params = {} + if ( + compute.GetIamPolicySubnetworkRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -497,8 +497,7 @@ def insert( Args: request (~.compute.InsertSubnetworkRequest): - The request object. - A request message for + The request object. A request message for Subnetworks.Insert. See the method description for details. @@ -553,15 +552,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertSubnetworkRequest.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() if v - ] + 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 @@ -583,8 +581,7 @@ def list( Args: request (~.compute.ListSubnetworksRequest): - The request object. - A request message for + The request object. A request message for Subnetworks.List. See the method description for details. @@ -606,23 +603,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListSubnetworksRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListSubnetworksRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListSubnetworksRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListSubnetworksRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListSubnetworksRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -642,8 +642,7 @@ def list_usable( Args: request (~.compute.ListUsableSubnetworksRequest): - The request object. - A request message for + The request object. A request message for Subnetworks.ListUsable. See the method description for details. @@ -663,23 +662,26 @@ def list_usable( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListUsableSubnetworksRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListUsableSubnetworksRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListUsableSubnetworksRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListUsableSubnetworksRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListUsableSubnetworksRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -699,8 +701,7 @@ def patch( Args: request (~.compute.PatchSubnetworkRequest): - The request object. - A request message for + The request object. A request message for Subnetworks.Patch. See the method description for details. @@ -758,16 +759,16 @@ def patch( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "drainTimeoutSeconds": request.drain_timeout_seconds, - "requestId": request.request_id, - } + query_params = {} + if compute.PatchSubnetworkRequest.drain_timeout_seconds in request: + query_params["drainTimeoutSeconds"] = request.drain_timeout_seconds + if compute.PatchSubnetworkRequest.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() if v - ] + 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 @@ -789,8 +790,7 @@ def set_iam_policy( Args: request (~.compute.SetIamPolicySubnetworkRequest): - The request object. - A request message for + The request object. A request message for Subnetworks.SetIamPolicy. See the method description for details. @@ -871,12 +871,11 @@ def set_iam_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() if v - ] + 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 @@ -899,8 +898,7 @@ def set_private_ip_google_access( Args: request (~.compute.SetPrivateIpGoogleAccessSubnetworkRequest): - The request object. - A request message for + The request object. A request message for Subnetworks.SetPrivateIpGoogleAccess. See the method description for details. @@ -958,15 +956,14 @@ def set_private_ip_google_access( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetPrivateIpGoogleAccessSubnetworkRequest.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() if v - ] + 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 @@ -988,8 +985,7 @@ def test_iam_permissions( Args: request (~.compute.TestIamPermissionsSubnetworkRequest): - The request object. - A request message for + The request object. A request message for Subnetworks.TestIamPermissions. See the method description for details. @@ -1020,12 +1016,11 @@ def test_iam_permissions( # 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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/target_grpc_proxies/__init__.py b/google/cloud/compute_v1/services/target_grpc_proxies/__init__.py index fe3f4280e..c429c9276 100644 --- a/google/cloud/compute_v1/services/target_grpc_proxies/__init__.py +++ b/google/cloud/compute_v1/services/target_grpc_proxies/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import TargetGrpcProxiesClient __all__ = ("TargetGrpcProxiesClient",) diff --git a/google/cloud/compute_v1/services/target_grpc_proxies/client.py b/google/cloud/compute_v1/services/target_grpc_proxies/client.py index c13568178..244113715 100644 --- a/google/cloud/compute_v1/services/target_grpc_proxies/client.py +++ b/google/cloud/compute_v1/services/target_grpc_proxies/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.target_grpc_proxies import pagers from google.cloud.compute_v1.types import compute - from .transports.base import TargetGrpcProxiesTransport, DEFAULT_CLIENT_INFO from .transports.rest import TargetGrpcProxiesRestTransport @@ -217,7 +214,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, TargetGrpcProxiesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -357,7 +354,6 @@ def delete( This corresponds to the ``target_grpc_proxy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -409,10 +405,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteTargetGrpcProxyRequest): request = compute.DeleteTargetGrpcProxyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if target_grpc_proxy is not None: @@ -458,7 +452,6 @@ def get( This corresponds to the ``target_grpc_proxy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -494,10 +487,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetTargetGrpcProxyRequest): request = compute.GetTargetGrpcProxyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if target_grpc_proxy is not None: @@ -542,7 +533,6 @@ def insert( This corresponds to the ``target_grpc_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. @@ -594,10 +584,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertTargetGrpcProxyRequest): request = compute.InsertTargetGrpcProxyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if target_grpc_proxy_resource is not None: @@ -635,7 +623,6 @@ def list( 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. @@ -665,10 +652,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListTargetGrpcProxiesRequest): request = compute.ListTargetGrpcProxiesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -726,7 +711,6 @@ def patch( This corresponds to the ``target_grpc_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. @@ -780,10 +764,8 @@ def patch( # there are no flattened fields. if not isinstance(request, compute.PatchTargetGrpcProxyRequest): request = compute.PatchTargetGrpcProxyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if target_grpc_proxy is not None: diff --git a/google/cloud/compute_v1/services/target_grpc_proxies/pagers.py b/google/cloud/compute_v1/services/target_grpc_proxies/pagers.py index 4602e3f62..1f330c80e 100644 --- a/google/cloud/compute_v1/services/target_grpc_proxies/pagers.py +++ b/google/cloud/compute_v1/services/target_grpc_proxies/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/target_grpc_proxies/transports/__init__.py b/google/cloud/compute_v1/services/target_grpc_proxies/transports/__init__.py index da6ce0031..55988c9fc 100644 --- a/google/cloud/compute_v1/services/target_grpc_proxies/transports/__init__.py +++ b/google/cloud/compute_v1/services/target_grpc_proxies/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/target_grpc_proxies/transports/base.py b/google/cloud/compute_v1/services/target_grpc_proxies/transports/base.py index e0152af07..57d27673f 100644 --- a/google/cloud/compute_v1/services/target_grpc_proxies/transports/base.py +++ b/google/cloud/compute_v1/services/target_grpc_proxies/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class TargetGrpcProxiesTransport(abc.ABC): """Abstract transport class for TargetGrpcProxies.""" @@ -44,21 +54,24 @@ class TargetGrpcProxiesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -127,49 +187,45 @@ def _prep_wrapped_messages(self, client_info): @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteTargetGrpcProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetTargetGrpcProxyRequest], - typing.Union[ - compute.TargetGrpcProxy, typing.Awaitable[compute.TargetGrpcProxy] - ], + Union[compute.TargetGrpcProxy, Awaitable[compute.TargetGrpcProxy]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertTargetGrpcProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListTargetGrpcProxiesRequest], - typing.Union[ - compute.TargetGrpcProxyList, typing.Awaitable[compute.TargetGrpcProxyList] - ], + Union[compute.TargetGrpcProxyList, Awaitable[compute.TargetGrpcProxyList]], ]: raise NotImplementedError() @property def patch( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchTargetGrpcProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/target_grpc_proxies/transports/rest.py b/google/cloud/compute_v1/services/target_grpc_proxies/transports/rest.py index ec7e8d6e4..30ffb7631 100644 --- a/google/cloud/compute_v1/services/target_grpc_proxies/transports/rest.py +++ b/google/cloud/compute_v1/services/target_grpc_proxies/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 TargetGrpcProxiesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def delete( Args: request (~.compute.DeleteTargetGrpcProxyRequest): - The request object. - A request message for + The request object. A request message for TargetGrpcProxies.Delete. See the method description for details. @@ -154,19 +153,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteTargetGrpcProxyRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -184,8 +182,7 @@ def get( Args: request (~.compute.GetTargetGrpcProxyRequest): - The request object. - A request message for + The request object. A request message for TargetGrpcProxies.Get. See the method description for details. @@ -216,16 +213,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -245,8 +241,7 @@ def insert( Args: request (~.compute.InsertTargetGrpcProxyRequest): - The request object. - A request message for + The request object. A request message for TargetGrpcProxies.Insert. See the method description for details. @@ -301,15 +296,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertTargetGrpcProxyRequest.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() if v - ] + 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 @@ -331,8 +325,7 @@ def list( Args: request (~.compute.ListTargetGrpcProxiesRequest): - The request object. - A request message for + The request object. A request message for TargetGrpcProxies.List. See the method description for details. @@ -352,23 +345,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListTargetGrpcProxiesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListTargetGrpcProxiesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListTargetGrpcProxiesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListTargetGrpcProxiesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListTargetGrpcProxiesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -388,8 +384,7 @@ def patch( Args: request (~.compute.PatchTargetGrpcProxyRequest): - The request object. - A request message for + The request object. A request message for TargetGrpcProxies.Patch. See the method description for details. @@ -446,15 +441,14 @@ def patch( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.PatchTargetGrpcProxyRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/target_http_proxies/__init__.py b/google/cloud/compute_v1/services/target_http_proxies/__init__.py index e72405b2a..b79a991fd 100644 --- a/google/cloud/compute_v1/services/target_http_proxies/__init__.py +++ b/google/cloud/compute_v1/services/target_http_proxies/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import TargetHttpProxiesClient __all__ = ("TargetHttpProxiesClient",) diff --git a/google/cloud/compute_v1/services/target_http_proxies/client.py b/google/cloud/compute_v1/services/target_http_proxies/client.py index 5065177ec..c5108a6ff 100644 --- a/google/cloud/compute_v1/services/target_http_proxies/client.py +++ b/google/cloud/compute_v1/services/target_http_proxies/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.target_http_proxies import pagers from google.cloud.compute_v1.types import compute - from .transports.base import TargetHttpProxiesTransport, DEFAULT_CLIENT_INFO from .transports.rest import TargetHttpProxiesRestTransport @@ -217,7 +214,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, TargetHttpProxiesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -351,7 +348,6 @@ def aggregated_list( 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. @@ -381,10 +377,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListTargetHttpProxiesRequest): request = compute.AggregatedListTargetHttpProxiesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -433,7 +427,6 @@ def delete( This corresponds to the ``target_http_proxy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -485,10 +478,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteTargetHttpProxyRequest): request = compute.DeleteTargetHttpProxyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if target_http_proxy is not None: @@ -535,7 +526,6 @@ def get( This corresponds to the ``target_http_proxy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -585,10 +575,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetTargetHttpProxyRequest): request = compute.GetTargetHttpProxyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if target_http_proxy is not None: @@ -632,7 +620,6 @@ def insert( This corresponds to the ``target_http_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. @@ -684,10 +671,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertTargetHttpProxyRequest): request = compute.InsertTargetHttpProxyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if target_http_proxy_resource is not None: @@ -725,7 +710,6 @@ def list( 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. @@ -756,10 +740,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListTargetHttpProxiesRequest): request = compute.ListTargetHttpProxiesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -817,7 +799,6 @@ def patch( This corresponds to the ``target_http_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. @@ -871,10 +852,8 @@ def patch( # there are no flattened fields. if not isinstance(request, compute.PatchTargetHttpProxyRequest): request = compute.PatchTargetHttpProxyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if target_http_proxy is not None: @@ -927,7 +906,6 @@ def set_url_map( This corresponds to the ``url_map_reference_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. @@ -981,10 +959,8 @@ def set_url_map( # there are no flattened fields. if not isinstance(request, compute.SetUrlMapTargetHttpProxyRequest): request = compute.SetUrlMapTargetHttpProxyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if target_http_proxy is not None: diff --git a/google/cloud/compute_v1/services/target_http_proxies/pagers.py b/google/cloud/compute_v1/services/target_http_proxies/pagers.py index 8d5848858..d8a8c0afc 100644 --- a/google/cloud/compute_v1/services/target_http_proxies/pagers.py +++ b/google/cloud/compute_v1/services/target_http_proxies/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/target_http_proxies/transports/__init__.py b/google/cloud/compute_v1/services/target_http_proxies/transports/__init__.py index 87e090acf..43bf2d0a3 100644 --- a/google/cloud/compute_v1/services/target_http_proxies/transports/__init__.py +++ b/google/cloud/compute_v1/services/target_http_proxies/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/target_http_proxies/transports/base.py b/google/cloud/compute_v1/services/target_http_proxies/transports/base.py index 215b0ee0a..91acce6c4 100644 --- a/google/cloud/compute_v1/services/target_http_proxies/transports/base.py +++ b/google/cloud/compute_v1/services/target_http_proxies/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class TargetHttpProxiesTransport(abc.ABC): """Abstract transport class for TargetHttpProxies.""" @@ -44,21 +54,24 @@ class TargetHttpProxiesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -133,11 +193,11 @@ def _prep_wrapped_messages(self, client_info): @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListTargetHttpProxiesRequest], - typing.Union[ + Union[ compute.TargetHttpProxyAggregatedList, - typing.Awaitable[compute.TargetHttpProxyAggregatedList], + Awaitable[compute.TargetHttpProxyAggregatedList], ], ]: raise NotImplementedError() @@ -145,58 +205,54 @@ def aggregated_list( @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteTargetHttpProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetTargetHttpProxyRequest], - typing.Union[ - compute.TargetHttpProxy, typing.Awaitable[compute.TargetHttpProxy] - ], + Union[compute.TargetHttpProxy, Awaitable[compute.TargetHttpProxy]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertTargetHttpProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListTargetHttpProxiesRequest], - typing.Union[ - compute.TargetHttpProxyList, typing.Awaitable[compute.TargetHttpProxyList] - ], + Union[compute.TargetHttpProxyList, Awaitable[compute.TargetHttpProxyList]], ]: raise NotImplementedError() @property def patch( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchTargetHttpProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_url_map( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetUrlMapTargetHttpProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/target_http_proxies/transports/rest.py b/google/cloud/compute_v1/services/target_http_proxies/transports/rest.py index 8c62a79fc..9f9dce2aa 100644 --- a/google/cloud/compute_v1/services/target_http_proxies/transports/rest.py +++ b/google/cloud/compute_v1/services/target_http_proxies/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 TargetHttpProxiesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListTargetHttpProxiesRequest): - The request object. - A request message for + The request object. A request message for TargetHttpProxies.AggregatedList. See the method description for details. @@ -124,24 +123,31 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListTargetHttpProxiesRequest.filter in request: + query_params["filter"] = request.filter + if compute.AggregatedListTargetHttpProxiesRequest.include_all_scopes in request: + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListTargetHttpProxiesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListTargetHttpProxiesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListTargetHttpProxiesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if ( + compute.AggregatedListTargetHttpProxiesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -161,8 +167,7 @@ def delete( Args: request (~.compute.DeleteTargetHttpProxyRequest): - The request object. - A request message for + The request object. A request message for TargetHttpProxies.Delete. See the method description for details. @@ -212,19 +217,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteTargetHttpProxyRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -242,8 +246,7 @@ def get( Args: request (~.compute.GetTargetHttpProxyRequest): - The request object. - A request message for + The request object. A request message for TargetHttpProxies.Get. See the method description for details. @@ -289,16 +292,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -318,8 +320,7 @@ def insert( Args: request (~.compute.InsertTargetHttpProxyRequest): - The request object. - A request message for + The request object. A request message for TargetHttpProxies.Insert. See the method description for details. @@ -374,15 +375,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertTargetHttpProxyRequest.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() if v - ] + 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 @@ -404,8 +404,7 @@ def list( Args: request (~.compute.ListTargetHttpProxiesRequest): - The request object. - A request message for + The request object. A request message for TargetHttpProxies.List. See the method description for details. @@ -425,23 +424,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListTargetHttpProxiesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListTargetHttpProxiesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListTargetHttpProxiesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListTargetHttpProxiesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListTargetHttpProxiesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -461,8 +463,7 @@ def patch( Args: request (~.compute.PatchTargetHttpProxyRequest): - The request object. - A request message for + The request object. A request message for TargetHttpProxies.Patch. See the method description for details. @@ -519,15 +520,14 @@ def patch( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.PatchTargetHttpProxyRequest.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() if v - ] + 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 @@ -549,8 +549,7 @@ def set_url_map( Args: request (~.compute.SetUrlMapTargetHttpProxyRequest): - The request object. - A request message for + The request object. A request message for TargetHttpProxies.SetUrlMap. See the method description for details. @@ -607,15 +606,14 @@ def set_url_map( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetUrlMapTargetHttpProxyRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/target_https_proxies/__init__.py b/google/cloud/compute_v1/services/target_https_proxies/__init__.py index e4264c140..1da336136 100644 --- a/google/cloud/compute_v1/services/target_https_proxies/__init__.py +++ b/google/cloud/compute_v1/services/target_https_proxies/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import TargetHttpsProxiesClient __all__ = ("TargetHttpsProxiesClient",) diff --git a/google/cloud/compute_v1/services/target_https_proxies/client.py b/google/cloud/compute_v1/services/target_https_proxies/client.py index 254494a86..8850aae52 100644 --- a/google/cloud/compute_v1/services/target_https_proxies/client.py +++ b/google/cloud/compute_v1/services/target_https_proxies/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.target_https_proxies import pagers from google.cloud.compute_v1.types import compute - from .transports.base import TargetHttpsProxiesTransport, DEFAULT_CLIENT_INFO from .transports.rest import TargetHttpsProxiesRestTransport @@ -217,7 +214,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, TargetHttpsProxiesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -351,7 +348,6 @@ def aggregated_list( 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. @@ -381,10 +377,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListTargetHttpsProxiesRequest): request = compute.AggregatedListTargetHttpsProxiesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -433,7 +427,6 @@ def delete( This corresponds to the ``target_https_proxy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -485,10 +478,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteTargetHttpsProxyRequest): request = compute.DeleteTargetHttpsProxyRequest(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: @@ -535,7 +526,6 @@ def get( This corresponds to the ``target_https_proxy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -585,10 +575,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetTargetHttpsProxyRequest): request = compute.GetTargetHttpsProxyRequest(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: @@ -632,7 +620,6 @@ def insert( 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. @@ -684,10 +671,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertTargetHttpsProxyRequest): request = compute.InsertTargetHttpsProxyRequest(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_resource is not None: @@ -725,7 +710,6 @@ def list( 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. @@ -757,10 +741,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListTargetHttpsProxiesRequest): request = compute.ListTargetHttpsProxiesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -816,7 +798,6 @@ def set_quic_override( This corresponds to the ``target_https_proxies_set_quic_override_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. @@ -874,10 +855,8 @@ def set_quic_override( # there are no flattened fields. if not isinstance(request, compute.SetQuicOverrideTargetHttpsProxyRequest): request = compute.SetQuicOverrideTargetHttpsProxyRequest(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: @@ -932,7 +911,6 @@ def set_ssl_certificates( This corresponds to the ``target_https_proxies_set_ssl_certificates_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. @@ -990,10 +968,8 @@ def set_ssl_certificates( # there are no flattened fields. if not isinstance(request, compute.SetSslCertificatesTargetHttpsProxyRequest): request = compute.SetSslCertificatesTargetHttpsProxyRequest(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: @@ -1054,7 +1030,6 @@ def set_ssl_policy( This corresponds to the ``ssl_policy_reference_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. @@ -1108,10 +1083,8 @@ def set_ssl_policy( # there are no flattened fields. if not isinstance(request, compute.SetSslPolicyTargetHttpsProxyRequest): request = compute.SetSslPolicyTargetHttpsProxyRequest(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: @@ -1164,7 +1137,6 @@ def set_url_map( This corresponds to the ``url_map_reference_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. @@ -1218,10 +1190,8 @@ def set_url_map( # there are no flattened fields. if not isinstance(request, compute.SetUrlMapTargetHttpsProxyRequest): request = compute.SetUrlMapTargetHttpsProxyRequest(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: diff --git a/google/cloud/compute_v1/services/target_https_proxies/pagers.py b/google/cloud/compute_v1/services/target_https_proxies/pagers.py index d6817b0e5..a1aff1e2f 100644 --- a/google/cloud/compute_v1/services/target_https_proxies/pagers.py +++ b/google/cloud/compute_v1/services/target_https_proxies/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/target_https_proxies/transports/__init__.py b/google/cloud/compute_v1/services/target_https_proxies/transports/__init__.py index e9889d33a..2835b46ce 100644 --- a/google/cloud/compute_v1/services/target_https_proxies/transports/__init__.py +++ b/google/cloud/compute_v1/services/target_https_proxies/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/target_https_proxies/transports/base.py b/google/cloud/compute_v1/services/target_https_proxies/transports/base.py index 44e4afbd3..620a8bf28 100644 --- a/google/cloud/compute_v1/services/target_https_proxies/transports/base.py +++ b/google/cloud/compute_v1/services/target_https_proxies/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class TargetHttpsProxiesTransport(abc.ABC): """Abstract transport class for TargetHttpsProxies.""" @@ -44,21 +54,24 @@ class TargetHttpsProxiesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -141,11 +201,11 @@ def _prep_wrapped_messages(self, client_info): @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListTargetHttpsProxiesRequest], - typing.Union[ + Union[ compute.TargetHttpsProxyAggregatedList, - typing.Awaitable[compute.TargetHttpsProxyAggregatedList], + Awaitable[compute.TargetHttpsProxyAggregatedList], ], ]: raise NotImplementedError() @@ -153,76 +213,72 @@ def aggregated_list( @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteTargetHttpsProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetTargetHttpsProxyRequest], - typing.Union[ - compute.TargetHttpsProxy, typing.Awaitable[compute.TargetHttpsProxy] - ], + Union[compute.TargetHttpsProxy, Awaitable[compute.TargetHttpsProxy]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertTargetHttpsProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListTargetHttpsProxiesRequest], - typing.Union[ - compute.TargetHttpsProxyList, typing.Awaitable[compute.TargetHttpsProxyList] - ], + Union[compute.TargetHttpsProxyList, Awaitable[compute.TargetHttpsProxyList]], ]: raise NotImplementedError() @property def set_quic_override( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetQuicOverrideTargetHttpsProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_ssl_certificates( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetSslCertificatesTargetHttpsProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_ssl_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetSslPolicyTargetHttpsProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_url_map( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetUrlMapTargetHttpsProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/target_https_proxies/transports/rest.py b/google/cloud/compute_v1/services/target_https_proxies/transports/rest.py index 25977e224..5118937a1 100644 --- a/google/cloud/compute_v1/services/target_https_proxies/transports/rest.py +++ b/google/cloud/compute_v1/services/target_https_proxies/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 TargetHttpsProxiesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListTargetHttpsProxiesRequest): - The request object. - A request message for + The request object. A request message for TargetHttpsProxies.AggregatedList. See the method description for details. @@ -124,24 +123,34 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListTargetHttpsProxiesRequest.filter in request: + query_params["filter"] = request.filter + if ( + compute.AggregatedListTargetHttpsProxiesRequest.include_all_scopes + in request + ): + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListTargetHttpsProxiesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListTargetHttpsProxiesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListTargetHttpsProxiesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if ( + compute.AggregatedListTargetHttpsProxiesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -161,8 +170,7 @@ def delete( Args: request (~.compute.DeleteTargetHttpsProxyRequest): - The request object. - A request message for + The request object. A request message for TargetHttpsProxies.Delete. See the method description for details. @@ -212,19 +220,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteTargetHttpsProxyRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -242,8 +249,7 @@ def get( Args: request (~.compute.GetTargetHttpsProxyRequest): - The request object. - A request message for + The request object. A request message for TargetHttpsProxies.Get. See the method description for details. @@ -288,16 +294,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -317,8 +322,7 @@ def insert( Args: request (~.compute.InsertTargetHttpsProxyRequest): - The request object. - A request message for + The request object. A request message for TargetHttpsProxies.Insert. See the method description for details. @@ -373,15 +377,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertTargetHttpsProxyRequest.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() if v - ] + 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 @@ -403,8 +406,7 @@ def list( Args: request (~.compute.ListTargetHttpsProxiesRequest): - The request object. - A request message for + The request object. A request message for TargetHttpsProxies.List. See the method description for details. @@ -426,23 +428,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListTargetHttpsProxiesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListTargetHttpsProxiesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListTargetHttpsProxiesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListTargetHttpsProxiesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListTargetHttpsProxiesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -462,8 +467,7 @@ def set_quic_override( Args: request (~.compute.SetQuicOverrideTargetHttpsProxyRequest): - The request object. - A request message for + The request object. A request message for TargetHttpsProxies.SetQuicOverride. See the method description for details. @@ -520,15 +524,14 @@ def set_quic_override( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetQuicOverrideTargetHttpsProxyRequest.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() if v - ] + 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 @@ -550,8 +553,7 @@ def set_ssl_certificates( Args: request (~.compute.SetSslCertificatesTargetHttpsProxyRequest): - The request object. - A request message for + The request object. A request message for TargetHttpsProxies.SetSslCertificates. See the method description for details. @@ -608,15 +610,14 @@ def set_ssl_certificates( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetSslCertificatesTargetHttpsProxyRequest.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() if v - ] + 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 @@ -638,8 +639,7 @@ def set_ssl_policy( Args: request (~.compute.SetSslPolicyTargetHttpsProxyRequest): - The request object. - A request message for + The request object. A request message for TargetHttpsProxies.SetSslPolicy. See the method description for details. @@ -696,15 +696,14 @@ def set_ssl_policy( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetSslPolicyTargetHttpsProxyRequest.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() if v - ] + 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 @@ -726,8 +725,7 @@ def set_url_map( Args: request (~.compute.SetUrlMapTargetHttpsProxyRequest): - The request object. - A request message for + The request object. A request message for TargetHttpsProxies.SetUrlMap. See the method description for details. @@ -784,15 +782,14 @@ def set_url_map( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetUrlMapTargetHttpsProxyRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/target_instances/__init__.py b/google/cloud/compute_v1/services/target_instances/__init__.py index 40d3198f2..592a1c65d 100644 --- a/google/cloud/compute_v1/services/target_instances/__init__.py +++ b/google/cloud/compute_v1/services/target_instances/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import TargetInstancesClient __all__ = ("TargetInstancesClient",) diff --git a/google/cloud/compute_v1/services/target_instances/client.py b/google/cloud/compute_v1/services/target_instances/client.py index 65f231da2..bf9d84daf 100644 --- a/google/cloud/compute_v1/services/target_instances/client.py +++ b/google/cloud/compute_v1/services/target_instances/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.target_instances import pagers from google.cloud.compute_v1.types import compute - from .transports.base import TargetInstancesTransport, DEFAULT_CLIENT_INFO from .transports.rest import TargetInstancesRestTransport @@ -215,7 +212,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, TargetInstancesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -346,7 +343,6 @@ def aggregated_list( 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. @@ -376,10 +372,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListTargetInstancesRequest): request = compute.AggregatedListTargetInstancesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -436,7 +430,6 @@ def delete( This corresponds to the ``target_instance`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -488,10 +481,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteTargetInstanceRequest): request = compute.DeleteTargetInstanceRequest(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: @@ -548,7 +539,6 @@ def get( This corresponds to the ``target_instance`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -583,10 +573,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetTargetInstanceRequest): request = compute.GetTargetInstanceRequest(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: @@ -640,7 +628,6 @@ def insert( This corresponds to the ``target_instance_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. @@ -692,10 +679,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertTargetInstanceRequest): request = compute.InsertTargetInstanceRequest(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: @@ -743,7 +728,6 @@ def list( This corresponds to the ``zone`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -775,10 +759,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListTargetInstancesRequest): request = compute.ListTargetInstancesRequest(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: diff --git a/google/cloud/compute_v1/services/target_instances/pagers.py b/google/cloud/compute_v1/services/target_instances/pagers.py index f31990bbd..7902e9c82 100644 --- a/google/cloud/compute_v1/services/target_instances/pagers.py +++ b/google/cloud/compute_v1/services/target_instances/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/target_instances/transports/__init__.py b/google/cloud/compute_v1/services/target_instances/transports/__init__.py index 662d203a3..37f862f10 100644 --- a/google/cloud/compute_v1/services/target_instances/transports/__init__.py +++ b/google/cloud/compute_v1/services/target_instances/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/target_instances/transports/base.py b/google/cloud/compute_v1/services/target_instances/transports/base.py index 968b218b3..71933229c 100644 --- a/google/cloud/compute_v1/services/target_instances/transports/base.py +++ b/google/cloud/compute_v1/services/target_instances/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class TargetInstancesTransport(abc.ABC): """Abstract transport class for TargetInstances.""" @@ -44,21 +54,24 @@ class TargetInstancesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -127,11 +187,11 @@ def _prep_wrapped_messages(self, client_info): @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListTargetInstancesRequest], - typing.Union[ + Union[ compute.TargetInstanceAggregatedList, - typing.Awaitable[compute.TargetInstanceAggregatedList], + Awaitable[compute.TargetInstanceAggregatedList], ], ]: raise NotImplementedError() @@ -139,38 +199,36 @@ def aggregated_list( @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteTargetInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetTargetInstanceRequest], - typing.Union[compute.TargetInstance, typing.Awaitable[compute.TargetInstance]], + Union[compute.TargetInstance, Awaitable[compute.TargetInstance]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertTargetInstanceRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListTargetInstancesRequest], - typing.Union[ - compute.TargetInstanceList, typing.Awaitable[compute.TargetInstanceList] - ], + Union[compute.TargetInstanceList, Awaitable[compute.TargetInstanceList]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/target_instances/transports/rest.py b/google/cloud/compute_v1/services/target_instances/transports/rest.py index fb2589eb5..0c2cbd282 100644 --- a/google/cloud/compute_v1/services/target_instances/transports/rest.py +++ b/google/cloud/compute_v1/services/target_instances/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 TargetInstancesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListTargetInstancesRequest): - The request object. - A request message for + The request object. A request message for TargetInstances.AggregatedList. See the method description for details. @@ -124,24 +123,31 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListTargetInstancesRequest.filter in request: + query_params["filter"] = request.filter + if compute.AggregatedListTargetInstancesRequest.include_all_scopes in request: + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListTargetInstancesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListTargetInstancesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListTargetInstancesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if ( + compute.AggregatedListTargetInstancesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -161,8 +167,7 @@ def delete( Args: request (~.compute.DeleteTargetInstanceRequest): - The request object. - A request message for + The request object. A request message for TargetInstances.Delete. See the method description for details. @@ -213,19 +218,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteTargetInstanceRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -243,8 +247,7 @@ def get( Args: request (~.compute.GetTargetInstanceRequest): - The request object. - A request message for + The request object. A request message for TargetInstances.Get. See the method description for details. @@ -276,16 +279,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -305,8 +307,7 @@ def insert( Args: request (~.compute.InsertTargetInstanceRequest): - The request object. - A request message for + The request object. A request message for TargetInstances.Insert. See the method description for details. @@ -361,15 +362,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertTargetInstanceRequest.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() if v - ] + 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 @@ -391,8 +391,7 @@ def list( Args: request (~.compute.ListTargetInstancesRequest): - The request object. - A request message for + The request object. A request message for TargetInstances.List. See the method description for details. @@ -414,23 +413,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListTargetInstancesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListTargetInstancesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListTargetInstancesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListTargetInstancesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListTargetInstancesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() diff --git a/google/cloud/compute_v1/services/target_pools/__init__.py b/google/cloud/compute_v1/services/target_pools/__init__.py index 6db7fad54..319c2d5de 100644 --- a/google/cloud/compute_v1/services/target_pools/__init__.py +++ b/google/cloud/compute_v1/services/target_pools/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import TargetPoolsClient __all__ = ("TargetPoolsClient",) diff --git a/google/cloud/compute_v1/services/target_pools/client.py b/google/cloud/compute_v1/services/target_pools/client.py index a98fe47d6..cfecc1177 100644 --- a/google/cloud/compute_v1/services/target_pools/client.py +++ b/google/cloud/compute_v1/services/target_pools/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.target_pools import pagers from google.cloud.compute_v1.types import compute - from .transports.base import TargetPoolsTransport, DEFAULT_CLIENT_INFO from .transports.rest import TargetPoolsRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, TargetPoolsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -366,7 +363,6 @@ def add_health_check( This corresponds to the ``target_pools_add_health_check_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. @@ -425,10 +421,8 @@ def add_health_check( # there are no flattened fields. if not isinstance(request, compute.AddHealthCheckTargetPoolRequest): request = compute.AddHealthCheckTargetPoolRequest(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: @@ -493,7 +487,6 @@ def add_instance( This corresponds to the ``target_pools_add_instance_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. @@ -547,10 +540,8 @@ def add_instance( # there are no flattened fields. if not isinstance(request, compute.AddInstanceTargetPoolRequest): request = compute.AddInstanceTargetPoolRequest(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: @@ -593,7 +584,6 @@ def aggregated_list( 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. @@ -623,10 +613,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListTargetPoolsRequest): request = compute.AggregatedListTargetPoolsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -683,7 +671,6 @@ def delete( This corresponds to the ``target_pool`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -735,10 +722,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteTargetPoolRequest): request = compute.DeleteTargetPoolRequest(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: @@ -793,7 +778,6 @@ def get( This corresponds to the ``target_pool`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -828,10 +812,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetTargetPoolRequest): request = compute.GetTargetPoolRequest(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: @@ -894,7 +876,6 @@ def get_health( This corresponds to the ``instance_reference_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. @@ -923,10 +904,8 @@ def get_health( # there are no flattened fields. if not isinstance(request, compute.GetHealthTargetPoolRequest): request = compute.GetHealthTargetPoolRequest(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: @@ -982,7 +961,6 @@ def insert( This corresponds to the ``target_pool_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. @@ -1034,10 +1012,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertTargetPoolRequest): request = compute.InsertTargetPoolRequest(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: @@ -1085,7 +1061,6 @@ def list( 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. @@ -1117,10 +1092,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListTargetPoolsRequest): request = compute.ListTargetPoolsRequest(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: @@ -1183,7 +1156,6 @@ def remove_health_check( This corresponds to the ``target_pools_remove_health_check_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. @@ -1242,10 +1214,8 @@ def remove_health_check( # there are no flattened fields. if not isinstance(request, compute.RemoveHealthCheckTargetPoolRequest): request = compute.RemoveHealthCheckTargetPoolRequest(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: @@ -1310,7 +1280,6 @@ def remove_instance( This corresponds to the ``target_pools_remove_instance_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. @@ -1369,10 +1338,8 @@ def remove_instance( # there are no flattened fields. if not isinstance(request, compute.RemoveInstanceTargetPoolRequest): request = compute.RemoveInstanceTargetPoolRequest(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: @@ -1437,7 +1404,6 @@ def set_backup( This corresponds to the ``target_reference_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. @@ -1491,10 +1457,8 @@ def set_backup( # there are no flattened fields. if not isinstance(request, compute.SetBackupTargetPoolRequest): request = compute.SetBackupTargetPoolRequest(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: diff --git a/google/cloud/compute_v1/services/target_pools/pagers.py b/google/cloud/compute_v1/services/target_pools/pagers.py index 30ade2320..5dfaa09fc 100644 --- a/google/cloud/compute_v1/services/target_pools/pagers.py +++ b/google/cloud/compute_v1/services/target_pools/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/target_pools/transports/__init__.py b/google/cloud/compute_v1/services/target_pools/transports/__init__.py index 7a8ed2c7a..a441cbe2c 100644 --- a/google/cloud/compute_v1/services/target_pools/transports/__init__.py +++ b/google/cloud/compute_v1/services/target_pools/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/target_pools/transports/base.py b/google/cloud/compute_v1/services/target_pools/transports/base.py index b92ed76fe..b8df7bf2a 100644 --- a/google/cloud/compute_v1/services/target_pools/transports/base.py +++ b/google/cloud/compute_v1/services/target_pools/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class TargetPoolsTransport(abc.ABC): """Abstract transport class for TargetPools.""" @@ -44,21 +54,24 @@ class TargetPoolsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -145,29 +205,29 @@ def _prep_wrapped_messages(self, client_info): @property def add_health_check( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AddHealthCheckTargetPoolRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def add_instance( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AddInstanceTargetPoolRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListTargetPoolsRequest], - typing.Union[ + Union[ compute.TargetPoolAggregatedList, - typing.Awaitable[compute.TargetPoolAggregatedList], + Awaitable[compute.TargetPoolAggregatedList], ], ]: raise NotImplementedError() @@ -175,29 +235,29 @@ def aggregated_list( @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteTargetPoolRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetTargetPoolRequest], - typing.Union[compute.TargetPool, typing.Awaitable[compute.TargetPool]], + Union[compute.TargetPool, Awaitable[compute.TargetPool]], ]: raise NotImplementedError() @property def get_health( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetHealthTargetPoolRequest], - typing.Union[ + Union[ compute.TargetPoolInstanceHealth, - typing.Awaitable[compute.TargetPoolInstanceHealth], + Awaitable[compute.TargetPoolInstanceHealth], ], ]: raise NotImplementedError() @@ -205,45 +265,45 @@ def get_health( @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertTargetPoolRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListTargetPoolsRequest], - typing.Union[compute.TargetPoolList, typing.Awaitable[compute.TargetPoolList]], + Union[compute.TargetPoolList, Awaitable[compute.TargetPoolList]], ]: raise NotImplementedError() @property def remove_health_check( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.RemoveHealthCheckTargetPoolRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def remove_instance( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.RemoveInstanceTargetPoolRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_backup( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetBackupTargetPoolRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/target_pools/transports/rest.py b/google/cloud/compute_v1/services/target_pools/transports/rest.py index 14bfda449..b9ee4a33e 100644 --- a/google/cloud/compute_v1/services/target_pools/transports/rest.py +++ b/google/cloud/compute_v1/services/target_pools/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 TargetPoolsTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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_health_check( self, @@ -103,8 +103,7 @@ def add_health_check( Args: request (~.compute.AddHealthCheckTargetPoolRequest): - The request object. - A request message for + The request object. A request message for TargetPools.AddHealthCheck. See the method description for details. @@ -162,15 +161,14 @@ def add_health_check( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.AddHealthCheckTargetPoolRequest.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() if v - ] + 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 @@ -192,8 +190,7 @@ def add_instance( Args: request (~.compute.AddInstanceTargetPoolRequest): - The request object. - A request message for + The request object. A request message for TargetPools.AddInstance. See the method description for details. @@ -251,15 +248,14 @@ def add_instance( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.AddInstanceTargetPoolRequest.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() if v - ] + 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 @@ -281,8 +277,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListTargetPoolsRequest): - The request object. - A request message for + The request object. A request message for TargetPools.AggregatedList. See the method description for details. @@ -302,24 +297,28 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListTargetPoolsRequest.filter in request: + query_params["filter"] = request.filter + if compute.AggregatedListTargetPoolsRequest.include_all_scopes in request: + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListTargetPoolsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListTargetPoolsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListTargetPoolsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.AggregatedListTargetPoolsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -339,8 +338,7 @@ def delete( Args: request (~.compute.DeleteTargetPoolRequest): - The request object. - A request message for + The request object. A request message for TargetPools.Delete. See the method description for details. @@ -391,19 +389,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteTargetPoolRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -421,8 +418,7 @@ def get( Args: request (~.compute.GetTargetPoolRequest): - The request object. - A request message for + The request object. A request message for TargetPools.Get. See the method description for details. @@ -454,16 +450,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -483,8 +478,7 @@ def get_health( Args: request (~.compute.GetHealthTargetPoolRequest): - The request object. - A request message for + The request object. A request message for TargetPools.GetHealth. See the method description for details. @@ -515,12 +509,11 @@ def get_health( # 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() if v - ] + 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 @@ -544,8 +537,7 @@ def insert( Args: request (~.compute.InsertTargetPoolRequest): - The request object. - A request message for + The request object. A request message for TargetPools.Insert. See the method description for details. @@ -600,15 +592,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertTargetPoolRequest.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() if v - ] + 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 @@ -630,8 +621,7 @@ def list( Args: request (~.compute.ListTargetPoolsRequest): - The request object. - A request message for + The request object. A request message for TargetPools.List. See the method description for details. @@ -653,23 +643,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListTargetPoolsRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListTargetPoolsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListTargetPoolsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListTargetPoolsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListTargetPoolsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -689,8 +682,7 @@ def remove_health_check( Args: request (~.compute.RemoveHealthCheckTargetPoolRequest): - The request object. - A request message for + The request object. A request message for TargetPools.RemoveHealthCheck. See the method description for details. @@ -748,15 +740,14 @@ def remove_health_check( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.RemoveHealthCheckTargetPoolRequest.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() if v - ] + 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 @@ -778,8 +769,7 @@ def remove_instance( Args: request (~.compute.RemoveInstanceTargetPoolRequest): - The request object. - A request message for + The request object. A request message for TargetPools.RemoveInstance. See the method description for details. @@ -837,15 +827,14 @@ def remove_instance( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.RemoveInstanceTargetPoolRequest.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() if v - ] + 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 @@ -867,8 +856,7 @@ def set_backup( Args: request (~.compute.SetBackupTargetPoolRequest): - The request object. - A request message for + The request object. A request message for TargetPools.SetBackup. See the method description for details. @@ -926,16 +914,16 @@ def set_backup( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "failoverRatio": request.failover_ratio, - "requestId": request.request_id, - } + query_params = {} + if compute.SetBackupTargetPoolRequest.failover_ratio in request: + query_params["failoverRatio"] = request.failover_ratio + if compute.SetBackupTargetPoolRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/target_ssl_proxies/__init__.py b/google/cloud/compute_v1/services/target_ssl_proxies/__init__.py index 2143b1e2f..a697e86dc 100644 --- a/google/cloud/compute_v1/services/target_ssl_proxies/__init__.py +++ b/google/cloud/compute_v1/services/target_ssl_proxies/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import TargetSslProxiesClient __all__ = ("TargetSslProxiesClient",) diff --git a/google/cloud/compute_v1/services/target_ssl_proxies/client.py b/google/cloud/compute_v1/services/target_ssl_proxies/client.py index bac26316e..4a23ebd29 100644 --- a/google/cloud/compute_v1/services/target_ssl_proxies/client.py +++ b/google/cloud/compute_v1/services/target_ssl_proxies/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.target_ssl_proxies import pagers from google.cloud.compute_v1.types import compute - from .transports.base import TargetSslProxiesTransport, DEFAULT_CLIENT_INFO from .transports.rest import TargetSslProxiesRestTransport @@ -215,7 +212,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, TargetSslProxiesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -354,7 +351,6 @@ def delete( This corresponds to the ``target_ssl_proxy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -406,10 +402,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteTargetSslProxyRequest): request = compute.DeleteTargetSslProxyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if target_ssl_proxy is not None: @@ -456,7 +450,6 @@ def get( This corresponds to the ``target_ssl_proxy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -491,10 +484,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetTargetSslProxyRequest): request = compute.GetTargetSslProxyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if target_ssl_proxy is not None: @@ -538,7 +529,6 @@ def insert( This corresponds to the ``target_ssl_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. @@ -590,10 +580,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertTargetSslProxyRequest): request = compute.InsertTargetSslProxyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if target_ssl_proxy_resource is not None: @@ -631,7 +619,6 @@ def list( 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. @@ -663,10 +650,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListTargetSslProxiesRequest): request = compute.ListTargetSslProxiesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -722,7 +707,6 @@ def set_backend_service( This corresponds to the ``target_ssl_proxies_set_backend_service_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. @@ -780,10 +764,8 @@ def set_backend_service( # there are no flattened fields. if not isinstance(request, compute.SetBackendServiceTargetSslProxyRequest): request = compute.SetBackendServiceTargetSslProxyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if target_ssl_proxy is not None: @@ -838,7 +820,6 @@ def set_proxy_header( This corresponds to the ``target_ssl_proxies_set_proxy_header_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. @@ -896,10 +877,8 @@ def set_proxy_header( # there are no flattened fields. if not isinstance(request, compute.SetProxyHeaderTargetSslProxyRequest): request = compute.SetProxyHeaderTargetSslProxyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if target_ssl_proxy is not None: @@ -955,7 +934,6 @@ def set_ssl_certificates( This corresponds to the ``target_ssl_proxies_set_ssl_certificates_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. @@ -1013,10 +991,8 @@ def set_ssl_certificates( # there are no flattened fields. if not isinstance(request, compute.SetSslCertificatesTargetSslProxyRequest): request = compute.SetSslCertificatesTargetSslProxyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if target_ssl_proxy is not None: @@ -1077,7 +1053,6 @@ def set_ssl_policy( This corresponds to the ``ssl_policy_reference_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. @@ -1131,10 +1106,8 @@ def set_ssl_policy( # there are no flattened fields. if not isinstance(request, compute.SetSslPolicyTargetSslProxyRequest): request = compute.SetSslPolicyTargetSslProxyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if target_ssl_proxy is not None: diff --git a/google/cloud/compute_v1/services/target_ssl_proxies/pagers.py b/google/cloud/compute_v1/services/target_ssl_proxies/pagers.py index d995c620f..09b1f2249 100644 --- a/google/cloud/compute_v1/services/target_ssl_proxies/pagers.py +++ b/google/cloud/compute_v1/services/target_ssl_proxies/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/target_ssl_proxies/transports/__init__.py b/google/cloud/compute_v1/services/target_ssl_proxies/transports/__init__.py index e1af89b07..534932a50 100644 --- a/google/cloud/compute_v1/services/target_ssl_proxies/transports/__init__.py +++ b/google/cloud/compute_v1/services/target_ssl_proxies/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/target_ssl_proxies/transports/base.py b/google/cloud/compute_v1/services/target_ssl_proxies/transports/base.py index bb2afd6bf..bd2d3580e 100644 --- a/google/cloud/compute_v1/services/target_ssl_proxies/transports/base.py +++ b/google/cloud/compute_v1/services/target_ssl_proxies/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class TargetSslProxiesTransport(abc.ABC): """Abstract transport class for TargetSslProxies.""" @@ -44,21 +54,24 @@ class TargetSslProxiesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -138,74 +198,72 @@ def _prep_wrapped_messages(self, client_info): @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteTargetSslProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetTargetSslProxyRequest], - typing.Union[compute.TargetSslProxy, typing.Awaitable[compute.TargetSslProxy]], + Union[compute.TargetSslProxy, Awaitable[compute.TargetSslProxy]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertTargetSslProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListTargetSslProxiesRequest], - typing.Union[ - compute.TargetSslProxyList, typing.Awaitable[compute.TargetSslProxyList] - ], + Union[compute.TargetSslProxyList, Awaitable[compute.TargetSslProxyList]], ]: raise NotImplementedError() @property def set_backend_service( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetBackendServiceTargetSslProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_proxy_header( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetProxyHeaderTargetSslProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_ssl_certificates( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetSslCertificatesTargetSslProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_ssl_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetSslPolicyTargetSslProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/target_ssl_proxies/transports/rest.py b/google/cloud/compute_v1/services/target_ssl_proxies/transports/rest.py index 92c2e43db..2959e1786 100644 --- a/google/cloud/compute_v1/services/target_ssl_proxies/transports/rest.py +++ b/google/cloud/compute_v1/services/target_ssl_proxies/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 TargetSslProxiesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def delete( Args: request (~.compute.DeleteTargetSslProxyRequest): - The request object. - A request message for + The request object. A request message for TargetSslProxies.Delete. See the method description for details. @@ -154,19 +153,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteTargetSslProxyRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -184,8 +182,7 @@ def get( Args: request (~.compute.GetTargetSslProxyRequest): - The request object. - A request message for + The request object. A request message for TargetSslProxies.Get. See the method description for details. @@ -216,16 +213,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -245,8 +241,7 @@ def insert( Args: request (~.compute.InsertTargetSslProxyRequest): - The request object. - A request message for + The request object. A request message for TargetSslProxies.Insert. See the method description for details. @@ -301,15 +296,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertTargetSslProxyRequest.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() if v - ] + 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 @@ -331,8 +325,7 @@ def list( Args: request (~.compute.ListTargetSslProxiesRequest): - The request object. - A request message for + The request object. A request message for TargetSslProxies.List. See the method description for details. @@ -354,23 +347,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListTargetSslProxiesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListTargetSslProxiesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListTargetSslProxiesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListTargetSslProxiesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListTargetSslProxiesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -390,8 +386,7 @@ def set_backend_service( Args: request (~.compute.SetBackendServiceTargetSslProxyRequest): - The request object. - A request message for + The request object. A request message for TargetSslProxies.SetBackendService. See the method description for details. @@ -448,15 +443,14 @@ def set_backend_service( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetBackendServiceTargetSslProxyRequest.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() if v - ] + 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 @@ -478,8 +472,7 @@ def set_proxy_header( Args: request (~.compute.SetProxyHeaderTargetSslProxyRequest): - The request object. - A request message for + The request object. A request message for TargetSslProxies.SetProxyHeader. See the method description for details. @@ -536,15 +529,14 @@ def set_proxy_header( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetProxyHeaderTargetSslProxyRequest.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() if v - ] + 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 @@ -566,8 +558,7 @@ def set_ssl_certificates( Args: request (~.compute.SetSslCertificatesTargetSslProxyRequest): - The request object. - A request message for + The request object. A request message for TargetSslProxies.SetSslCertificates. See the method description for details. @@ -624,15 +615,14 @@ def set_ssl_certificates( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetSslCertificatesTargetSslProxyRequest.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() if v - ] + 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 @@ -654,8 +644,7 @@ def set_ssl_policy( Args: request (~.compute.SetSslPolicyTargetSslProxyRequest): - The request object. - A request message for + The request object. A request message for TargetSslProxies.SetSslPolicy. See the method description for details. @@ -712,15 +701,14 @@ def set_ssl_policy( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetSslPolicyTargetSslProxyRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/target_tcp_proxies/__init__.py b/google/cloud/compute_v1/services/target_tcp_proxies/__init__.py index c0bdf4fc8..ccd3dd8cf 100644 --- a/google/cloud/compute_v1/services/target_tcp_proxies/__init__.py +++ b/google/cloud/compute_v1/services/target_tcp_proxies/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import TargetTcpProxiesClient __all__ = ("TargetTcpProxiesClient",) diff --git a/google/cloud/compute_v1/services/target_tcp_proxies/client.py b/google/cloud/compute_v1/services/target_tcp_proxies/client.py index 9afbacfd9..81fc4e06c 100644 --- a/google/cloud/compute_v1/services/target_tcp_proxies/client.py +++ b/google/cloud/compute_v1/services/target_tcp_proxies/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.target_tcp_proxies import pagers from google.cloud.compute_v1.types import compute - from .transports.base import TargetTcpProxiesTransport, DEFAULT_CLIENT_INFO from .transports.rest import TargetTcpProxiesRestTransport @@ -215,7 +212,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, TargetTcpProxiesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -354,7 +351,6 @@ def delete( This corresponds to the ``target_tcp_proxy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -406,10 +402,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteTargetTcpProxyRequest): request = compute.DeleteTargetTcpProxyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if target_tcp_proxy is not None: @@ -456,7 +450,6 @@ def get( This corresponds to the ``target_tcp_proxy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -491,10 +484,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetTargetTcpProxyRequest): request = compute.GetTargetTcpProxyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if target_tcp_proxy is not None: @@ -538,7 +529,6 @@ def insert( This corresponds to the ``target_tcp_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. @@ -590,10 +580,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertTargetTcpProxyRequest): request = compute.InsertTargetTcpProxyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if target_tcp_proxy_resource is not None: @@ -631,7 +619,6 @@ def list( 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. @@ -663,10 +650,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListTargetTcpProxiesRequest): request = compute.ListTargetTcpProxiesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -722,7 +707,6 @@ def set_backend_service( This corresponds to the ``target_tcp_proxies_set_backend_service_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. @@ -780,10 +764,8 @@ def set_backend_service( # there are no flattened fields. if not isinstance(request, compute.SetBackendServiceTargetTcpProxyRequest): request = compute.SetBackendServiceTargetTcpProxyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if target_tcp_proxy is not None: @@ -838,7 +820,6 @@ def set_proxy_header( This corresponds to the ``target_tcp_proxies_set_proxy_header_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. @@ -896,10 +877,8 @@ def set_proxy_header( # there are no flattened fields. if not isinstance(request, compute.SetProxyHeaderTargetTcpProxyRequest): request = compute.SetProxyHeaderTargetTcpProxyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if target_tcp_proxy is not None: diff --git a/google/cloud/compute_v1/services/target_tcp_proxies/pagers.py b/google/cloud/compute_v1/services/target_tcp_proxies/pagers.py index b9fcb6753..a942527ae 100644 --- a/google/cloud/compute_v1/services/target_tcp_proxies/pagers.py +++ b/google/cloud/compute_v1/services/target_tcp_proxies/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/target_tcp_proxies/transports/__init__.py b/google/cloud/compute_v1/services/target_tcp_proxies/transports/__init__.py index dd5e5973d..c6d0f663b 100644 --- a/google/cloud/compute_v1/services/target_tcp_proxies/transports/__init__.py +++ b/google/cloud/compute_v1/services/target_tcp_proxies/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/target_tcp_proxies/transports/base.py b/google/cloud/compute_v1/services/target_tcp_proxies/transports/base.py index c29d17189..771478189 100644 --- a/google/cloud/compute_v1/services/target_tcp_proxies/transports/base.py +++ b/google/cloud/compute_v1/services/target_tcp_proxies/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class TargetTcpProxiesTransport(abc.ABC): """Abstract transport class for TargetTcpProxies.""" @@ -44,21 +54,24 @@ class TargetTcpProxiesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -130,56 +190,54 @@ def _prep_wrapped_messages(self, client_info): @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteTargetTcpProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetTargetTcpProxyRequest], - typing.Union[compute.TargetTcpProxy, typing.Awaitable[compute.TargetTcpProxy]], + Union[compute.TargetTcpProxy, Awaitable[compute.TargetTcpProxy]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertTargetTcpProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListTargetTcpProxiesRequest], - typing.Union[ - compute.TargetTcpProxyList, typing.Awaitable[compute.TargetTcpProxyList] - ], + Union[compute.TargetTcpProxyList, Awaitable[compute.TargetTcpProxyList]], ]: raise NotImplementedError() @property def set_backend_service( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetBackendServiceTargetTcpProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def set_proxy_header( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetProxyHeaderTargetTcpProxyRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/target_tcp_proxies/transports/rest.py b/google/cloud/compute_v1/services/target_tcp_proxies/transports/rest.py index 23986003e..2d42752c4 100644 --- a/google/cloud/compute_v1/services/target_tcp_proxies/transports/rest.py +++ b/google/cloud/compute_v1/services/target_tcp_proxies/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 TargetTcpProxiesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def delete( Args: request (~.compute.DeleteTargetTcpProxyRequest): - The request object. - A request message for + The request object. A request message for TargetTcpProxies.Delete. See the method description for details. @@ -154,19 +153,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteTargetTcpProxyRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -184,8 +182,7 @@ def get( Args: request (~.compute.GetTargetTcpProxyRequest): - The request object. - A request message for + The request object. A request message for TargetTcpProxies.Get. See the method description for details. @@ -216,16 +213,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -245,8 +241,7 @@ def insert( Args: request (~.compute.InsertTargetTcpProxyRequest): - The request object. - A request message for + The request object. A request message for TargetTcpProxies.Insert. See the method description for details. @@ -301,15 +296,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertTargetTcpProxyRequest.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() if v - ] + 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 @@ -331,8 +325,7 @@ def list( Args: request (~.compute.ListTargetTcpProxiesRequest): - The request object. - A request message for + The request object. A request message for TargetTcpProxies.List. See the method description for details. @@ -354,23 +347,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListTargetTcpProxiesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListTargetTcpProxiesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListTargetTcpProxiesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListTargetTcpProxiesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListTargetTcpProxiesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -390,8 +386,7 @@ def set_backend_service( Args: request (~.compute.SetBackendServiceTargetTcpProxyRequest): - The request object. - A request message for + The request object. A request message for TargetTcpProxies.SetBackendService. See the method description for details. @@ -448,15 +443,14 @@ def set_backend_service( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetBackendServiceTargetTcpProxyRequest.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() if v - ] + 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 @@ -478,8 +472,7 @@ def set_proxy_header( Args: request (~.compute.SetProxyHeaderTargetTcpProxyRequest): - The request object. - A request message for + The request object. A request message for TargetTcpProxies.SetProxyHeader. See the method description for details. @@ -536,15 +529,14 @@ def set_proxy_header( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetProxyHeaderTargetTcpProxyRequest.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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/target_vpn_gateways/__init__.py b/google/cloud/compute_v1/services/target_vpn_gateways/__init__.py index 5eb7b9096..7d3e0e6d6 100644 --- a/google/cloud/compute_v1/services/target_vpn_gateways/__init__.py +++ b/google/cloud/compute_v1/services/target_vpn_gateways/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import TargetVpnGatewaysClient __all__ = ("TargetVpnGatewaysClient",) diff --git a/google/cloud/compute_v1/services/target_vpn_gateways/client.py b/google/cloud/compute_v1/services/target_vpn_gateways/client.py index d12a7a27b..d93fd4c27 100644 --- a/google/cloud/compute_v1/services/target_vpn_gateways/client.py +++ b/google/cloud/compute_v1/services/target_vpn_gateways/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.target_vpn_gateways import pagers from google.cloud.compute_v1.types import compute - from .transports.base import TargetVpnGatewaysTransport, DEFAULT_CLIENT_INFO from .transports.rest import TargetVpnGatewaysRestTransport @@ -217,7 +214,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, TargetVpnGatewaysTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -348,7 +345,6 @@ def aggregated_list( 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. @@ -378,10 +374,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListTargetVpnGatewaysRequest): request = compute.AggregatedListTargetVpnGatewaysRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -436,7 +430,6 @@ def delete( This corresponds to the ``target_vpn_gateway`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -488,10 +481,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteTargetVpnGatewayRequest): request = compute.DeleteTargetVpnGatewayRequest(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: @@ -546,7 +537,6 @@ def get( This corresponds to the ``target_vpn_gateway`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -579,10 +569,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetTargetVpnGatewayRequest): request = compute.GetTargetVpnGatewayRequest(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: @@ -634,7 +622,6 @@ def insert( This corresponds to the ``target_vpn_gateway_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. @@ -686,10 +673,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertTargetVpnGatewayRequest): request = compute.InsertTargetVpnGatewayRequest(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: @@ -735,7 +720,6 @@ def list( 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. @@ -767,10 +751,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListTargetVpnGatewaysRequest): request = compute.ListTargetVpnGatewaysRequest(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: diff --git a/google/cloud/compute_v1/services/target_vpn_gateways/pagers.py b/google/cloud/compute_v1/services/target_vpn_gateways/pagers.py index e01973f79..a5dcca01e 100644 --- a/google/cloud/compute_v1/services/target_vpn_gateways/pagers.py +++ b/google/cloud/compute_v1/services/target_vpn_gateways/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/target_vpn_gateways/transports/__init__.py b/google/cloud/compute_v1/services/target_vpn_gateways/transports/__init__.py index 36486b3e8..8911c3112 100644 --- a/google/cloud/compute_v1/services/target_vpn_gateways/transports/__init__.py +++ b/google/cloud/compute_v1/services/target_vpn_gateways/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/target_vpn_gateways/transports/base.py b/google/cloud/compute_v1/services/target_vpn_gateways/transports/base.py index 4b840085a..82aa6de86 100644 --- a/google/cloud/compute_v1/services/target_vpn_gateways/transports/base.py +++ b/google/cloud/compute_v1/services/target_vpn_gateways/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class TargetVpnGatewaysTransport(abc.ABC): """Abstract transport class for TargetVpnGateways.""" @@ -44,21 +54,24 @@ class TargetVpnGatewaysTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -127,11 +187,11 @@ def _prep_wrapped_messages(self, client_info): @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListTargetVpnGatewaysRequest], - typing.Union[ + Union[ compute.TargetVpnGatewayAggregatedList, - typing.Awaitable[compute.TargetVpnGatewayAggregatedList], + Awaitable[compute.TargetVpnGatewayAggregatedList], ], ]: raise NotImplementedError() @@ -139,40 +199,36 @@ def aggregated_list( @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteTargetVpnGatewayRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetTargetVpnGatewayRequest], - typing.Union[ - compute.TargetVpnGateway, typing.Awaitable[compute.TargetVpnGateway] - ], + Union[compute.TargetVpnGateway, Awaitable[compute.TargetVpnGateway]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertTargetVpnGatewayRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListTargetVpnGatewaysRequest], - typing.Union[ - compute.TargetVpnGatewayList, typing.Awaitable[compute.TargetVpnGatewayList] - ], + Union[compute.TargetVpnGatewayList, Awaitable[compute.TargetVpnGatewayList]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/target_vpn_gateways/transports/rest.py b/google/cloud/compute_v1/services/target_vpn_gateways/transports/rest.py index adede88b3..2ba82a45e 100644 --- a/google/cloud/compute_v1/services/target_vpn_gateways/transports/rest.py +++ b/google/cloud/compute_v1/services/target_vpn_gateways/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 TargetVpnGatewaysTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListTargetVpnGatewaysRequest): - The request object. - A request message for + The request object. A request message for TargetVpnGateways.AggregatedList. See the method description for details. @@ -124,24 +123,31 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListTargetVpnGatewaysRequest.filter in request: + query_params["filter"] = request.filter + if compute.AggregatedListTargetVpnGatewaysRequest.include_all_scopes in request: + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListTargetVpnGatewaysRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListTargetVpnGatewaysRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListTargetVpnGatewaysRequest.page_token in request: + query_params["pageToken"] = request.page_token + if ( + compute.AggregatedListTargetVpnGatewaysRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -161,8 +167,7 @@ def delete( Args: request (~.compute.DeleteTargetVpnGatewayRequest): - The request object. - A request message for + The request object. A request message for TargetVpnGateways.Delete. See the method description for details. @@ -213,19 +218,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteTargetVpnGatewayRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -243,8 +247,7 @@ def get( Args: request (~.compute.GetTargetVpnGatewayRequest): - The request object. - A request message for + The request object. A request message for TargetVpnGateways.Get. See the method description for details. @@ -274,16 +277,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -303,8 +305,7 @@ def insert( Args: request (~.compute.InsertTargetVpnGatewayRequest): - The request object. - A request message for + The request object. A request message for TargetVpnGateways.Insert. See the method description for details. @@ -359,15 +360,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertTargetVpnGatewayRequest.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() if v - ] + 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 @@ -389,8 +389,7 @@ def list( Args: request (~.compute.ListTargetVpnGatewaysRequest): - The request object. - A request message for + The request object. A request message for TargetVpnGateways.List. See the method description for details. @@ -412,23 +411,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListTargetVpnGatewaysRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListTargetVpnGatewaysRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListTargetVpnGatewaysRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListTargetVpnGatewaysRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListTargetVpnGatewaysRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() diff --git a/google/cloud/compute_v1/services/url_maps/__init__.py b/google/cloud/compute_v1/services/url_maps/__init__.py index a5f582866..caeebbc8a 100644 --- a/google/cloud/compute_v1/services/url_maps/__init__.py +++ b/google/cloud/compute_v1/services/url_maps/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import UrlMapsClient __all__ = ("UrlMapsClient",) diff --git a/google/cloud/compute_v1/services/url_maps/client.py b/google/cloud/compute_v1/services/url_maps/client.py index c42f3ccd0..d6b089960 100644 --- a/google/cloud/compute_v1/services/url_maps/client.py +++ b/google/cloud/compute_v1/services/url_maps/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.url_maps import pagers from google.cloud.compute_v1.types import compute - from .transports.base import UrlMapsTransport, DEFAULT_CLIENT_INFO from .transports.rest import UrlMapsRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, UrlMapsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -347,7 +344,6 @@ def aggregated_list( 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. @@ -377,10 +373,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListUrlMapsRequest): request = compute.AggregatedListUrlMapsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -428,7 +422,6 @@ def delete( This corresponds to the ``url_map`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -480,10 +473,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteUrlMapRequest): request = compute.DeleteUrlMapRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if url_map is not None: @@ -528,7 +519,6 @@ def get( This corresponds to the ``url_map`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -588,10 +578,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetUrlMapRequest): request = compute.GetUrlMapRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if url_map is not None: @@ -634,7 +622,6 @@ def insert( This corresponds to the ``url_map_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. @@ -686,10 +673,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertUrlMapRequest): request = compute.InsertUrlMapRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if url_map_resource is not None: @@ -744,7 +729,6 @@ def invalidate_cache( This corresponds to the ``cache_invalidation_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. @@ -796,10 +780,8 @@ def invalidate_cache( # there are no flattened fields. if not isinstance(request, compute.InvalidateCacheUrlMapRequest): request = compute.InvalidateCacheUrlMapRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if url_map is not None: @@ -840,7 +822,6 @@ def list( 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. @@ -871,10 +852,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListUrlMapsRequest): request = compute.ListUrlMapsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -929,7 +908,6 @@ def patch( This corresponds to the ``url_map_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. @@ -981,10 +959,8 @@ def patch( # there are no flattened fields. if not isinstance(request, compute.PatchUrlMapRequest): request = compute.PatchUrlMapRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if url_map is not None: @@ -1037,7 +1013,6 @@ def update( This corresponds to the ``url_map_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. @@ -1089,10 +1064,8 @@ def update( # there are no flattened fields. if not isinstance(request, compute.UpdateUrlMapRequest): request = compute.UpdateUrlMapRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if url_map is not None: @@ -1147,7 +1120,6 @@ def validate( This corresponds to the ``url_maps_validate_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. @@ -1176,10 +1148,8 @@ def validate( # there are no flattened fields. if not isinstance(request, compute.ValidateUrlMapRequest): request = compute.ValidateUrlMapRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project if url_map is not None: diff --git a/google/cloud/compute_v1/services/url_maps/pagers.py b/google/cloud/compute_v1/services/url_maps/pagers.py index 1ceea1492..1a5d42fc4 100644 --- a/google/cloud/compute_v1/services/url_maps/pagers.py +++ b/google/cloud/compute_v1/services/url_maps/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/url_maps/transports/__init__.py b/google/cloud/compute_v1/services/url_maps/transports/__init__.py index bc5555980..acd446c7a 100644 --- a/google/cloud/compute_v1/services/url_maps/transports/__init__.py +++ b/google/cloud/compute_v1/services/url_maps/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/url_maps/transports/base.py b/google/cloud/compute_v1/services/url_maps/transports/base.py index 130758c96..04dd0ae69 100644 --- a/google/cloud/compute_v1/services/url_maps/transports/base.py +++ b/google/cloud/compute_v1/services/url_maps/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class UrlMapsTransport(abc.ABC): """Abstract transport class for UrlMaps.""" @@ -44,21 +54,24 @@ class UrlMapsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -139,86 +199,81 @@ def _prep_wrapped_messages(self, client_info): @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListUrlMapsRequest], - typing.Union[ - compute.UrlMapsAggregatedList, - typing.Awaitable[compute.UrlMapsAggregatedList], - ], + Union[compute.UrlMapsAggregatedList, Awaitable[compute.UrlMapsAggregatedList]], ]: raise NotImplementedError() @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteUrlMapRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ - [compute.GetUrlMapRequest], - typing.Union[compute.UrlMap, typing.Awaitable[compute.UrlMap]], + ) -> Callable[ + [compute.GetUrlMapRequest], Union[compute.UrlMap, Awaitable[compute.UrlMap]] ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertUrlMapRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def invalidate_cache( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InvalidateCacheUrlMapRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListUrlMapsRequest], - typing.Union[compute.UrlMapList, typing.Awaitable[compute.UrlMapList]], + Union[compute.UrlMapList, Awaitable[compute.UrlMapList]], ]: raise NotImplementedError() @property def patch( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.PatchUrlMapRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def update( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.UpdateUrlMapRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def validate( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ValidateUrlMapRequest], - typing.Union[ - compute.UrlMapsValidateResponse, - typing.Awaitable[compute.UrlMapsValidateResponse], + Union[ + compute.UrlMapsValidateResponse, Awaitable[compute.UrlMapsValidateResponse] ], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/url_maps/transports/rest.py b/google/cloud/compute_v1/services/url_maps/transports/rest.py index f19acf1bf..0a92c3fe0 100644 --- a/google/cloud/compute_v1/services/url_maps/transports/rest.py +++ b/google/cloud/compute_v1/services/url_maps/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 UrlMapsTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListUrlMapsRequest): - The request object. - A request message for + The request object. A request message for UrlMaps.AggregatedList. See the method description for details. @@ -124,24 +123,28 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListUrlMapsRequest.filter in request: + query_params["filter"] = request.filter + if compute.AggregatedListUrlMapsRequest.include_all_scopes in request: + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListUrlMapsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListUrlMapsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListUrlMapsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.AggregatedListUrlMapsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -161,8 +164,7 @@ def delete( Args: request (~.compute.DeleteUrlMapRequest): - The request object. - A request message for UrlMaps.Delete. + The request object. A request message for UrlMaps.Delete. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -209,19 +211,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteUrlMapRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -239,8 +240,7 @@ def get( Args: request (~.compute.GetUrlMapRequest): - The request object. - A request message for UrlMaps.Get. + The request object. A request message for UrlMaps.Get. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -292,16 +292,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -319,8 +318,7 @@ def insert( Args: request (~.compute.InsertUrlMapRequest): - The request object. - A request message for UrlMaps.Insert. + The request object. A request message for UrlMaps.Insert. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -374,15 +372,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertUrlMapRequest.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() if v - ] + 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 @@ -404,8 +401,7 @@ def invalidate_cache( Args: request (~.compute.InvalidateCacheUrlMapRequest): - The request object. - A request message for + The request object. A request message for UrlMaps.InvalidateCache. See the method description for details. @@ -460,15 +456,14 @@ def invalidate_cache( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InvalidateCacheUrlMapRequest.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() if v - ] + 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 @@ -490,8 +485,7 @@ def list( Args: request (~.compute.ListUrlMapsRequest): - The request object. - A request message for UrlMaps.List. + The request object. A request message for UrlMaps.List. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -510,23 +504,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListUrlMapsRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListUrlMapsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListUrlMapsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListUrlMapsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListUrlMapsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -546,8 +543,7 @@ def patch( Args: request (~.compute.PatchUrlMapRequest): - The request object. - A request message for UrlMaps.Patch. + The request object. A request message for UrlMaps.Patch. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -601,15 +597,14 @@ def patch( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.PatchUrlMapRequest.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() if v - ] + 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 @@ -631,8 +626,7 @@ def update( Args: request (~.compute.UpdateUrlMapRequest): - The request object. - A request message for UrlMaps.Update. + The request object. A request message for UrlMaps.Update. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -686,15 +680,14 @@ def update( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.UpdateUrlMapRequest.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() if v - ] + 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 @@ -716,8 +709,7 @@ def validate( Args: request (~.compute.ValidateUrlMapRequest): - The request object. - A request message for + The request object. A request message for UrlMaps.Validate. See the method description for details. @@ -745,12 +737,11 @@ def validate( # 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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/vpn_gateways/__init__.py b/google/cloud/compute_v1/services/vpn_gateways/__init__.py index 08aa9a2da..2dbccedce 100644 --- a/google/cloud/compute_v1/services/vpn_gateways/__init__.py +++ b/google/cloud/compute_v1/services/vpn_gateways/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import VpnGatewaysClient __all__ = ("VpnGatewaysClient",) diff --git a/google/cloud/compute_v1/services/vpn_gateways/client.py b/google/cloud/compute_v1/services/vpn_gateways/client.py index 84d7fcfa4..5a67d88ca 100644 --- a/google/cloud/compute_v1/services/vpn_gateways/client.py +++ b/google/cloud/compute_v1/services/vpn_gateways/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.vpn_gateways import pagers from google.cloud.compute_v1.types import compute - from .transports.base import VpnGatewaysTransport, DEFAULT_CLIENT_INFO from .transports.rest import VpnGatewaysRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, VpnGatewaysTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -344,7 +341,6 @@ def aggregated_list( 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. @@ -374,10 +370,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListVpnGatewaysRequest): request = compute.AggregatedListVpnGatewaysRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -430,7 +424,6 @@ def delete( This corresponds to the ``vpn_gateway`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -482,10 +475,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteVpnGatewayRequest): request = compute.DeleteVpnGatewayRequest(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: @@ -536,7 +527,6 @@ def get( This corresponds to the ``vpn_gateway`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -572,10 +562,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetVpnGatewayRequest): request = compute.GetVpnGatewayRequest(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: @@ -626,7 +614,6 @@ def get_status( This corresponds to the ``vpn_gateway`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -653,10 +640,8 @@ def get_status( # there are no flattened fields. if not isinstance(request, compute.GetStatusVpnGatewayRequest): request = compute.GetStatusVpnGatewayRequest(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: @@ -708,7 +693,6 @@ def insert( This corresponds to the ``vpn_gateway_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. @@ -760,10 +744,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertVpnGatewayRequest): request = compute.InsertVpnGatewayRequest(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: @@ -809,7 +791,6 @@ def list( 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. @@ -841,10 +822,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListVpnGatewaysRequest): request = compute.ListVpnGatewaysRequest(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: @@ -908,7 +887,6 @@ def set_labels( 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. @@ -962,10 +940,8 @@ def set_labels( # there are no flattened fields. if not isinstance(request, compute.SetLabelsVpnGatewayRequest): request = compute.SetLabelsVpnGatewayRequest(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: @@ -1031,7 +1007,6 @@ def test_iam_permissions( 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. @@ -1060,10 +1035,8 @@ def test_iam_permissions( # there are no flattened fields. if not isinstance(request, compute.TestIamPermissionsVpnGatewayRequest): request = compute.TestIamPermissionsVpnGatewayRequest(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: diff --git a/google/cloud/compute_v1/services/vpn_gateways/pagers.py b/google/cloud/compute_v1/services/vpn_gateways/pagers.py index 8e414a067..e8f6cc966 100644 --- a/google/cloud/compute_v1/services/vpn_gateways/pagers.py +++ b/google/cloud/compute_v1/services/vpn_gateways/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/vpn_gateways/transports/__init__.py b/google/cloud/compute_v1/services/vpn_gateways/transports/__init__.py index 9608ab89f..0089a0aa3 100644 --- a/google/cloud/compute_v1/services/vpn_gateways/transports/__init__.py +++ b/google/cloud/compute_v1/services/vpn_gateways/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/vpn_gateways/transports/base.py b/google/cloud/compute_v1/services/vpn_gateways/transports/base.py index bc559d6c3..effc0dec4 100644 --- a/google/cloud/compute_v1/services/vpn_gateways/transports/base.py +++ b/google/cloud/compute_v1/services/vpn_gateways/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class VpnGatewaysTransport(abc.ABC): """Abstract transport class for VpnGateways.""" @@ -44,21 +54,24 @@ class VpnGatewaysTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -138,11 +198,11 @@ def _prep_wrapped_messages(self, client_info): @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListVpnGatewaysRequest], - typing.Union[ + Union[ compute.VpnGatewayAggregatedList, - typing.Awaitable[compute.VpnGatewayAggregatedList], + Awaitable[compute.VpnGatewayAggregatedList], ], ]: raise NotImplementedError() @@ -150,29 +210,29 @@ def aggregated_list( @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteVpnGatewayRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetVpnGatewayRequest], - typing.Union[compute.VpnGateway, typing.Awaitable[compute.VpnGateway]], + Union[compute.VpnGateway, Awaitable[compute.VpnGateway]], ]: raise NotImplementedError() @property def get_status( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetStatusVpnGatewayRequest], - typing.Union[ + Union[ compute.VpnGatewaysGetStatusResponse, - typing.Awaitable[compute.VpnGatewaysGetStatusResponse], + Awaitable[compute.VpnGatewaysGetStatusResponse], ], ]: raise NotImplementedError() @@ -180,38 +240,37 @@ def get_status( @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertVpnGatewayRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListVpnGatewaysRequest], - typing.Union[compute.VpnGatewayList, typing.Awaitable[compute.VpnGatewayList]], + Union[compute.VpnGatewayList, Awaitable[compute.VpnGatewayList]], ]: raise NotImplementedError() @property def set_labels( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.SetLabelsVpnGatewayRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.TestIamPermissionsVpnGatewayRequest], - typing.Union[ - compute.TestPermissionsResponse, - typing.Awaitable[compute.TestPermissionsResponse], + Union[ + compute.TestPermissionsResponse, Awaitable[compute.TestPermissionsResponse] ], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/vpn_gateways/transports/rest.py b/google/cloud/compute_v1/services/vpn_gateways/transports/rest.py index 2b48bc276..9095b070e 100644 --- a/google/cloud/compute_v1/services/vpn_gateways/transports/rest.py +++ b/google/cloud/compute_v1/services/vpn_gateways/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 VpnGatewaysTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListVpnGatewaysRequest): - The request object. - A request message for + The request object. A request message for VpnGateways.AggregatedList. See the method description for details. @@ -124,24 +123,28 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListVpnGatewaysRequest.filter in request: + query_params["filter"] = request.filter + if compute.AggregatedListVpnGatewaysRequest.include_all_scopes in request: + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListVpnGatewaysRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListVpnGatewaysRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListVpnGatewaysRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.AggregatedListVpnGatewaysRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -161,8 +164,7 @@ def delete( Args: request (~.compute.DeleteVpnGatewayRequest): - The request object. - A request message for + The request object. A request message for VpnGateways.Delete. See the method description for details. @@ -213,19 +215,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteVpnGatewayRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -243,8 +244,7 @@ def get( Args: request (~.compute.GetVpnGatewayRequest): - The request object. - A request message for + The request object. A request message for VpnGateways.Get. See the method description for details. @@ -277,16 +277,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -306,8 +305,7 @@ def get_status( Args: request (~.compute.GetStatusVpnGatewayRequest): - The request object. - A request message for + The request object. A request message for VpnGateways.GetStatus. See the method description for details. @@ -331,16 +329,15 @@ def get_status( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -360,8 +357,7 @@ def insert( Args: request (~.compute.InsertVpnGatewayRequest): - The request object. - A request message for + The request object. A request message for VpnGateways.Insert. See the method description for details. @@ -416,15 +412,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertVpnGatewayRequest.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() if v - ] + 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 @@ -446,8 +441,7 @@ def list( Args: request (~.compute.ListVpnGatewaysRequest): - The request object. - A request message for + The request object. A request message for VpnGateways.List. See the method description for details. @@ -469,23 +463,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListVpnGatewaysRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListVpnGatewaysRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListVpnGatewaysRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListVpnGatewaysRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListVpnGatewaysRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -505,8 +502,7 @@ def set_labels( Args: request (~.compute.SetLabelsVpnGatewayRequest): - The request object. - A request message for + The request object. A request message for VpnGateways.SetLabels. See the method description for details. @@ -564,15 +560,14 @@ def set_labels( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.SetLabelsVpnGatewayRequest.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() if v - ] + 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 @@ -594,8 +589,7 @@ def test_iam_permissions( Args: request (~.compute.TestIamPermissionsVpnGatewayRequest): - The request object. - A request message for + The request object. A request message for VpnGateways.TestIamPermissions. See the method description for details. @@ -626,12 +620,11 @@ def test_iam_permissions( # 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() if v - ] + 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 diff --git a/google/cloud/compute_v1/services/vpn_tunnels/__init__.py b/google/cloud/compute_v1/services/vpn_tunnels/__init__.py index 8907b9c16..6d0286c9f 100644 --- a/google/cloud/compute_v1/services/vpn_tunnels/__init__.py +++ b/google/cloud/compute_v1/services/vpn_tunnels/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import VpnTunnelsClient __all__ = ("VpnTunnelsClient",) diff --git a/google/cloud/compute_v1/services/vpn_tunnels/client.py b/google/cloud/compute_v1/services/vpn_tunnels/client.py index af6863525..a805f8b4b 100644 --- a/google/cloud/compute_v1/services/vpn_tunnels/client.py +++ b/google/cloud/compute_v1/services/vpn_tunnels/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.vpn_tunnels import pagers from google.cloud.compute_v1.types import compute - from .transports.base import VpnTunnelsTransport, DEFAULT_CLIENT_INFO from .transports.rest import VpnTunnelsRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, VpnTunnelsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -344,7 +341,6 @@ def aggregated_list( 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. @@ -374,10 +370,8 @@ def aggregated_list( # there are no flattened fields. if not isinstance(request, compute.AggregatedListVpnTunnelsRequest): request = compute.AggregatedListVpnTunnelsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project @@ -432,7 +426,6 @@ def delete( This corresponds to the ``vpn_tunnel`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -484,10 +477,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteVpnTunnelRequest): request = compute.DeleteVpnTunnelRequest(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: @@ -540,7 +531,6 @@ def get( This corresponds to the ``vpn_tunnel`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -572,10 +562,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetVpnTunnelRequest): request = compute.GetVpnTunnelRequest(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: @@ -627,7 +615,6 @@ def insert( This corresponds to the ``vpn_tunnel_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. @@ -679,10 +666,8 @@ def insert( # there are no flattened fields. if not isinstance(request, compute.InsertVpnTunnelRequest): request = compute.InsertVpnTunnelRequest(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: @@ -727,7 +712,6 @@ def list( 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. @@ -759,10 +743,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListVpnTunnelsRequest): request = compute.ListVpnTunnelsRequest(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: diff --git a/google/cloud/compute_v1/services/vpn_tunnels/pagers.py b/google/cloud/compute_v1/services/vpn_tunnels/pagers.py index 13780f8d6..f6c2be400 100644 --- a/google/cloud/compute_v1/services/vpn_tunnels/pagers.py +++ b/google/cloud/compute_v1/services/vpn_tunnels/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/vpn_tunnels/transports/__init__.py b/google/cloud/compute_v1/services/vpn_tunnels/transports/__init__.py index 5005ed172..a851bbf3d 100644 --- a/google/cloud/compute_v1/services/vpn_tunnels/transports/__init__.py +++ b/google/cloud/compute_v1/services/vpn_tunnels/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/vpn_tunnels/transports/base.py b/google/cloud/compute_v1/services/vpn_tunnels/transports/base.py index 7bb0f9e70..cf36f3605 100644 --- a/google/cloud/compute_v1/services/vpn_tunnels/transports/base.py +++ b/google/cloud/compute_v1/services/vpn_tunnels/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class VpnTunnelsTransport(abc.ABC): """Abstract transport class for VpnTunnels.""" @@ -44,21 +54,24 @@ class VpnTunnelsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -127,11 +187,10 @@ def _prep_wrapped_messages(self, client_info): @property def aggregated_list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.AggregatedListVpnTunnelsRequest], - typing.Union[ - compute.VpnTunnelAggregatedList, - typing.Awaitable[compute.VpnTunnelAggregatedList], + Union[ + compute.VpnTunnelAggregatedList, Awaitable[compute.VpnTunnelAggregatedList] ], ]: raise NotImplementedError() @@ -139,36 +198,36 @@ def aggregated_list( @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteVpnTunnelRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetVpnTunnelRequest], - typing.Union[compute.VpnTunnel, typing.Awaitable[compute.VpnTunnel]], + Union[compute.VpnTunnel, Awaitable[compute.VpnTunnel]], ]: raise NotImplementedError() @property def insert( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.InsertVpnTunnelRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListVpnTunnelsRequest], - typing.Union[compute.VpnTunnelList, typing.Awaitable[compute.VpnTunnelList]], + Union[compute.VpnTunnelList, Awaitable[compute.VpnTunnelList]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/vpn_tunnels/transports/rest.py b/google/cloud/compute_v1/services/vpn_tunnels/transports/rest.py index a0e9d43d3..4879f5062 100644 --- a/google/cloud/compute_v1/services/vpn_tunnels/transports/rest.py +++ b/google/cloud/compute_v1/services/vpn_tunnels/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 VpnTunnelsTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def aggregated_list( Args: request (~.compute.AggregatedListVpnTunnelsRequest): - The request object. - A request message for + The request object. A request message for VpnTunnels.AggregatedList. See the method description for details. @@ -124,24 +123,28 @@ def aggregated_list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "includeAllScopes": request.include_all_scopes, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.AggregatedListVpnTunnelsRequest.filter in request: + query_params["filter"] = request.filter + if compute.AggregatedListVpnTunnelsRequest.include_all_scopes in request: + query_params["includeAllScopes"] = request.include_all_scopes + if compute.AggregatedListVpnTunnelsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.AggregatedListVpnTunnelsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.AggregatedListVpnTunnelsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.AggregatedListVpnTunnelsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -161,8 +164,7 @@ def delete( Args: request (~.compute.DeleteVpnTunnelRequest): - The request object. - A request message for + The request object. A request message for VpnTunnels.Delete. See the method description for details. @@ -213,19 +215,18 @@ def delete( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.DeleteVpnTunnelRequest.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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -243,8 +244,7 @@ def get( Args: request (~.compute.GetVpnTunnelRequest): - The request object. - A request message for VpnTunnels.Get. + The request object. A request message for VpnTunnels.Get. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -271,16 +271,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -298,8 +297,7 @@ def insert( Args: request (~.compute.InsertVpnTunnelRequest): - The request object. - A request message for + The request object. A request message for VpnTunnels.Insert. See the method description for details. @@ -354,15 +352,14 @@ def insert( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "requestId": request.request_id, - } + query_params = {} + if compute.InsertVpnTunnelRequest.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() if v - ] + 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 @@ -384,8 +381,7 @@ def list( Args: request (~.compute.ListVpnTunnelsRequest): - The request object. - A request message for + The request object. A request message for VpnTunnels.List. See the method description for details. @@ -407,23 +403,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListVpnTunnelsRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListVpnTunnelsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListVpnTunnelsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListVpnTunnelsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListVpnTunnelsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() diff --git a/google/cloud/compute_v1/services/zone_operations/__init__.py b/google/cloud/compute_v1/services/zone_operations/__init__.py index c45854f44..5cf5b06c5 100644 --- a/google/cloud/compute_v1/services/zone_operations/__init__.py +++ b/google/cloud/compute_v1/services/zone_operations/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import ZoneOperationsClient __all__ = ("ZoneOperationsClient",) diff --git a/google/cloud/compute_v1/services/zone_operations/client.py b/google/cloud/compute_v1/services/zone_operations/client.py index 38e20d474..e62b4006b 100644 --- a/google/cloud/compute_v1/services/zone_operations/client.py +++ b/google/cloud/compute_v1/services/zone_operations/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.zone_operations import pagers from google.cloud.compute_v1.types import compute - from .transports.base import ZoneOperationsTransport, DEFAULT_CLIENT_INFO from .transports.rest import ZoneOperationsRestTransport @@ -215,7 +212,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ZoneOperationsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -361,7 +358,6 @@ def delete( This corresponds to the ``operation`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -391,10 +387,8 @@ def delete( # there are no flattened fields. if not isinstance(request, compute.DeleteZoneOperationRequest): request = compute.DeleteZoneOperationRequest(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: @@ -448,7 +442,6 @@ def get( This corresponds to the ``operation`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -500,10 +493,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetZoneOperationRequest): request = compute.GetZoneOperationRequest(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: @@ -549,7 +540,6 @@ def list( This corresponds to the ``zone`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -581,10 +571,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListZoneOperationsRequest): request = compute.ListZoneOperationsRequest(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: @@ -655,7 +643,6 @@ def wait( This corresponds to the ``operation`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -707,10 +694,8 @@ def wait( # there are no flattened fields. if not isinstance(request, compute.WaitZoneOperationRequest): request = compute.WaitZoneOperationRequest(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: diff --git a/google/cloud/compute_v1/services/zone_operations/pagers.py b/google/cloud/compute_v1/services/zone_operations/pagers.py index 62db29079..e4c89f59a 100644 --- a/google/cloud/compute_v1/services/zone_operations/pagers.py +++ b/google/cloud/compute_v1/services/zone_operations/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/zone_operations/transports/__init__.py b/google/cloud/compute_v1/services/zone_operations/transports/__init__.py index 54c46a5ce..17122ac81 100644 --- a/google/cloud/compute_v1/services/zone_operations/transports/__init__.py +++ b/google/cloud/compute_v1/services/zone_operations/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/zone_operations/transports/base.py b/google/cloud/compute_v1/services/zone_operations/transports/base.py index 3b04a2bfb..f2f3ddcdb 100644 --- a/google/cloud/compute_v1/services/zone_operations/transports/base.py +++ b/google/cloud/compute_v1/services/zone_operations/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class ZoneOperationsTransport(abc.ABC): """Abstract transport class for ZoneOperations.""" @@ -44,21 +54,24 @@ class ZoneOperationsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -67,13 +80,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -81,28 +94,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -124,11 +184,11 @@ def _prep_wrapped_messages(self, client_info): @property def delete( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.DeleteZoneOperationRequest], - typing.Union[ + Union[ compute.DeleteZoneOperationResponse, - typing.Awaitable[compute.DeleteZoneOperationResponse], + Awaitable[compute.DeleteZoneOperationResponse], ], ]: raise NotImplementedError() @@ -136,27 +196,27 @@ def delete( @property def get( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.GetZoneOperationRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.ListZoneOperationsRequest], - typing.Union[compute.OperationList, typing.Awaitable[compute.OperationList]], + Union[compute.OperationList, Awaitable[compute.OperationList]], ]: raise NotImplementedError() @property def wait( self, - ) -> typing.Callable[ + ) -> Callable[ [compute.WaitZoneOperationRequest], - typing.Union[compute.Operation, typing.Awaitable[compute.Operation]], + Union[compute.Operation, Awaitable[compute.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/zone_operations/transports/rest.py b/google/cloud/compute_v1/services/zone_operations/transports/rest.py index 016f53020..d3810bef0 100644 --- a/google/cloud/compute_v1/services/zone_operations/transports/rest.py +++ b/google/cloud/compute_v1/services/zone_operations/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 ZoneOperationsTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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, @@ -103,8 +103,7 @@ def delete( Args: request (~.compute.DeleteZoneOperationRequest): - The request object. - A request message for + The request object. A request message for ZoneOperations.Delete. See the method description for details. @@ -131,16 +130,15 @@ def delete( # 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() if v - ] + 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 - response = self._session.delete(url) + response = self._session.delete(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -160,8 +158,7 @@ def get( Args: request (~.compute.GetZoneOperationRequest): - The request object. - A request message for + The request object. A request message for ZoneOperations.Get. See the method description for details. @@ -213,16 +210,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -240,8 +236,7 @@ def list( Args: request (~.compute.ListZoneOperationsRequest): - The request object. - A request message for + The request object. A request message for ZoneOperations.List. See the method description for details. @@ -263,23 +258,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListZoneOperationsRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListZoneOperationsRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListZoneOperationsRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListZoneOperationsRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListZoneOperationsRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -299,8 +297,7 @@ def wait( Args: request (~.compute.WaitZoneOperationRequest): - The request object. - A request message for + The request object. A request message for ZoneOperations.Wait. See the method description for details. @@ -352,16 +349,15 @@ def wait( # 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() if v - ] + 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 - response = self._session.post(url) + response = self._session.post(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() diff --git a/google/cloud/compute_v1/services/zones/__init__.py b/google/cloud/compute_v1/services/zones/__init__.py index 077a20d19..d0f4097fc 100644 --- a/google/cloud/compute_v1/services/zones/__init__.py +++ b/google/cloud/compute_v1/services/zones/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import ZonesClient __all__ = ("ZonesClient",) diff --git a/google/cloud/compute_v1/services/zones/client.py b/google/cloud/compute_v1/services/zones/client.py index fec06f719..9e8f5ffb9 100644 --- a/google/cloud/compute_v1/services/zones/client.py +++ b/google/cloud/compute_v1/services/zones/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -34,7 +32,6 @@ from google.cloud.compute_v1.services.zones import pagers from google.cloud.compute_v1.types import compute - from .transports.base import ZonesTransport, DEFAULT_CLIENT_INFO from .transports.rest import ZonesRestTransport @@ -213,7 +210,7 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ZonesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -350,7 +347,6 @@ def get( This corresponds to the ``zone`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -384,10 +380,8 @@ def get( # there are no flattened fields. if not isinstance(request, compute.GetZoneRequest): request = compute.GetZoneRequest(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: @@ -424,7 +418,6 @@ def list( 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. @@ -455,10 +448,8 @@ def list( # there are no flattened fields. if not isinstance(request, compute.ListZonesRequest): request = compute.ListZonesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if project is not None: request.project = project diff --git a/google/cloud/compute_v1/services/zones/pagers.py b/google/cloud/compute_v1/services/zones/pagers.py index 8ed009ba3..46507215f 100644 --- a/google/cloud/compute_v1/services/zones/pagers.py +++ b/google/cloud/compute_v1/services/zones/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, diff --git a/google/cloud/compute_v1/services/zones/transports/__init__.py b/google/cloud/compute_v1/services/zones/transports/__init__.py index 394c7383d..f59d06c66 100644 --- a/google/cloud/compute_v1/services/zones/transports/__init__.py +++ b/google/cloud/compute_v1/services/zones/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/compute_v1/services/zones/transports/base.py b/google/cloud/compute_v1/services/zones/transports/base.py index 484ddb0bd..c2e20fd17 100644 --- a/google/cloud/compute_v1/services/zones/transports/base.py +++ b/google/cloud/compute_v1/services/zones/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # 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, @@ -35,6 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class ZonesTransport(abc.ABC): """Abstract transport class for Zones.""" @@ -45,21 +55,24 @@ class ZonesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform", ) + DEFAULT_HOST: str = "compute.googleapis.com" + def __init__( self, *, - host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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. + 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 @@ -68,13 +81,13 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + 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. @@ -82,28 +95,75 @@ def __init__( 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 exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are 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. + + # 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 + + # 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. @@ -119,18 +179,16 @@ def _prep_wrapped_messages(self, client_info): @property def get( self, - ) -> typing.Callable[ - [compute.GetZoneRequest], - typing.Union[compute.Zone, typing.Awaitable[compute.Zone]], + ) -> Callable[ + [compute.GetZoneRequest], Union[compute.Zone, Awaitable[compute.Zone]] ]: raise NotImplementedError() @property def list( self, - ) -> typing.Callable[ - [compute.ListZonesRequest], - typing.Union[compute.ZoneList, typing.Awaitable[compute.ZoneList]], + ) -> Callable[ + [compute.ListZonesRequest], Union[compute.ZoneList, Awaitable[compute.ZoneList]] ]: raise NotImplementedError() diff --git a/google/cloud/compute_v1/services/zones/transports/rest.py b/google/cloud/compute_v1/services/zones/transports/rest.py index 523ef1183..e5d35f7f6 100644 --- a/google/cloud/compute_v1/services/zones/transports/rest.py +++ b/google/cloud/compute_v1/services/zones/transports/rest.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,19 @@ # 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 import auth # type: ignore -from google.auth import credentials # 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 ZonesTransport, DEFAULT_CLIENT_INFO @@ -51,7 +45,7 @@ def __init__( self, *, host: str = "compute.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, @@ -61,7 +55,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -78,20 +73,25 @@ def __init__( 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 + 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) + 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 get( self, @@ -103,8 +103,7 @@ def get( Args: request (~.compute.GetZoneRequest): - The request object. - A request message for Zones.Get. See + The request object. A request message for Zones.Get. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -131,16 +130,15 @@ def get( # 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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() @@ -158,8 +156,7 @@ def list( Args: request (~.compute.ListZonesRequest): - The request object. - A request message for Zones.List. See + The request object. A request message for Zones.List. See the method description for details. metadata (Sequence[Tuple[str, str]]): Strings which should be @@ -178,23 +175,26 @@ def list( # TODO(yon-mg): handle nested fields corerctly rather than using only top level fields # not required for GCE - query_params = { - "filter": request.filter, - "maxResults": request.max_results, - "orderBy": request.order_by, - "pageToken": request.page_token, - "returnPartialSuccess": request.return_partial_success, - } + query_params = {} + if compute.ListZonesRequest.filter in request: + query_params["filter"] = request.filter + if compute.ListZonesRequest.max_results in request: + query_params["maxResults"] = request.max_results + if compute.ListZonesRequest.order_by in request: + query_params["orderBy"] = request.order_by + if compute.ListZonesRequest.page_token in request: + query_params["pageToken"] = request.page_token + if compute.ListZonesRequest.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() if v - ] + 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 - response = self._session.get(url) + response = self._session.get(url,) # Raise requests.exceptions.HTTPError if the status code is >= 400 response.raise_for_status() diff --git a/google/cloud/compute_v1/types/__init__.py b/google/cloud/compute_v1/types/__init__.py index 33c076398..2e2e4277b 100644 --- a/google/cloud/compute_v1/types/__init__.py +++ b/google/cloud/compute_v1/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,357 +13,750 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .compute import ( + AbandonInstancesInstanceGroupManagerRequest, + AbandonInstancesRegionInstanceGroupManagerRequest, AcceleratorConfig, - DeprecationStatus, + Accelerators, AcceleratorType, - AcceleratorTypesScopedList, - Data, - Warning, AcceleratorTypeAggregatedList, AcceleratorTypeList, + AcceleratorTypesScopedList, AccessConfig, + AddAccessConfigInstanceRequest, + AddHealthCheckTargetPoolRequest, + AddInstancesInstanceGroupRequest, + AddInstanceTargetPoolRequest, + AddNodesNodeGroupRequest, + AddPeeringNetworkRequest, + AddResourcePoliciesDiskRequest, + AddResourcePoliciesInstanceRequest, + AddResourcePoliciesRegionDiskRequest, Address, - AddressesScopedList, AddressAggregatedList, + AddressesScopedList, AddressList, + AddRuleSecurityPolicyRequest, + AddSignedUrlKeyBackendBucketRequest, + AddSignedUrlKeyBackendServiceRequest, + AggregatedListAcceleratorTypesRequest, + AggregatedListAddressesRequest, + AggregatedListAutoscalersRequest, + AggregatedListBackendServicesRequest, + AggregatedListDisksRequest, + AggregatedListDiskTypesRequest, + AggregatedListForwardingRulesRequest, + AggregatedListGlobalOperationsRequest, + AggregatedListHealthChecksRequest, + AggregatedListInstanceGroupManagersRequest, + AggregatedListInstanceGroupsRequest, + AggregatedListInstancesRequest, + AggregatedListInterconnectAttachmentsRequest, + AggregatedListMachineTypesRequest, + AggregatedListNetworkEndpointGroupsRequest, + AggregatedListNodeGroupsRequest, + AggregatedListNodeTemplatesRequest, + AggregatedListNodeTypesRequest, + AggregatedListPacketMirroringsRequest, + AggregatedListRegionCommitmentsRequest, + AggregatedListReservationsRequest, + AggregatedListResourcePoliciesRequest, + AggregatedListRoutersRequest, + AggregatedListSslCertificatesRequest, + AggregatedListSubnetworksRequest, + AggregatedListTargetHttpProxiesRequest, + AggregatedListTargetHttpsProxiesRequest, + AggregatedListTargetInstancesRequest, + AggregatedListTargetPoolsRequest, + AggregatedListTargetVpnGatewaysRequest, + AggregatedListUrlMapsRequest, + AggregatedListVpnGatewaysRequest, + AggregatedListVpnTunnelsRequest, AliasIpRange, AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk, AllocationSpecificSKUAllocationReservedInstanceProperties, AllocationSpecificSKUReservation, - CustomerEncryptionKey, - GuestOsFeature, - AttachedDiskInitializeParams, - InitialStateConfig, + Allowed, + ApplyUpdatesToInstancesInstanceGroupManagerRequest, + ApplyUpdatesToInstancesRegionInstanceGroupManagerRequest, + AttachDiskInstanceRequest, AttachedDisk, - AuditLogConfig, + AttachedDiskInitializeParams, + AttachNetworkEndpointsGlobalNetworkEndpointGroupRequest, + AttachNetworkEndpointsNetworkEndpointGroupRequest, AuditConfig, + AuditLogConfig, AuthorizationLoggingOptions, - AutoscalingPolicy, - AutoscalerStatusDetails, Autoscaler, - AutoscalersScopedList, AutoscalerAggregatedList, AutoscalerList, + AutoscalersScopedList, + AutoscalerStatusDetails, + AutoscalingPolicy, AutoscalingPolicyCpuUtilization, AutoscalingPolicyCustomMetricUtilization, AutoscalingPolicyLoadBalancingUtilization, AutoscalingPolicyScaleInControl, - FixedOrPercent, Backend, - BackendBucketCdnPolicy, BackendBucket, + BackendBucketCdnPolicy, BackendBucketList, - BackendServiceCdnPolicy, - CircuitBreakers, - ConnectionDraining, - ConsistentHashLoadBalancerSettings, - BackendServiceFailoverPolicy, - BackendServiceIAP, - BackendServiceLogConfig, - OutlierDetection, - SecuritySettings, BackendService, - BackendServicesScopedList, BackendServiceAggregatedList, - CacheKeyPolicy, - HealthStatus, + BackendServiceCdnPolicy, + BackendServiceFailoverPolicy, BackendServiceGroupHealth, + BackendServiceIAP, BackendServiceList, + BackendServiceLogConfig, BackendServiceReference, - Expr, + BackendServicesScopedList, Binding, CacheInvalidationRule, - LicenseResourceCommitment, - Reservation, - ResourceCommitment, + CacheKeyPolicy, + CircuitBreakers, Commitment, - CommitmentsScopedList, CommitmentAggregatedList, CommitmentList, + CommitmentsScopedList, Condition, ConfidentialInstanceConfig, + ConnectionDraining, + ConsistentHashLoadBalancerSettings, ConsistentHashLoadBalancerSettingsHttpCookie, - Duration, CorsPolicy, + CreateInstancesInstanceGroupManagerRequest, + CreateInstancesRegionInstanceGroupManagerRequest, + CreateSnapshotDiskRequest, + CreateSnapshotRegionDiskRequest, + CustomerEncryptionKey, CustomerEncryptionKeyProtectedDisk, + Data, + DeleteAccessConfigInstanceRequest, + DeleteAddressRequest, + DeleteAutoscalerRequest, + DeleteBackendBucketRequest, + DeleteBackendServiceRequest, + DeleteDiskRequest, + DeleteExternalVpnGatewayRequest, + DeleteFirewallRequest, + DeleteForwardingRuleRequest, + DeleteGlobalAddressRequest, + DeleteGlobalForwardingRuleRequest, + DeleteGlobalNetworkEndpointGroupRequest, + DeleteGlobalOperationRequest, + DeleteGlobalOperationResponse, + DeleteGlobalOrganizationOperationRequest, + DeleteGlobalOrganizationOperationResponse, + DeleteHealthCheckRequest, + DeleteImageRequest, + DeleteInstanceGroupManagerRequest, + DeleteInstanceGroupRequest, + DeleteInstanceRequest, + DeleteInstancesInstanceGroupManagerRequest, + DeleteInstancesRegionInstanceGroupManagerRequest, + DeleteInstanceTemplateRequest, + DeleteInterconnectAttachmentRequest, + DeleteInterconnectRequest, + DeleteLicenseRequest, + DeleteNetworkEndpointGroupRequest, + DeleteNetworkRequest, + DeleteNodeGroupRequest, + DeleteNodesNodeGroupRequest, + DeleteNodeTemplateRequest, + DeletePacketMirroringRequest, + DeletePerInstanceConfigsInstanceGroupManagerRequest, + DeletePerInstanceConfigsRegionInstanceGroupManagerRequest, + DeleteRegionAutoscalerRequest, + DeleteRegionBackendServiceRequest, + DeleteRegionDiskRequest, + DeleteRegionHealthCheckRequest, + DeleteRegionHealthCheckServiceRequest, + DeleteRegionInstanceGroupManagerRequest, + DeleteRegionNetworkEndpointGroupRequest, + DeleteRegionNotificationEndpointRequest, + DeleteRegionOperationRequest, + DeleteRegionOperationResponse, + DeleteRegionSslCertificateRequest, + DeleteRegionTargetHttpProxyRequest, + DeleteRegionTargetHttpsProxyRequest, + DeleteRegionUrlMapRequest, + DeleteReservationRequest, + DeleteResourcePolicyRequest, + DeleteRouteRequest, + DeleteRouterRequest, + DeleteSecurityPolicyRequest, + DeleteSignedUrlKeyBackendBucketRequest, + DeleteSignedUrlKeyBackendServiceRequest, + DeleteSnapshotRequest, + DeleteSslCertificateRequest, + DeleteSslPolicyRequest, + DeleteSubnetworkRequest, + DeleteTargetGrpcProxyRequest, + DeleteTargetHttpProxyRequest, + DeleteTargetHttpsProxyRequest, + DeleteTargetInstanceRequest, + DeleteTargetPoolRequest, + DeleteTargetSslProxyRequest, + DeleteTargetTcpProxyRequest, + DeleteTargetVpnGatewayRequest, + DeleteUrlMapRequest, + DeleteVpnGatewayRequest, + DeleteVpnTunnelRequest, + DeleteZoneOperationRequest, + DeleteZoneOperationResponse, + Denied, + DeprecateImageRequest, + DeprecationStatus, + DetachDiskInstanceRequest, + DetachNetworkEndpointsGlobalNetworkEndpointGroupRequest, + DetachNetworkEndpointsNetworkEndpointGroupRequest, + DisableXpnHostProjectRequest, + DisableXpnResourceProjectRequest, Disk, - DisksScopedList, DiskAggregatedList, DiskInstantiationConfig, DiskList, DiskMoveRequest, - DiskType, - DiskTypesScopedList, - DiskTypeAggregatedList, - DiskTypeList, DisksAddResourcePoliciesRequest, DisksRemoveResourcePoliciesRequest, DisksResizeRequest, + DisksScopedList, + DiskType, + DiskTypeAggregatedList, + DiskTypeList, + DiskTypesScopedList, DisplayDevice, - DistributionPolicyZoneConfiguration, DistributionPolicy, + DistributionPolicyZoneConfiguration, + Duration, + EnableXpnHostProjectRequest, + EnableXpnResourceProjectRequest, + Error, + Errors, ExchangedPeeringRoute, ExchangedPeeringRoutesList, - ExternalVpnGatewayInterface, + ExpandIpCidrRangeSubnetworkRequest, + Expr, ExternalVpnGateway, + ExternalVpnGatewayInterface, ExternalVpnGatewayList, FileContentBuffer, - Allowed, - Denied, - FirewallLogConfig, Firewall, FirewallList, - MetadataFilter, + FirewallLogConfig, + FixedOrPercent, ForwardingRule, - ForwardingRulesScopedList, ForwardingRuleAggregatedList, ForwardingRuleList, ForwardingRuleReference, - GRPCHealthCheck, - NetworkEndpoint, - GlobalNetworkEndpointGroupsAttachEndpointsRequest, - GlobalNetworkEndpointGroupsDetachEndpointsRequest, - GlobalSetLabelsRequest, - Policy, - GlobalSetPolicyRequest, - GuestAttributesValue, - GuestAttributes, - GuestAttributesEntry, - HTTP2HealthCheck, - HTTPHealthCheck, - HTTPSHealthCheck, - HealthCheckLogConfig, - SSLHealthCheck, - TCPHealthCheck, - HealthCheck, - HealthCheckList, - HealthCheckReference, - HealthCheckService, - HealthCheckServiceReference, - HealthCheckServicesList, - HealthChecksScopedList, - HealthChecksAggregatedList, - HealthStatusForNetworkEndpoint, - HostRule, - HttpFaultAbort, - HttpFaultDelay, - HttpFaultInjection, - HttpHeaderOption, - HttpHeaderAction, - Int64RangeMatch, - HttpHeaderMatch, - HttpQueryParameterMatch, + ForwardingRulesScopedList, + GetAcceleratorTypeRequest, + GetAddressRequest, + GetAutoscalerRequest, + GetBackendBucketRequest, + GetBackendServiceRequest, + GetDiagnosticsInterconnectRequest, + GetDiskRequest, + GetDiskTypeRequest, + GetExternalVpnGatewayRequest, + GetFirewallRequest, + GetForwardingRuleRequest, + GetFromFamilyImageRequest, + GetGlobalAddressRequest, + GetGlobalForwardingRuleRequest, + GetGlobalNetworkEndpointGroupRequest, + GetGlobalOperationRequest, + GetGlobalOrganizationOperationRequest, + GetGuestAttributesInstanceRequest, + GetHealthBackendServiceRequest, + GetHealthCheckRequest, + GetHealthRegionBackendServiceRequest, + GetHealthTargetPoolRequest, + GetIamPolicyDiskRequest, + GetIamPolicyImageRequest, + GetIamPolicyInstanceRequest, + GetIamPolicyInstanceTemplateRequest, + GetIamPolicyLicenseRequest, + GetIamPolicyNodeGroupRequest, + GetIamPolicyNodeTemplateRequest, + GetIamPolicyRegionDiskRequest, + GetIamPolicyReservationRequest, + GetIamPolicyResourcePolicyRequest, + GetIamPolicySnapshotRequest, + GetIamPolicySubnetworkRequest, + GetImageRequest, + GetInstanceGroupManagerRequest, + GetInstanceGroupRequest, + GetInstanceRequest, + GetInstanceTemplateRequest, + GetInterconnectAttachmentRequest, + GetInterconnectLocationRequest, + GetInterconnectRequest, + GetLicenseCodeRequest, + GetLicenseRequest, + GetMachineTypeRequest, + GetNatMappingInfoRoutersRequest, + GetNetworkEndpointGroupRequest, + GetNetworkRequest, + GetNodeGroupRequest, + GetNodeTemplateRequest, + GetNodeTypeRequest, + GetPacketMirroringRequest, + GetProjectRequest, + GetRegionAutoscalerRequest, + GetRegionBackendServiceRequest, + GetRegionCommitmentRequest, + GetRegionDiskRequest, + GetRegionDiskTypeRequest, + GetRegionHealthCheckRequest, + GetRegionHealthCheckServiceRequest, + GetRegionInstanceGroupManagerRequest, + GetRegionInstanceGroupRequest, + GetRegionNetworkEndpointGroupRequest, + GetRegionNotificationEndpointRequest, + GetRegionOperationRequest, + GetRegionRequest, + GetRegionSslCertificateRequest, + GetRegionTargetHttpProxyRequest, + GetRegionTargetHttpsProxyRequest, + GetRegionUrlMapRequest, + GetReservationRequest, + GetResourcePolicyRequest, + GetRouteRequest, + GetRouterRequest, + GetRouterStatusRouterRequest, + GetRuleSecurityPolicyRequest, + GetScreenshotInstanceRequest, + GetSecurityPolicyRequest, + GetSerialPortOutputInstanceRequest, + GetShieldedInstanceIdentityInstanceRequest, + GetSnapshotRequest, + GetSslCertificateRequest, + GetSslPolicyRequest, + GetStatusVpnGatewayRequest, + GetSubnetworkRequest, + GetTargetGrpcProxyRequest, + GetTargetHttpProxyRequest, + GetTargetHttpsProxyRequest, + GetTargetInstanceRequest, + GetTargetPoolRequest, + GetTargetSslProxyRequest, + GetTargetTcpProxyRequest, + GetTargetVpnGatewayRequest, + GetUrlMapRequest, + GetVpnGatewayRequest, + GetVpnTunnelRequest, + GetXpnHostProjectRequest, + GetXpnResourcesProjectsRequest, + GetZoneOperationRequest, + GetZoneRequest, + GlobalNetworkEndpointGroupsAttachEndpointsRequest, + GlobalNetworkEndpointGroupsDetachEndpointsRequest, + GlobalSetLabelsRequest, + GlobalSetPolicyRequest, + GRPCHealthCheck, + GuestAttributes, + GuestAttributesEntry, + GuestAttributesValue, + GuestOsFeature, + HealthCheck, + HealthCheckList, + HealthCheckLogConfig, + HealthCheckReference, + HealthChecksAggregatedList, + HealthCheckService, + HealthCheckServiceReference, + HealthCheckServicesList, + HealthChecksScopedList, + HealthStatus, + HealthStatusForNetworkEndpoint, + HostRule, + HTTP2HealthCheck, + HttpFaultAbort, + HttpFaultDelay, + HttpFaultInjection, + HttpHeaderAction, + HttpHeaderMatch, + HttpHeaderOption, + HTTPHealthCheck, + HttpQueryParameterMatch, HttpRedirectAction, HttpRetryPolicy, - RequestMirrorPolicy, - UrlRewrite, - WeightedBackendService, HttpRouteAction, - HttpRouteRuleMatch, HttpRouteRule, - RawDisk, + HttpRouteRuleMatch, + HTTPSHealthCheck, Image, ImageList, - Metadata, - NetworkInterface, - ReservationAffinity, - Scheduling, - ServiceAccount, - ShieldedInstanceConfig, - ShieldedInstanceIntegrityPolicy, - Tags, + InitialStateConfig, + InsertAddressRequest, + InsertAutoscalerRequest, + InsertBackendBucketRequest, + InsertBackendServiceRequest, + InsertDiskRequest, + InsertExternalVpnGatewayRequest, + InsertFirewallRequest, + InsertForwardingRuleRequest, + InsertGlobalAddressRequest, + InsertGlobalForwardingRuleRequest, + InsertGlobalNetworkEndpointGroupRequest, + InsertHealthCheckRequest, + InsertImageRequest, + InsertInstanceGroupManagerRequest, + InsertInstanceGroupRequest, + InsertInstanceRequest, + InsertInstanceTemplateRequest, + InsertInterconnectAttachmentRequest, + InsertInterconnectRequest, + InsertLicenseRequest, + InsertNetworkEndpointGroupRequest, + InsertNetworkRequest, + InsertNodeGroupRequest, + InsertNodeTemplateRequest, + InsertPacketMirroringRequest, + InsertRegionAutoscalerRequest, + InsertRegionBackendServiceRequest, + InsertRegionCommitmentRequest, + InsertRegionDiskRequest, + InsertRegionHealthCheckRequest, + InsertRegionHealthCheckServiceRequest, + InsertRegionInstanceGroupManagerRequest, + InsertRegionNetworkEndpointGroupRequest, + InsertRegionNotificationEndpointRequest, + InsertRegionSslCertificateRequest, + InsertRegionTargetHttpProxyRequest, + InsertRegionTargetHttpsProxyRequest, + InsertRegionUrlMapRequest, + InsertReservationRequest, + InsertResourcePolicyRequest, + InsertRouteRequest, + InsertRouterRequest, + InsertSecurityPolicyRequest, + InsertSslCertificateRequest, + InsertSslPolicyRequest, + InsertSubnetworkRequest, + InsertTargetGrpcProxyRequest, + InsertTargetHttpProxyRequest, + InsertTargetHttpsProxyRequest, + InsertTargetInstanceRequest, + InsertTargetPoolRequest, + InsertTargetSslProxyRequest, + InsertTargetTcpProxyRequest, + InsertTargetVpnGatewayRequest, + InsertUrlMapRequest, + InsertVpnGatewayRequest, + InsertVpnTunnelRequest, Instance, - InstancesScopedList, InstanceAggregatedList, - NamedPort, InstanceGroup, - InstanceGroupsScopedList, InstanceGroupAggregatedList, InstanceGroupList, - InstanceGroupManagerAutoHealingPolicy, - InstanceGroupManagerActionsSummary, - StatefulPolicy, - InstanceGroupManagerStatus, - InstanceGroupManagerUpdatePolicy, - InstanceGroupManagerVersion, InstanceGroupManager, - InstanceGroupManagersScopedList, + InstanceGroupManagerActionsSummary, InstanceGroupManagerAggregatedList, + InstanceGroupManagerAutoHealingPolicy, InstanceGroupManagerList, - InstanceGroupManagerStatusStateful, - InstanceGroupManagerStatusVersionTarget, - InstanceGroupManagerStatusStatefulPerInstanceConfigs, InstanceGroupManagersAbandonInstancesRequest, InstanceGroupManagersApplyUpdatesRequest, - PerInstanceConfig, InstanceGroupManagersCreateInstancesRequest, InstanceGroupManagersDeleteInstancesRequest, InstanceGroupManagersDeletePerInstanceConfigsReq, - InstanceManagedByIgmError, InstanceGroupManagersListErrorsResponse, - ManagedInstance, InstanceGroupManagersListManagedInstancesResponse, InstanceGroupManagersListPerInstanceConfigsResp, InstanceGroupManagersPatchPerInstanceConfigsReq, InstanceGroupManagersRecreateInstancesRequest, + InstanceGroupManagersScopedList, InstanceGroupManagersSetInstanceTemplateRequest, InstanceGroupManagersSetTargetPoolsRequest, + InstanceGroupManagerStatus, + InstanceGroupManagerStatusStateful, + InstanceGroupManagerStatusStatefulPerInstanceConfigs, + InstanceGroupManagerStatusVersionTarget, InstanceGroupManagersUpdatePerInstanceConfigsReq, - InstanceReference, + InstanceGroupManagerUpdatePolicy, + InstanceGroupManagerVersion, InstanceGroupsAddInstancesRequest, - InstanceWithNamedPorts, InstanceGroupsListInstances, InstanceGroupsListInstancesRequest, InstanceGroupsRemoveInstancesRequest, + InstanceGroupsScopedList, InstanceGroupsSetNamedPortsRequest, InstanceList, - Reference, InstanceListReferrers, - InstanceManagedByIgmErrorManagedInstanceError, + InstanceManagedByIgmError, InstanceManagedByIgmErrorInstanceActionDetails, - ManagedInstanceVersion, + InstanceManagedByIgmErrorManagedInstanceError, InstanceMoveRequest, InstanceProperties, - SourceInstanceParams, - InstanceTemplate, - InstanceTemplateList, + InstanceReference, InstancesAddResourcePoliciesRequest, InstancesRemoveResourcePoliciesRequest, + InstancesScopedList, InstancesSetLabelsRequest, InstancesSetMachineResourcesRequest, InstancesSetMachineTypeRequest, InstancesSetMinCpuPlatformRequest, InstancesSetServiceAccountRequest, InstancesStartWithEncryptionKeyRequest, - InterconnectCircuitInfo, - InterconnectOutageNotification, + InstanceTemplate, + InstanceTemplateList, + InstanceWithNamedPorts, + Int64RangeMatch, Interconnect, - InterconnectAttachmentPartnerMetadata, - InterconnectAttachmentPrivateInfo, InterconnectAttachment, - InterconnectAttachmentsScopedList, InterconnectAttachmentAggregatedList, InterconnectAttachmentList, + InterconnectAttachmentPartnerMetadata, + InterconnectAttachmentPrivateInfo, + InterconnectAttachmentsScopedList, + InterconnectCircuitInfo, + InterconnectDiagnostics, InterconnectDiagnosticsARPEntry, - InterconnectDiagnosticsLinkStatus, - InterconnectDiagnostics, InterconnectDiagnosticsLinkLACPStatus, InterconnectDiagnosticsLinkOpticalPower, + InterconnectDiagnosticsLinkStatus, InterconnectList, - InterconnectLocationRegionInfo, InterconnectLocation, InterconnectLocationList, + InterconnectLocationRegionInfo, + InterconnectOutageNotification, InterconnectsGetDiagnosticsResponse, - LicenseResourceRequirements, + InvalidateCacheUrlMapRequest, + Items, License, - LicenseCodeLicenseAlias, LicenseCode, + LicenseCodeLicenseAlias, + LicenseResourceCommitment, + LicenseResourceRequirements, LicensesListResponse, + ListAcceleratorTypesRequest, + ListAddressesRequest, + ListAutoscalersRequest, + ListAvailableFeaturesSslPoliciesRequest, + ListBackendBucketsRequest, + ListBackendServicesRequest, + ListDisksRequest, + ListDiskTypesRequest, + ListErrorsInstanceGroupManagersRequest, + ListErrorsRegionInstanceGroupManagersRequest, + ListExternalVpnGatewaysRequest, + ListFirewallsRequest, + ListForwardingRulesRequest, + ListGlobalAddressesRequest, + ListGlobalForwardingRulesRequest, + ListGlobalNetworkEndpointGroupsRequest, + ListGlobalOperationsRequest, + ListGlobalOrganizationOperationsRequest, + ListHealthChecksRequest, + ListImagesRequest, + ListInstanceGroupManagersRequest, + ListInstanceGroupsRequest, + ListInstancesInstanceGroupsRequest, + ListInstancesRegionInstanceGroupsRequest, + ListInstancesRequest, + ListInstanceTemplatesRequest, + ListInterconnectAttachmentsRequest, + ListInterconnectLocationsRequest, + ListInterconnectsRequest, + ListLicensesRequest, + ListMachineTypesRequest, + ListManagedInstancesInstanceGroupManagersRequest, + ListManagedInstancesRegionInstanceGroupManagersRequest, + ListNetworkEndpointGroupsRequest, + ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest, + ListNetworkEndpointsNetworkEndpointGroupsRequest, + ListNetworksRequest, + ListNodeGroupsRequest, + ListNodesNodeGroupsRequest, + ListNodeTemplatesRequest, + ListNodeTypesRequest, + ListPacketMirroringsRequest, + ListPeeringRoutesNetworksRequest, + ListPerInstanceConfigsInstanceGroupManagersRequest, + ListPerInstanceConfigsRegionInstanceGroupManagersRequest, + ListPreconfiguredExpressionSetsSecurityPoliciesRequest, + ListReferrersInstancesRequest, + ListRegionAutoscalersRequest, + ListRegionBackendServicesRequest, + ListRegionCommitmentsRequest, + ListRegionDisksRequest, + ListRegionDiskTypesRequest, + ListRegionHealthCheckServicesRequest, + ListRegionHealthChecksRequest, + ListRegionInstanceGroupManagersRequest, + ListRegionInstanceGroupsRequest, + ListRegionNetworkEndpointGroupsRequest, + ListRegionNotificationEndpointsRequest, + ListRegionOperationsRequest, + ListRegionsRequest, + ListRegionSslCertificatesRequest, + ListRegionTargetHttpProxiesRequest, + ListRegionTargetHttpsProxiesRequest, + ListRegionUrlMapsRequest, + ListReservationsRequest, + ListResourcePoliciesRequest, + ListRoutersRequest, + ListRoutesRequest, + ListSecurityPoliciesRequest, + ListSnapshotsRequest, + ListSslCertificatesRequest, + ListSslPoliciesRequest, + ListSubnetworksRequest, + ListTargetGrpcProxiesRequest, + ListTargetHttpProxiesRequest, + ListTargetHttpsProxiesRequest, + ListTargetInstancesRequest, + ListTargetPoolsRequest, + ListTargetSslProxiesRequest, + ListTargetTcpProxiesRequest, + ListTargetVpnGatewaysRequest, + ListUrlMapsRequest, + ListUsableSubnetworksRequest, + ListVpnGatewaysRequest, + ListVpnTunnelsRequest, + ListXpnHostsProjectsRequest, + ListZoneOperationsRequest, + ListZonesRequest, LocalDisk, + LogConfig, LogConfigCloudAuditOptions, LogConfigCounterOptions, - LogConfigDataAccessOptions, - LogConfig, LogConfigCounterOptionsCustomField, - Accelerators, - ScratchDisks, + LogConfigDataAccessOptions, MachineType, - MachineTypesScopedList, MachineTypeAggregatedList, MachineTypeList, + MachineTypesScopedList, + ManagedInstance, ManagedInstanceInstanceHealth, ManagedInstanceLastAttempt, - PreservedState, - Errors, - Items, + ManagedInstanceVersion, + Metadata, + MetadataFilter, MetadataFilterLabelMatch, - NetworkPeering, - NetworkRoutingConfig, + MoveDiskProjectRequest, + MoveInstanceProjectRequest, + NamedPort, Network, + NetworkEndpoint, + NetworkEndpointGroup, + NetworkEndpointGroupAggregatedList, NetworkEndpointGroupAppEngine, NetworkEndpointGroupCloudFunction, NetworkEndpointGroupCloudRun, - NetworkEndpointGroup, - NetworkEndpointGroupsScopedList, - NetworkEndpointGroupAggregatedList, NetworkEndpointGroupList, NetworkEndpointGroupsAttachEndpointsRequest, NetworkEndpointGroupsDetachEndpointsRequest, NetworkEndpointGroupsListEndpointsRequest, - NetworkEndpointWithHealthStatus, NetworkEndpointGroupsListNetworkEndpoints, + NetworkEndpointGroupsScopedList, + NetworkEndpointWithHealthStatus, + NetworkInterface, NetworkList, + NetworkPeering, + NetworkRoutingConfig, NetworksAddPeeringRequest, NetworksRemovePeeringRequest, NetworksUpdatePeeringRequest, - NodeGroupAutoscalingPolicy, - NodeGroupMaintenanceWindow, NodeGroup, - NodeGroupsScopedList, NodeGroupAggregatedList, + NodeGroupAutoscalingPolicy, NodeGroupList, - ServerBinding, + NodeGroupMaintenanceWindow, NodeGroupNode, NodeGroupsAddNodesRequest, NodeGroupsDeleteNodesRequest, NodeGroupsListNodes, + NodeGroupsScopedList, NodeGroupsSetNodeTemplateRequest, - NodeTemplateNodeTypeFlexibility, NodeTemplate, - NodeTemplatesScopedList, NodeTemplateAggregatedList, NodeTemplateList, + NodeTemplateNodeTypeFlexibility, + NodeTemplatesScopedList, NodeType, - NodeTypesScopedList, NodeTypeAggregatedList, NodeTypeList, - NotificationEndpointGrpcSettings, + NodeTypesScopedList, NotificationEndpoint, + NotificationEndpointGrpcSettings, NotificationEndpointList, - Error, - Warnings, Operation, - OperationsScopedList, OperationAggregatedList, OperationList, - PacketMirroringForwardingRuleInfo, - PacketMirroringFilter, - PacketMirroringMirroredResourceInfo, - PacketMirroringNetworkInfo, + OperationsScopedList, + OutlierDetection, PacketMirroring, - PacketMirroringsScopedList, PacketMirroringAggregatedList, + PacketMirroringFilter, + PacketMirroringForwardingRuleInfo, PacketMirroringList, + PacketMirroringMirroredResourceInfo, PacketMirroringMirroredResourceInfoInstanceInfo, PacketMirroringMirroredResourceInfoSubnetInfo, - PathRule, + PacketMirroringNetworkInfo, + PacketMirroringsScopedList, + PatchAutoscalerRequest, + PatchBackendBucketRequest, + PatchBackendServiceRequest, + PatchFirewallRequest, + PatchForwardingRuleRequest, + PatchGlobalForwardingRuleRequest, + PatchHealthCheckRequest, + PatchImageRequest, + PatchInstanceGroupManagerRequest, + PatchInterconnectAttachmentRequest, + PatchInterconnectRequest, + PatchNetworkRequest, + PatchNodeGroupRequest, + PatchPacketMirroringRequest, + PatchPerInstanceConfigsInstanceGroupManagerRequest, + PatchPerInstanceConfigsRegionInstanceGroupManagerRequest, + PatchRegionAutoscalerRequest, + PatchRegionBackendServiceRequest, + PatchRegionHealthCheckRequest, + PatchRegionHealthCheckServiceRequest, + PatchRegionInstanceGroupManagerRequest, + PatchRegionUrlMapRequest, + PatchRouterRequest, + PatchRuleSecurityPolicyRequest, + PatchSecurityPolicyRequest, + PatchSslPolicyRequest, + PatchSubnetworkRequest, + PatchTargetGrpcProxyRequest, + PatchTargetHttpProxyRequest, + PatchUrlMapRequest, PathMatcher, - Rule, - WafExpressionSet, + PathRule, + PerInstanceConfig, + Policy, PreconfiguredWafSet, + PreservedState, PreservedStatePreservedDisk, - Quota, - UsageExportLocation, + PreviewRouterRequest, Project, - XpnResourceId, ProjectsDisableXpnResourceRequest, ProjectsEnableXpnResourceRequest, ProjectsGetXpnResources, ProjectsListXpnHostsRequest, ProjectsSetDefaultNetworkTierRequest, + Quota, + RawDisk, + RecreateInstancesInstanceGroupManagerRequest, + RecreateInstancesRegionInstanceGroupManagerRequest, + Reference, Region, RegionAutoscalerList, - RegionDiskTypeList, RegionDisksAddResourcePoliciesRequest, RegionDisksRemoveResourcePoliciesRequest, RegionDisksResizeRequest, + RegionDiskTypeList, RegionInstanceGroupList, RegionInstanceGroupManagerDeleteInstanceConfigReq, RegionInstanceGroupManagerList, RegionInstanceGroupManagerPatchInstanceConfigReq, - RegionInstanceGroupManagerUpdateInstanceConfigReq, RegionInstanceGroupManagersAbandonInstancesRequest, RegionInstanceGroupManagersApplyUpdatesRequest, RegionInstanceGroupManagersCreateInstancesRequest, @@ -375,6 +767,7 @@ RegionInstanceGroupManagersRecreateRequest, RegionInstanceGroupManagersSetTargetPoolsRequest, RegionInstanceGroupManagersSetTemplateRequest, + RegionInstanceGroupManagerUpdateInstanceConfigReq, RegionInstanceGroupsListInstances, RegionInstanceGroupsListInstancesRequest, RegionInstanceGroupsSetNamedPortsRequest, @@ -382,21 +775,38 @@ RegionSetLabelsRequest, RegionSetPolicyRequest, RegionTargetHttpsProxiesSetSslCertificatesRequest, - UrlMap, RegionUrlMapsValidateRequest, - ReservationsScopedList, + RemoveHealthCheckTargetPoolRequest, + RemoveInstancesInstanceGroupRequest, + RemoveInstanceTargetPoolRequest, + RemovePeeringNetworkRequest, + RemoveResourcePoliciesDiskRequest, + RemoveResourcePoliciesInstanceRequest, + RemoveResourcePoliciesRegionDiskRequest, + RemoveRuleSecurityPolicyRequest, + RequestMirrorPolicy, + Reservation, + ReservationAffinity, ReservationAggregatedList, ReservationList, ReservationsResizeRequest, + ReservationsScopedList, + ResetInstanceRequest, + ResizeDiskRequest, + ResizeInstanceGroupManagerRequest, + ResizeRegionDiskRequest, + ResizeRegionInstanceGroupManagerRequest, + ResizeReservationRequest, + ResourceCommitment, ResourceGroupReference, - ResourcePolicy, ResourcePoliciesScopedList, - ResourcePolicyGroupPlacementPolicy, - ResourcePolicySnapshotSchedulePolicy, + ResourcePolicy, ResourcePolicyAggregatedList, ResourcePolicyDailyCycle, + ResourcePolicyGroupPlacementPolicy, ResourcePolicyHourlyCycle, ResourcePolicyList, + ResourcePolicySnapshotSchedulePolicy, ResourcePolicySnapshotSchedulePolicyRetentionPolicy, ResourcePolicySnapshotSchedulePolicySchedule, ResourcePolicySnapshotSchedulePolicySnapshotProperties, @@ -404,76 +814,150 @@ ResourcePolicyWeeklyCycleDayOfWeek, Route, RouteList, - RouterBgp, - RouterBgpPeer, - RouterInterface, - RouterNat, Router, RouterAdvertisedIpRange, - RoutersScopedList, RouterAggregatedList, + RouterBgp, + RouterBgpPeer, + RouterInterface, RouterList, + RouterNat, RouterNatLogConfig, RouterNatSubnetworkToNat, + RoutersPreviewResponse, + RoutersScopedList, + RouterStatus, RouterStatusBgpPeerStatus, RouterStatusNatStatus, - RouterStatus, RouterStatusResponse, - RoutersPreviewResponse, + Rule, + Scheduling, SchedulingNodeAffinity, + ScratchDisks, Screenshot, - SecurityPoliciesWafConfig, SecurityPoliciesListPreconfiguredExpressionSetsResponse, - SecurityPolicyRule, + SecurityPoliciesWafConfig, SecurityPolicy, SecurityPolicyList, SecurityPolicyReference, + SecurityPolicyRule, SecurityPolicyRuleMatcher, SecurityPolicyRuleMatcherConfig, + SecuritySettings, SerialPortOutput, - ShieldedInstanceIdentityEntry, + ServerBinding, + ServiceAccount, + SetBackendServiceTargetSslProxyRequest, + SetBackendServiceTargetTcpProxyRequest, + SetBackupTargetPoolRequest, + SetCommonInstanceMetadataProjectRequest, + SetDefaultNetworkTierProjectRequest, + SetDeletionProtectionInstanceRequest, + SetDiskAutoDeleteInstanceRequest, + SetIamPolicyDiskRequest, + SetIamPolicyImageRequest, + SetIamPolicyInstanceRequest, + SetIamPolicyInstanceTemplateRequest, + SetIamPolicyLicenseRequest, + SetIamPolicyNodeGroupRequest, + SetIamPolicyNodeTemplateRequest, + SetIamPolicyRegionDiskRequest, + SetIamPolicyReservationRequest, + SetIamPolicyResourcePolicyRequest, + SetIamPolicySnapshotRequest, + SetIamPolicySubnetworkRequest, + SetInstanceTemplateInstanceGroupManagerRequest, + SetInstanceTemplateRegionInstanceGroupManagerRequest, + SetLabelsDiskRequest, + SetLabelsExternalVpnGatewayRequest, + SetLabelsImageRequest, + SetLabelsInstanceRequest, + SetLabelsRegionDiskRequest, + SetLabelsSnapshotRequest, + SetLabelsVpnGatewayRequest, + SetMachineResourcesInstanceRequest, + SetMachineTypeInstanceRequest, + SetMetadataInstanceRequest, + SetMinCpuPlatformInstanceRequest, + SetNamedPortsInstanceGroupRequest, + SetNamedPortsRegionInstanceGroupRequest, + SetNodeTemplateNodeGroupRequest, + SetPrivateIpGoogleAccessSubnetworkRequest, + SetProxyHeaderTargetSslProxyRequest, + SetProxyHeaderTargetTcpProxyRequest, + SetQuicOverrideTargetHttpsProxyRequest, + SetSchedulingInstanceRequest, + SetSecurityPolicyBackendServiceRequest, + SetServiceAccountInstanceRequest, + SetShieldedInstanceIntegrityPolicyInstanceRequest, + SetSslCertificatesRegionTargetHttpsProxyRequest, + SetSslCertificatesTargetHttpsProxyRequest, + SetSslCertificatesTargetSslProxyRequest, + SetSslPolicyTargetHttpsProxyRequest, + SetSslPolicyTargetSslProxyRequest, + SetTagsInstanceRequest, + SetTargetForwardingRuleRequest, + SetTargetGlobalForwardingRuleRequest, + SetTargetPoolsInstanceGroupManagerRequest, + SetTargetPoolsRegionInstanceGroupManagerRequest, + SetUrlMapRegionTargetHttpProxyRequest, + SetUrlMapRegionTargetHttpsProxyRequest, + SetUrlMapTargetHttpProxyRequest, + SetUrlMapTargetHttpsProxyRequest, + SetUsageExportBucketProjectRequest, + ShieldedInstanceConfig, ShieldedInstanceIdentity, + ShieldedInstanceIdentityEntry, + ShieldedInstanceIntegrityPolicy, SignedUrlKey, + SimulateMaintenanceEventInstanceRequest, Snapshot, SnapshotList, - SslCertificateManagedSslCertificate, - SslCertificateSelfManagedSslCertificate, + SourceInstanceParams, SslCertificate, - SslCertificatesScopedList, SslCertificateAggregatedList, SslCertificateList, - SslPolicy, + SslCertificateManagedSslCertificate, + SslCertificateSelfManagedSslCertificate, + SslCertificatesScopedList, + SSLHealthCheck, SslPoliciesList, SslPoliciesListAvailableFeaturesResponse, + SslPolicy, SslPolicyReference, + StartInstanceRequest, + StartWithEncryptionKeyInstanceRequest, + StatefulPolicy, StatefulPolicyPreservedState, StatefulPolicyPreservedStateDiskDevice, - SubnetworkLogConfig, - SubnetworkSecondaryRange, + StopInstanceRequest, Subnetwork, - SubnetworksScopedList, SubnetworkAggregatedList, SubnetworkList, + SubnetworkLogConfig, + SubnetworkSecondaryRange, SubnetworksExpandIpCidrRangeRequest, + SubnetworksScopedList, SubnetworksSetPrivateIpGoogleAccessRequest, + SwitchToCustomModeNetworkRequest, + Tags, TargetGrpcProxy, TargetGrpcProxyList, - TargetHttpProxy, TargetHttpProxiesScopedList, + TargetHttpProxy, TargetHttpProxyAggregatedList, TargetHttpProxyList, - TargetHttpsProxy, TargetHttpsProxiesScopedList, TargetHttpsProxiesSetQuicOverrideRequest, TargetHttpsProxiesSetSslCertificatesRequest, + TargetHttpsProxy, TargetHttpsProxyAggregatedList, TargetHttpsProxyList, TargetInstance, - TargetInstancesScopedList, TargetInstanceAggregatedList, TargetInstanceList, + TargetInstancesScopedList, TargetPool, - TargetPoolsScopedList, TargetPoolAggregatedList, TargetPoolInstanceHealth, TargetPoolList, @@ -481,6 +965,7 @@ TargetPoolsAddInstanceRequest, TargetPoolsRemoveHealthCheckRequest, TargetPoolsRemoveInstanceRequest, + TargetPoolsScopedList, TargetReference, TargetSslProxiesSetBackendServiceRequest, TargetSslProxiesSetProxyHeaderRequest, @@ -492,1637 +977,1150 @@ TargetTcpProxy, TargetTcpProxyList, TargetVpnGateway, - TargetVpnGatewaysScopedList, TargetVpnGatewayAggregatedList, TargetVpnGatewayList, + TargetVpnGatewaysScopedList, + TCPHealthCheck, TestFailure, + TestIamPermissionsDiskRequest, + TestIamPermissionsExternalVpnGatewayRequest, + TestIamPermissionsImageRequest, + TestIamPermissionsInstanceRequest, + TestIamPermissionsInstanceTemplateRequest, + TestIamPermissionsLicenseCodeRequest, + TestIamPermissionsLicenseRequest, + TestIamPermissionsNetworkEndpointGroupRequest, + TestIamPermissionsNodeGroupRequest, + TestIamPermissionsNodeTemplateRequest, + TestIamPermissionsPacketMirroringRequest, + TestIamPermissionsRegionDiskRequest, + TestIamPermissionsReservationRequest, + TestIamPermissionsResourcePolicyRequest, + TestIamPermissionsSnapshotRequest, + TestIamPermissionsSubnetworkRequest, + TestIamPermissionsVpnGatewayRequest, TestPermissionsRequest, TestPermissionsResponse, - UrlMapTest, + UpdateAccessConfigInstanceRequest, + UpdateAutoscalerRequest, + UpdateBackendBucketRequest, + UpdateBackendServiceRequest, + UpdateDisplayDeviceInstanceRequest, + UpdateFirewallRequest, + UpdateHealthCheckRequest, + UpdateInstanceRequest, + UpdateNetworkInterfaceInstanceRequest, + UpdatePeeringNetworkRequest, + UpdatePerInstanceConfigsInstanceGroupManagerRequest, + UpdatePerInstanceConfigsRegionInstanceGroupManagerRequest, + UpdateRegionAutoscalerRequest, + UpdateRegionBackendServiceRequest, + UpdateRegionHealthCheckRequest, + UpdateRegionUrlMapRequest, + UpdateRouterRequest, + UpdateShieldedInstanceConfigInstanceRequest, + UpdateUrlMapRequest, + UrlMap, UrlMapList, UrlMapReference, - UrlMapValidationResult, - UrlMapsScopedList, UrlMapsAggregatedList, + UrlMapsScopedList, UrlMapsValidateRequest, UrlMapsValidateResponse, - UsableSubnetworkSecondaryRange, + UrlMapTest, + UrlMapValidationResult, + UrlRewrite, UsableSubnetwork, UsableSubnetworksAggregatedList, - VmEndpointNatMappingsInterfaceNatMappings, + UsableSubnetworkSecondaryRange, + UsageExportLocation, + ValidateRegionUrlMapRequest, + ValidateUrlMapRequest, VmEndpointNatMappings, + VmEndpointNatMappingsInterfaceNatMappings, VmEndpointNatMappingsList, - VpnGatewayVpnGatewayInterface, VpnGateway, - VpnGatewaysScopedList, VpnGatewayAggregatedList, VpnGatewayList, - VpnGatewayStatusVpnConnection, + VpnGatewaysGetStatusResponse, + VpnGatewaysScopedList, VpnGatewayStatus, VpnGatewayStatusHighAvailabilityRequirementState, VpnGatewayStatusTunnel, - VpnGatewaysGetStatusResponse, + VpnGatewayStatusVpnConnection, + VpnGatewayVpnGatewayInterface, VpnTunnel, - VpnTunnelsScopedList, VpnTunnelAggregatedList, VpnTunnelList, + VpnTunnelsScopedList, + WafExpressionSet, WafExpressionSetExpression, + WaitGlobalOperationRequest, + WaitRegionOperationRequest, + WaitZoneOperationRequest, + Warning, + Warnings, + WeightedBackendService, XpnHostList, + XpnResourceId, Zone, ZoneList, ZoneSetLabelsRequest, ZoneSetPolicyRequest, - AggregatedListAcceleratorTypesRequest, - GetAcceleratorTypeRequest, - ListAcceleratorTypesRequest, - AggregatedListAddressesRequest, - DeleteAddressRequest, - GetAddressRequest, - InsertAddressRequest, - ListAddressesRequest, - AggregatedListAutoscalersRequest, - DeleteAutoscalerRequest, - GetAutoscalerRequest, - InsertAutoscalerRequest, - ListAutoscalersRequest, - PatchAutoscalerRequest, - UpdateAutoscalerRequest, - AddSignedUrlKeyBackendBucketRequest, - DeleteBackendBucketRequest, - DeleteSignedUrlKeyBackendBucketRequest, - GetBackendBucketRequest, - InsertBackendBucketRequest, - ListBackendBucketsRequest, - PatchBackendBucketRequest, - UpdateBackendBucketRequest, - AddSignedUrlKeyBackendServiceRequest, - AggregatedListBackendServicesRequest, - DeleteBackendServiceRequest, - DeleteSignedUrlKeyBackendServiceRequest, - GetBackendServiceRequest, - GetHealthBackendServiceRequest, - InsertBackendServiceRequest, - ListBackendServicesRequest, - PatchBackendServiceRequest, - SetSecurityPolicyBackendServiceRequest, - UpdateBackendServiceRequest, - AggregatedListDiskTypesRequest, - GetDiskTypeRequest, - ListDiskTypesRequest, - AddResourcePoliciesDiskRequest, - AggregatedListDisksRequest, - CreateSnapshotDiskRequest, - DeleteDiskRequest, - GetDiskRequest, - GetIamPolicyDiskRequest, - InsertDiskRequest, - ListDisksRequest, - RemoveResourcePoliciesDiskRequest, - ResizeDiskRequest, - SetIamPolicyDiskRequest, - SetLabelsDiskRequest, - TestIamPermissionsDiskRequest, - DeleteExternalVpnGatewayRequest, - GetExternalVpnGatewayRequest, - InsertExternalVpnGatewayRequest, - ListExternalVpnGatewaysRequest, - SetLabelsExternalVpnGatewayRequest, - TestIamPermissionsExternalVpnGatewayRequest, - DeleteFirewallRequest, - GetFirewallRequest, - InsertFirewallRequest, - ListFirewallsRequest, - PatchFirewallRequest, - UpdateFirewallRequest, - AggregatedListForwardingRulesRequest, - DeleteForwardingRuleRequest, - GetForwardingRuleRequest, - InsertForwardingRuleRequest, - ListForwardingRulesRequest, - PatchForwardingRuleRequest, - SetTargetForwardingRuleRequest, - DeleteGlobalAddressRequest, - GetGlobalAddressRequest, - InsertGlobalAddressRequest, - ListGlobalAddressesRequest, - DeleteGlobalForwardingRuleRequest, - GetGlobalForwardingRuleRequest, - InsertGlobalForwardingRuleRequest, - ListGlobalForwardingRulesRequest, - PatchGlobalForwardingRuleRequest, - SetTargetGlobalForwardingRuleRequest, - AttachNetworkEndpointsGlobalNetworkEndpointGroupRequest, - DeleteGlobalNetworkEndpointGroupRequest, - DetachNetworkEndpointsGlobalNetworkEndpointGroupRequest, - GetGlobalNetworkEndpointGroupRequest, - InsertGlobalNetworkEndpointGroupRequest, - ListGlobalNetworkEndpointGroupsRequest, - ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest, - AggregatedListGlobalOperationsRequest, - DeleteGlobalOperationRequest, - DeleteGlobalOperationResponse, - GetGlobalOperationRequest, - ListGlobalOperationsRequest, - WaitGlobalOperationRequest, - DeleteGlobalOrganizationOperationRequest, - DeleteGlobalOrganizationOperationResponse, - GetGlobalOrganizationOperationRequest, - ListGlobalOrganizationOperationsRequest, - AggregatedListHealthChecksRequest, - DeleteHealthCheckRequest, - GetHealthCheckRequest, - InsertHealthCheckRequest, - ListHealthChecksRequest, - PatchHealthCheckRequest, - UpdateHealthCheckRequest, - DeleteImageRequest, - DeprecateImageRequest, - GetImageRequest, - GetFromFamilyImageRequest, - GetIamPolicyImageRequest, - InsertImageRequest, - ListImagesRequest, - PatchImageRequest, - SetIamPolicyImageRequest, - SetLabelsImageRequest, - TestIamPermissionsImageRequest, - AbandonInstancesInstanceGroupManagerRequest, - AggregatedListInstanceGroupManagersRequest, - ApplyUpdatesToInstancesInstanceGroupManagerRequest, - CreateInstancesInstanceGroupManagerRequest, - DeleteInstanceGroupManagerRequest, - DeleteInstancesInstanceGroupManagerRequest, - DeletePerInstanceConfigsInstanceGroupManagerRequest, - GetInstanceGroupManagerRequest, - InsertInstanceGroupManagerRequest, - ListInstanceGroupManagersRequest, - ListErrorsInstanceGroupManagersRequest, - ListManagedInstancesInstanceGroupManagersRequest, - ListPerInstanceConfigsInstanceGroupManagersRequest, - PatchInstanceGroupManagerRequest, - PatchPerInstanceConfigsInstanceGroupManagerRequest, - RecreateInstancesInstanceGroupManagerRequest, - ResizeInstanceGroupManagerRequest, - SetInstanceTemplateInstanceGroupManagerRequest, - SetTargetPoolsInstanceGroupManagerRequest, - UpdatePerInstanceConfigsInstanceGroupManagerRequest, - AddInstancesInstanceGroupRequest, - AggregatedListInstanceGroupsRequest, - DeleteInstanceGroupRequest, - GetInstanceGroupRequest, - InsertInstanceGroupRequest, - ListInstanceGroupsRequest, - ListInstancesInstanceGroupsRequest, - RemoveInstancesInstanceGroupRequest, - SetNamedPortsInstanceGroupRequest, - DeleteInstanceTemplateRequest, - GetInstanceTemplateRequest, - GetIamPolicyInstanceTemplateRequest, - InsertInstanceTemplateRequest, - ListInstanceTemplatesRequest, - SetIamPolicyInstanceTemplateRequest, - TestIamPermissionsInstanceTemplateRequest, - AddAccessConfigInstanceRequest, - AddResourcePoliciesInstanceRequest, - AggregatedListInstancesRequest, - AttachDiskInstanceRequest, - DeleteInstanceRequest, - DeleteAccessConfigInstanceRequest, - DetachDiskInstanceRequest, - GetInstanceRequest, - GetGuestAttributesInstanceRequest, - GetIamPolicyInstanceRequest, - GetScreenshotInstanceRequest, - GetSerialPortOutputInstanceRequest, - GetShieldedInstanceIdentityInstanceRequest, - InsertInstanceRequest, - ListInstancesRequest, - ListReferrersInstancesRequest, - RemoveResourcePoliciesInstanceRequest, - ResetInstanceRequest, - SetDeletionProtectionInstanceRequest, - SetDiskAutoDeleteInstanceRequest, - SetIamPolicyInstanceRequest, - SetLabelsInstanceRequest, - SetMachineResourcesInstanceRequest, - SetMachineTypeInstanceRequest, - SetMetadataInstanceRequest, - SetMinCpuPlatformInstanceRequest, - SetSchedulingInstanceRequest, - SetServiceAccountInstanceRequest, - SetShieldedInstanceIntegrityPolicyInstanceRequest, - SetTagsInstanceRequest, - SimulateMaintenanceEventInstanceRequest, - StartInstanceRequest, - StartWithEncryptionKeyInstanceRequest, - StopInstanceRequest, - TestIamPermissionsInstanceRequest, - UpdateInstanceRequest, - UpdateAccessConfigInstanceRequest, - UpdateDisplayDeviceInstanceRequest, - UpdateNetworkInterfaceInstanceRequest, - UpdateShieldedInstanceConfigInstanceRequest, - AggregatedListInterconnectAttachmentsRequest, - DeleteInterconnectAttachmentRequest, - GetInterconnectAttachmentRequest, - InsertInterconnectAttachmentRequest, - ListInterconnectAttachmentsRequest, - PatchInterconnectAttachmentRequest, - GetInterconnectLocationRequest, - ListInterconnectLocationsRequest, - DeleteInterconnectRequest, - GetInterconnectRequest, - GetDiagnosticsInterconnectRequest, - InsertInterconnectRequest, - ListInterconnectsRequest, - PatchInterconnectRequest, - GetLicenseCodeRequest, - TestIamPermissionsLicenseCodeRequest, - DeleteLicenseRequest, - GetLicenseRequest, - GetIamPolicyLicenseRequest, - InsertLicenseRequest, - ListLicensesRequest, - SetIamPolicyLicenseRequest, - TestIamPermissionsLicenseRequest, - AggregatedListMachineTypesRequest, - GetMachineTypeRequest, - ListMachineTypesRequest, - AggregatedListNetworkEndpointGroupsRequest, - AttachNetworkEndpointsNetworkEndpointGroupRequest, - DeleteNetworkEndpointGroupRequest, - DetachNetworkEndpointsNetworkEndpointGroupRequest, - GetNetworkEndpointGroupRequest, - InsertNetworkEndpointGroupRequest, - ListNetworkEndpointGroupsRequest, - ListNetworkEndpointsNetworkEndpointGroupsRequest, - TestIamPermissionsNetworkEndpointGroupRequest, - AddPeeringNetworkRequest, - DeleteNetworkRequest, - GetNetworkRequest, - InsertNetworkRequest, - ListNetworksRequest, - ListPeeringRoutesNetworksRequest, - PatchNetworkRequest, - RemovePeeringNetworkRequest, - SwitchToCustomModeNetworkRequest, - UpdatePeeringNetworkRequest, - AddNodesNodeGroupRequest, - AggregatedListNodeGroupsRequest, - DeleteNodeGroupRequest, - DeleteNodesNodeGroupRequest, - GetNodeGroupRequest, - GetIamPolicyNodeGroupRequest, - InsertNodeGroupRequest, - ListNodeGroupsRequest, - ListNodesNodeGroupsRequest, - PatchNodeGroupRequest, - SetIamPolicyNodeGroupRequest, - SetNodeTemplateNodeGroupRequest, - TestIamPermissionsNodeGroupRequest, - AggregatedListNodeTemplatesRequest, - DeleteNodeTemplateRequest, - GetNodeTemplateRequest, - GetIamPolicyNodeTemplateRequest, - InsertNodeTemplateRequest, - ListNodeTemplatesRequest, - SetIamPolicyNodeTemplateRequest, - TestIamPermissionsNodeTemplateRequest, - AggregatedListNodeTypesRequest, - GetNodeTypeRequest, - ListNodeTypesRequest, - AggregatedListPacketMirroringsRequest, - DeletePacketMirroringRequest, - GetPacketMirroringRequest, - InsertPacketMirroringRequest, - ListPacketMirroringsRequest, - PatchPacketMirroringRequest, - TestIamPermissionsPacketMirroringRequest, - DisableXpnHostProjectRequest, - DisableXpnResourceProjectRequest, - EnableXpnHostProjectRequest, - EnableXpnResourceProjectRequest, - GetProjectRequest, - GetXpnHostProjectRequest, - GetXpnResourcesProjectsRequest, - ListXpnHostsProjectsRequest, - MoveDiskProjectRequest, - MoveInstanceProjectRequest, - SetCommonInstanceMetadataProjectRequest, - SetDefaultNetworkTierProjectRequest, - SetUsageExportBucketProjectRequest, - DeleteRegionAutoscalerRequest, - GetRegionAutoscalerRequest, - InsertRegionAutoscalerRequest, - ListRegionAutoscalersRequest, - PatchRegionAutoscalerRequest, - UpdateRegionAutoscalerRequest, - DeleteRegionBackendServiceRequest, - GetRegionBackendServiceRequest, - GetHealthRegionBackendServiceRequest, - InsertRegionBackendServiceRequest, - ListRegionBackendServicesRequest, - PatchRegionBackendServiceRequest, - UpdateRegionBackendServiceRequest, - AggregatedListRegionCommitmentsRequest, - GetRegionCommitmentRequest, - InsertRegionCommitmentRequest, - ListRegionCommitmentsRequest, - GetRegionDiskTypeRequest, - ListRegionDiskTypesRequest, - AddResourcePoliciesRegionDiskRequest, - CreateSnapshotRegionDiskRequest, - DeleteRegionDiskRequest, - GetRegionDiskRequest, - GetIamPolicyRegionDiskRequest, - InsertRegionDiskRequest, - ListRegionDisksRequest, - RemoveResourcePoliciesRegionDiskRequest, - ResizeRegionDiskRequest, - SetIamPolicyRegionDiskRequest, - SetLabelsRegionDiskRequest, - TestIamPermissionsRegionDiskRequest, - DeleteRegionHealthCheckServiceRequest, - GetRegionHealthCheckServiceRequest, - InsertRegionHealthCheckServiceRequest, - ListRegionHealthCheckServicesRequest, - PatchRegionHealthCheckServiceRequest, - DeleteRegionHealthCheckRequest, - GetRegionHealthCheckRequest, - InsertRegionHealthCheckRequest, - ListRegionHealthChecksRequest, - PatchRegionHealthCheckRequest, - UpdateRegionHealthCheckRequest, - AbandonInstancesRegionInstanceGroupManagerRequest, - ApplyUpdatesToInstancesRegionInstanceGroupManagerRequest, - CreateInstancesRegionInstanceGroupManagerRequest, - DeleteRegionInstanceGroupManagerRequest, - DeleteInstancesRegionInstanceGroupManagerRequest, - DeletePerInstanceConfigsRegionInstanceGroupManagerRequest, - GetRegionInstanceGroupManagerRequest, - InsertRegionInstanceGroupManagerRequest, - ListRegionInstanceGroupManagersRequest, - ListErrorsRegionInstanceGroupManagersRequest, - ListManagedInstancesRegionInstanceGroupManagersRequest, - ListPerInstanceConfigsRegionInstanceGroupManagersRequest, - PatchRegionInstanceGroupManagerRequest, - PatchPerInstanceConfigsRegionInstanceGroupManagerRequest, - RecreateInstancesRegionInstanceGroupManagerRequest, - ResizeRegionInstanceGroupManagerRequest, - SetInstanceTemplateRegionInstanceGroupManagerRequest, - SetTargetPoolsRegionInstanceGroupManagerRequest, - UpdatePerInstanceConfigsRegionInstanceGroupManagerRequest, - GetRegionInstanceGroupRequest, - ListRegionInstanceGroupsRequest, - ListInstancesRegionInstanceGroupsRequest, - SetNamedPortsRegionInstanceGroupRequest, - DeleteRegionNetworkEndpointGroupRequest, - GetRegionNetworkEndpointGroupRequest, - InsertRegionNetworkEndpointGroupRequest, - ListRegionNetworkEndpointGroupsRequest, - DeleteRegionNotificationEndpointRequest, - GetRegionNotificationEndpointRequest, - InsertRegionNotificationEndpointRequest, - ListRegionNotificationEndpointsRequest, - DeleteRegionOperationRequest, - DeleteRegionOperationResponse, - GetRegionOperationRequest, - ListRegionOperationsRequest, - WaitRegionOperationRequest, - DeleteRegionSslCertificateRequest, - GetRegionSslCertificateRequest, - InsertRegionSslCertificateRequest, - ListRegionSslCertificatesRequest, - DeleteRegionTargetHttpProxyRequest, - GetRegionTargetHttpProxyRequest, - InsertRegionTargetHttpProxyRequest, - ListRegionTargetHttpProxiesRequest, - SetUrlMapRegionTargetHttpProxyRequest, - DeleteRegionTargetHttpsProxyRequest, - GetRegionTargetHttpsProxyRequest, - InsertRegionTargetHttpsProxyRequest, - ListRegionTargetHttpsProxiesRequest, - SetSslCertificatesRegionTargetHttpsProxyRequest, - SetUrlMapRegionTargetHttpsProxyRequest, - DeleteRegionUrlMapRequest, - GetRegionUrlMapRequest, - InsertRegionUrlMapRequest, - ListRegionUrlMapsRequest, - PatchRegionUrlMapRequest, - UpdateRegionUrlMapRequest, - ValidateRegionUrlMapRequest, - GetRegionRequest, - ListRegionsRequest, - AggregatedListReservationsRequest, - DeleteReservationRequest, - GetReservationRequest, - GetIamPolicyReservationRequest, - InsertReservationRequest, - ListReservationsRequest, - ResizeReservationRequest, - SetIamPolicyReservationRequest, - TestIamPermissionsReservationRequest, - AggregatedListResourcePoliciesRequest, - DeleteResourcePolicyRequest, - GetResourcePolicyRequest, - GetIamPolicyResourcePolicyRequest, - InsertResourcePolicyRequest, - ListResourcePoliciesRequest, - SetIamPolicyResourcePolicyRequest, - TestIamPermissionsResourcePolicyRequest, - AggregatedListRoutersRequest, - DeleteRouterRequest, - GetRouterRequest, - GetNatMappingInfoRoutersRequest, - GetRouterStatusRouterRequest, - InsertRouterRequest, - ListRoutersRequest, - PatchRouterRequest, - PreviewRouterRequest, - UpdateRouterRequest, - DeleteRouteRequest, - GetRouteRequest, - InsertRouteRequest, - ListRoutesRequest, - AddRuleSecurityPolicyRequest, - DeleteSecurityPolicyRequest, - GetSecurityPolicyRequest, - GetRuleSecurityPolicyRequest, - InsertSecurityPolicyRequest, - ListSecurityPoliciesRequest, - ListPreconfiguredExpressionSetsSecurityPoliciesRequest, - PatchSecurityPolicyRequest, - PatchRuleSecurityPolicyRequest, - RemoveRuleSecurityPolicyRequest, - DeleteSnapshotRequest, - GetSnapshotRequest, - GetIamPolicySnapshotRequest, - ListSnapshotsRequest, - SetIamPolicySnapshotRequest, - SetLabelsSnapshotRequest, - TestIamPermissionsSnapshotRequest, - AggregatedListSslCertificatesRequest, - DeleteSslCertificateRequest, - GetSslCertificateRequest, - InsertSslCertificateRequest, - ListSslCertificatesRequest, - DeleteSslPolicyRequest, - GetSslPolicyRequest, - InsertSslPolicyRequest, - ListSslPoliciesRequest, - ListAvailableFeaturesSslPoliciesRequest, - PatchSslPolicyRequest, - AggregatedListSubnetworksRequest, - DeleteSubnetworkRequest, - ExpandIpCidrRangeSubnetworkRequest, - GetSubnetworkRequest, - GetIamPolicySubnetworkRequest, - InsertSubnetworkRequest, - ListSubnetworksRequest, - ListUsableSubnetworksRequest, - PatchSubnetworkRequest, - SetIamPolicySubnetworkRequest, - SetPrivateIpGoogleAccessSubnetworkRequest, - TestIamPermissionsSubnetworkRequest, - DeleteTargetGrpcProxyRequest, - GetTargetGrpcProxyRequest, - InsertTargetGrpcProxyRequest, - ListTargetGrpcProxiesRequest, - PatchTargetGrpcProxyRequest, - AggregatedListTargetHttpProxiesRequest, - DeleteTargetHttpProxyRequest, - GetTargetHttpProxyRequest, - InsertTargetHttpProxyRequest, - ListTargetHttpProxiesRequest, - PatchTargetHttpProxyRequest, - SetUrlMapTargetHttpProxyRequest, - AggregatedListTargetHttpsProxiesRequest, - DeleteTargetHttpsProxyRequest, - GetTargetHttpsProxyRequest, - InsertTargetHttpsProxyRequest, - ListTargetHttpsProxiesRequest, - SetQuicOverrideTargetHttpsProxyRequest, - SetSslCertificatesTargetHttpsProxyRequest, - SetSslPolicyTargetHttpsProxyRequest, - SetUrlMapTargetHttpsProxyRequest, - AggregatedListTargetInstancesRequest, - DeleteTargetInstanceRequest, - GetTargetInstanceRequest, - InsertTargetInstanceRequest, - ListTargetInstancesRequest, - AddHealthCheckTargetPoolRequest, - AddInstanceTargetPoolRequest, - AggregatedListTargetPoolsRequest, - DeleteTargetPoolRequest, - GetTargetPoolRequest, - GetHealthTargetPoolRequest, - InsertTargetPoolRequest, - ListTargetPoolsRequest, - RemoveHealthCheckTargetPoolRequest, - RemoveInstanceTargetPoolRequest, - SetBackupTargetPoolRequest, - DeleteTargetSslProxyRequest, - GetTargetSslProxyRequest, - InsertTargetSslProxyRequest, - ListTargetSslProxiesRequest, - SetBackendServiceTargetSslProxyRequest, - SetProxyHeaderTargetSslProxyRequest, - SetSslCertificatesTargetSslProxyRequest, - SetSslPolicyTargetSslProxyRequest, - DeleteTargetTcpProxyRequest, - GetTargetTcpProxyRequest, - InsertTargetTcpProxyRequest, - ListTargetTcpProxiesRequest, - SetBackendServiceTargetTcpProxyRequest, - SetProxyHeaderTargetTcpProxyRequest, - AggregatedListTargetVpnGatewaysRequest, - DeleteTargetVpnGatewayRequest, - GetTargetVpnGatewayRequest, - InsertTargetVpnGatewayRequest, - ListTargetVpnGatewaysRequest, - AggregatedListUrlMapsRequest, - DeleteUrlMapRequest, - GetUrlMapRequest, - InsertUrlMapRequest, - InvalidateCacheUrlMapRequest, - ListUrlMapsRequest, - PatchUrlMapRequest, - UpdateUrlMapRequest, - ValidateUrlMapRequest, - AggregatedListVpnGatewaysRequest, - DeleteVpnGatewayRequest, - GetVpnGatewayRequest, - GetStatusVpnGatewayRequest, - InsertVpnGatewayRequest, - ListVpnGatewaysRequest, - SetLabelsVpnGatewayRequest, - TestIamPermissionsVpnGatewayRequest, - AggregatedListVpnTunnelsRequest, - DeleteVpnTunnelRequest, - GetVpnTunnelRequest, - InsertVpnTunnelRequest, - ListVpnTunnelsRequest, - DeleteZoneOperationRequest, - DeleteZoneOperationResponse, - GetZoneOperationRequest, - ListZoneOperationsRequest, - WaitZoneOperationRequest, - GetZoneRequest, - ListZonesRequest, -) - -__all__ = ( - "AcceleratorConfig", - "DeprecationStatus", - "AcceleratorType", - "AcceleratorTypesScopedList", - "Data", - "Warning", - "AcceleratorTypeAggregatedList", - "AcceleratorTypeList", - "AccessConfig", - "Address", - "AddressesScopedList", - "AddressAggregatedList", - "AddressList", - "AliasIpRange", - "AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk", - "AllocationSpecificSKUAllocationReservedInstanceProperties", - "AllocationSpecificSKUReservation", - "CustomerEncryptionKey", - "GuestOsFeature", - "AttachedDiskInitializeParams", - "InitialStateConfig", - "AttachedDisk", - "AuditLogConfig", - "AuditConfig", - "AuthorizationLoggingOptions", - "AutoscalingPolicy", - "AutoscalerStatusDetails", - "Autoscaler", - "AutoscalersScopedList", - "AutoscalerAggregatedList", - "AutoscalerList", - "AutoscalingPolicyCpuUtilization", - "AutoscalingPolicyCustomMetricUtilization", - "AutoscalingPolicyLoadBalancingUtilization", - "AutoscalingPolicyScaleInControl", - "FixedOrPercent", - "Backend", - "BackendBucketCdnPolicy", - "BackendBucket", - "BackendBucketList", - "BackendServiceCdnPolicy", - "CircuitBreakers", - "ConnectionDraining", - "ConsistentHashLoadBalancerSettings", - "BackendServiceFailoverPolicy", - "BackendServiceIAP", - "BackendServiceLogConfig", - "OutlierDetection", - "SecuritySettings", - "BackendService", - "BackendServicesScopedList", - "BackendServiceAggregatedList", - "CacheKeyPolicy", - "HealthStatus", - "BackendServiceGroupHealth", - "BackendServiceList", - "BackendServiceReference", - "Expr", - "Binding", - "CacheInvalidationRule", - "LicenseResourceCommitment", - "Reservation", - "ResourceCommitment", - "Commitment", - "CommitmentsScopedList", - "CommitmentAggregatedList", - "CommitmentList", - "Condition", - "ConfidentialInstanceConfig", - "ConsistentHashLoadBalancerSettingsHttpCookie", - "Duration", - "CorsPolicy", - "CustomerEncryptionKeyProtectedDisk", - "Disk", - "DisksScopedList", - "DiskAggregatedList", - "DiskInstantiationConfig", - "DiskList", - "DiskMoveRequest", - "DiskType", - "DiskTypesScopedList", - "DiskTypeAggregatedList", - "DiskTypeList", - "DisksAddResourcePoliciesRequest", - "DisksRemoveResourcePoliciesRequest", - "DisksResizeRequest", - "DisplayDevice", - "DistributionPolicyZoneConfiguration", - "DistributionPolicy", - "ExchangedPeeringRoute", - "ExchangedPeeringRoutesList", - "ExternalVpnGatewayInterface", - "ExternalVpnGateway", - "ExternalVpnGatewayList", - "FileContentBuffer", - "Allowed", - "Denied", - "FirewallLogConfig", - "Firewall", - "FirewallList", - "MetadataFilter", - "ForwardingRule", - "ForwardingRulesScopedList", - "ForwardingRuleAggregatedList", - "ForwardingRuleList", - "ForwardingRuleReference", - "GRPCHealthCheck", - "NetworkEndpoint", - "GlobalNetworkEndpointGroupsAttachEndpointsRequest", - "GlobalNetworkEndpointGroupsDetachEndpointsRequest", - "GlobalSetLabelsRequest", - "Policy", - "GlobalSetPolicyRequest", - "GuestAttributesValue", - "GuestAttributes", - "GuestAttributesEntry", - "HTTP2HealthCheck", - "HTTPHealthCheck", - "HTTPSHealthCheck", - "HealthCheckLogConfig", - "SSLHealthCheck", - "TCPHealthCheck", - "HealthCheck", - "HealthCheckList", - "HealthCheckReference", - "HealthCheckService", - "HealthCheckServiceReference", - "HealthCheckServicesList", - "HealthChecksScopedList", - "HealthChecksAggregatedList", - "HealthStatusForNetworkEndpoint", - "HostRule", - "HttpFaultAbort", - "HttpFaultDelay", - "HttpFaultInjection", - "HttpHeaderOption", - "HttpHeaderAction", - "Int64RangeMatch", - "HttpHeaderMatch", - "HttpQueryParameterMatch", - "HttpRedirectAction", - "HttpRetryPolicy", - "RequestMirrorPolicy", - "UrlRewrite", - "WeightedBackendService", - "HttpRouteAction", - "HttpRouteRuleMatch", - "HttpRouteRule", - "RawDisk", - "Image", - "ImageList", - "Metadata", - "NetworkInterface", - "ReservationAffinity", - "Scheduling", - "ServiceAccount", - "ShieldedInstanceConfig", - "ShieldedInstanceIntegrityPolicy", - "Tags", - "Instance", - "InstancesScopedList", - "InstanceAggregatedList", - "NamedPort", - "InstanceGroup", - "InstanceGroupsScopedList", - "InstanceGroupAggregatedList", - "InstanceGroupList", - "InstanceGroupManagerAutoHealingPolicy", - "InstanceGroupManagerActionsSummary", - "StatefulPolicy", - "InstanceGroupManagerStatus", - "InstanceGroupManagerUpdatePolicy", - "InstanceGroupManagerVersion", - "InstanceGroupManager", - "InstanceGroupManagersScopedList", - "InstanceGroupManagerAggregatedList", - "InstanceGroupManagerList", - "InstanceGroupManagerStatusStateful", - "InstanceGroupManagerStatusVersionTarget", - "InstanceGroupManagerStatusStatefulPerInstanceConfigs", - "InstanceGroupManagersAbandonInstancesRequest", - "InstanceGroupManagersApplyUpdatesRequest", - "PerInstanceConfig", - "InstanceGroupManagersCreateInstancesRequest", - "InstanceGroupManagersDeleteInstancesRequest", - "InstanceGroupManagersDeletePerInstanceConfigsReq", - "InstanceManagedByIgmError", - "InstanceGroupManagersListErrorsResponse", - "ManagedInstance", - "InstanceGroupManagersListManagedInstancesResponse", - "InstanceGroupManagersListPerInstanceConfigsResp", - "InstanceGroupManagersPatchPerInstanceConfigsReq", - "InstanceGroupManagersRecreateInstancesRequest", - "InstanceGroupManagersSetInstanceTemplateRequest", - "InstanceGroupManagersSetTargetPoolsRequest", - "InstanceGroupManagersUpdatePerInstanceConfigsReq", - "InstanceReference", - "InstanceGroupsAddInstancesRequest", - "InstanceWithNamedPorts", - "InstanceGroupsListInstances", - "InstanceGroupsListInstancesRequest", - "InstanceGroupsRemoveInstancesRequest", - "InstanceGroupsSetNamedPortsRequest", - "InstanceList", - "Reference", - "InstanceListReferrers", - "InstanceManagedByIgmErrorManagedInstanceError", - "InstanceManagedByIgmErrorInstanceActionDetails", - "ManagedInstanceVersion", - "InstanceMoveRequest", - "InstanceProperties", - "SourceInstanceParams", - "InstanceTemplate", - "InstanceTemplateList", - "InstancesAddResourcePoliciesRequest", - "InstancesRemoveResourcePoliciesRequest", - "InstancesSetLabelsRequest", - "InstancesSetMachineResourcesRequest", - "InstancesSetMachineTypeRequest", - "InstancesSetMinCpuPlatformRequest", - "InstancesSetServiceAccountRequest", - "InstancesStartWithEncryptionKeyRequest", - "InterconnectCircuitInfo", - "InterconnectOutageNotification", - "Interconnect", - "InterconnectAttachmentPartnerMetadata", - "InterconnectAttachmentPrivateInfo", - "InterconnectAttachment", - "InterconnectAttachmentsScopedList", - "InterconnectAttachmentAggregatedList", - "InterconnectAttachmentList", - "InterconnectDiagnosticsARPEntry", - "InterconnectDiagnosticsLinkStatus", - "InterconnectDiagnostics", - "InterconnectDiagnosticsLinkLACPStatus", - "InterconnectDiagnosticsLinkOpticalPower", - "InterconnectList", - "InterconnectLocationRegionInfo", - "InterconnectLocation", - "InterconnectLocationList", - "InterconnectsGetDiagnosticsResponse", - "LicenseResourceRequirements", - "License", - "LicenseCodeLicenseAlias", - "LicenseCode", - "LicensesListResponse", - "LocalDisk", - "LogConfigCloudAuditOptions", - "LogConfigCounterOptions", - "LogConfigDataAccessOptions", - "LogConfig", - "LogConfigCounterOptionsCustomField", - "Accelerators", - "ScratchDisks", - "MachineType", - "MachineTypesScopedList", - "MachineTypeAggregatedList", - "MachineTypeList", - "ManagedInstanceInstanceHealth", - "ManagedInstanceLastAttempt", - "PreservedState", - "Errors", - "Items", - "MetadataFilterLabelMatch", - "NetworkPeering", - "NetworkRoutingConfig", - "Network", - "NetworkEndpointGroupAppEngine", - "NetworkEndpointGroupCloudFunction", - "NetworkEndpointGroupCloudRun", - "NetworkEndpointGroup", - "NetworkEndpointGroupsScopedList", - "NetworkEndpointGroupAggregatedList", - "NetworkEndpointGroupList", - "NetworkEndpointGroupsAttachEndpointsRequest", - "NetworkEndpointGroupsDetachEndpointsRequest", - "NetworkEndpointGroupsListEndpointsRequest", - "NetworkEndpointWithHealthStatus", - "NetworkEndpointGroupsListNetworkEndpoints", - "NetworkList", - "NetworksAddPeeringRequest", - "NetworksRemovePeeringRequest", - "NetworksUpdatePeeringRequest", - "NodeGroupAutoscalingPolicy", - "NodeGroupMaintenanceWindow", - "NodeGroup", - "NodeGroupsScopedList", - "NodeGroupAggregatedList", - "NodeGroupList", - "ServerBinding", - "NodeGroupNode", - "NodeGroupsAddNodesRequest", - "NodeGroupsDeleteNodesRequest", - "NodeGroupsListNodes", - "NodeGroupsSetNodeTemplateRequest", - "NodeTemplateNodeTypeFlexibility", - "NodeTemplate", - "NodeTemplatesScopedList", - "NodeTemplateAggregatedList", - "NodeTemplateList", - "NodeType", - "NodeTypesScopedList", - "NodeTypeAggregatedList", - "NodeTypeList", - "NotificationEndpointGrpcSettings", - "NotificationEndpoint", - "NotificationEndpointList", - "Error", - "Warnings", - "Operation", - "OperationsScopedList", - "OperationAggregatedList", - "OperationList", - "PacketMirroringForwardingRuleInfo", - "PacketMirroringFilter", - "PacketMirroringMirroredResourceInfo", - "PacketMirroringNetworkInfo", - "PacketMirroring", - "PacketMirroringsScopedList", - "PacketMirroringAggregatedList", - "PacketMirroringList", - "PacketMirroringMirroredResourceInfoInstanceInfo", - "PacketMirroringMirroredResourceInfoSubnetInfo", - "PathRule", - "PathMatcher", - "Rule", - "WafExpressionSet", - "PreconfiguredWafSet", - "PreservedStatePreservedDisk", - "Quota", - "UsageExportLocation", - "Project", - "XpnResourceId", - "ProjectsDisableXpnResourceRequest", - "ProjectsEnableXpnResourceRequest", - "ProjectsGetXpnResources", - "ProjectsListXpnHostsRequest", - "ProjectsSetDefaultNetworkTierRequest", - "Region", - "RegionAutoscalerList", - "RegionDiskTypeList", - "RegionDisksAddResourcePoliciesRequest", - "RegionDisksRemoveResourcePoliciesRequest", - "RegionDisksResizeRequest", - "RegionInstanceGroupList", - "RegionInstanceGroupManagerDeleteInstanceConfigReq", - "RegionInstanceGroupManagerList", - "RegionInstanceGroupManagerPatchInstanceConfigReq", - "RegionInstanceGroupManagerUpdateInstanceConfigReq", - "RegionInstanceGroupManagersAbandonInstancesRequest", - "RegionInstanceGroupManagersApplyUpdatesRequest", - "RegionInstanceGroupManagersCreateInstancesRequest", - "RegionInstanceGroupManagersDeleteInstancesRequest", - "RegionInstanceGroupManagersListErrorsResponse", - "RegionInstanceGroupManagersListInstanceConfigsResp", - "RegionInstanceGroupManagersListInstancesResponse", - "RegionInstanceGroupManagersRecreateRequest", - "RegionInstanceGroupManagersSetTargetPoolsRequest", - "RegionInstanceGroupManagersSetTemplateRequest", - "RegionInstanceGroupsListInstances", - "RegionInstanceGroupsListInstancesRequest", - "RegionInstanceGroupsSetNamedPortsRequest", - "RegionList", - "RegionSetLabelsRequest", - "RegionSetPolicyRequest", - "RegionTargetHttpsProxiesSetSslCertificatesRequest", - "UrlMap", - "RegionUrlMapsValidateRequest", - "ReservationsScopedList", - "ReservationAggregatedList", - "ReservationList", - "ReservationsResizeRequest", - "ResourceGroupReference", - "ResourcePolicy", - "ResourcePoliciesScopedList", - "ResourcePolicyGroupPlacementPolicy", - "ResourcePolicySnapshotSchedulePolicy", - "ResourcePolicyAggregatedList", - "ResourcePolicyDailyCycle", - "ResourcePolicyHourlyCycle", - "ResourcePolicyList", - "ResourcePolicySnapshotSchedulePolicyRetentionPolicy", - "ResourcePolicySnapshotSchedulePolicySchedule", - "ResourcePolicySnapshotSchedulePolicySnapshotProperties", - "ResourcePolicyWeeklyCycle", - "ResourcePolicyWeeklyCycleDayOfWeek", - "Route", - "RouteList", - "RouterBgp", - "RouterBgpPeer", - "RouterInterface", - "RouterNat", - "Router", - "RouterAdvertisedIpRange", - "RoutersScopedList", - "RouterAggregatedList", - "RouterList", - "RouterNatLogConfig", - "RouterNatSubnetworkToNat", - "RouterStatusBgpPeerStatus", - "RouterStatusNatStatus", - "RouterStatus", - "RouterStatusResponse", - "RoutersPreviewResponse", - "SchedulingNodeAffinity", - "Screenshot", - "SecurityPoliciesWafConfig", - "SecurityPoliciesListPreconfiguredExpressionSetsResponse", - "SecurityPolicyRule", - "SecurityPolicy", - "SecurityPolicyList", - "SecurityPolicyReference", - "SecurityPolicyRuleMatcher", - "SecurityPolicyRuleMatcherConfig", - "SerialPortOutput", - "ShieldedInstanceIdentityEntry", - "ShieldedInstanceIdentity", - "SignedUrlKey", - "Snapshot", - "SnapshotList", - "SslCertificateManagedSslCertificate", - "SslCertificateSelfManagedSslCertificate", - "SslCertificate", - "SslCertificatesScopedList", - "SslCertificateAggregatedList", - "SslCertificateList", - "SslPolicy", - "SslPoliciesList", - "SslPoliciesListAvailableFeaturesResponse", - "SslPolicyReference", - "StatefulPolicyPreservedState", - "StatefulPolicyPreservedStateDiskDevice", - "SubnetworkLogConfig", - "SubnetworkSecondaryRange", - "Subnetwork", - "SubnetworksScopedList", - "SubnetworkAggregatedList", - "SubnetworkList", - "SubnetworksExpandIpCidrRangeRequest", - "SubnetworksSetPrivateIpGoogleAccessRequest", - "TargetGrpcProxy", - "TargetGrpcProxyList", - "TargetHttpProxy", - "TargetHttpProxiesScopedList", - "TargetHttpProxyAggregatedList", - "TargetHttpProxyList", - "TargetHttpsProxy", - "TargetHttpsProxiesScopedList", - "TargetHttpsProxiesSetQuicOverrideRequest", - "TargetHttpsProxiesSetSslCertificatesRequest", - "TargetHttpsProxyAggregatedList", - "TargetHttpsProxyList", - "TargetInstance", - "TargetInstancesScopedList", - "TargetInstanceAggregatedList", - "TargetInstanceList", - "TargetPool", - "TargetPoolsScopedList", - "TargetPoolAggregatedList", - "TargetPoolInstanceHealth", - "TargetPoolList", - "TargetPoolsAddHealthCheckRequest", - "TargetPoolsAddInstanceRequest", - "TargetPoolsRemoveHealthCheckRequest", - "TargetPoolsRemoveInstanceRequest", - "TargetReference", - "TargetSslProxiesSetBackendServiceRequest", - "TargetSslProxiesSetProxyHeaderRequest", - "TargetSslProxiesSetSslCertificatesRequest", - "TargetSslProxy", - "TargetSslProxyList", - "TargetTcpProxiesSetBackendServiceRequest", - "TargetTcpProxiesSetProxyHeaderRequest", - "TargetTcpProxy", - "TargetTcpProxyList", - "TargetVpnGateway", - "TargetVpnGatewaysScopedList", - "TargetVpnGatewayAggregatedList", - "TargetVpnGatewayList", - "TestFailure", - "TestPermissionsRequest", - "TestPermissionsResponse", - "UrlMapTest", - "UrlMapList", - "UrlMapReference", - "UrlMapValidationResult", - "UrlMapsScopedList", - "UrlMapsAggregatedList", - "UrlMapsValidateRequest", - "UrlMapsValidateResponse", - "UsableSubnetworkSecondaryRange", - "UsableSubnetwork", - "UsableSubnetworksAggregatedList", - "VmEndpointNatMappingsInterfaceNatMappings", - "VmEndpointNatMappings", - "VmEndpointNatMappingsList", - "VpnGatewayVpnGatewayInterface", - "VpnGateway", - "VpnGatewaysScopedList", - "VpnGatewayAggregatedList", - "VpnGatewayList", - "VpnGatewayStatusVpnConnection", - "VpnGatewayStatus", - "VpnGatewayStatusHighAvailabilityRequirementState", - "VpnGatewayStatusTunnel", - "VpnGatewaysGetStatusResponse", - "VpnTunnel", - "VpnTunnelsScopedList", - "VpnTunnelAggregatedList", - "VpnTunnelList", - "WafExpressionSetExpression", - "XpnHostList", - "Zone", - "ZoneList", - "ZoneSetLabelsRequest", - "ZoneSetPolicyRequest", +) + +__all__ = ( + "AbandonInstancesInstanceGroupManagerRequest", + "AbandonInstancesRegionInstanceGroupManagerRequest", + "AcceleratorConfig", + "Accelerators", + "AcceleratorType", + "AcceleratorTypeAggregatedList", + "AcceleratorTypeList", + "AcceleratorTypesScopedList", + "AccessConfig", + "AddAccessConfigInstanceRequest", + "AddHealthCheckTargetPoolRequest", + "AddInstancesInstanceGroupRequest", + "AddInstanceTargetPoolRequest", + "AddNodesNodeGroupRequest", + "AddPeeringNetworkRequest", + "AddResourcePoliciesDiskRequest", + "AddResourcePoliciesInstanceRequest", + "AddResourcePoliciesRegionDiskRequest", + "Address", + "AddressAggregatedList", + "AddressesScopedList", + "AddressList", + "AddRuleSecurityPolicyRequest", + "AddSignedUrlKeyBackendBucketRequest", + "AddSignedUrlKeyBackendServiceRequest", "AggregatedListAcceleratorTypesRequest", + "AggregatedListAddressesRequest", + "AggregatedListAutoscalersRequest", + "AggregatedListBackendServicesRequest", + "AggregatedListDisksRequest", + "AggregatedListDiskTypesRequest", + "AggregatedListForwardingRulesRequest", + "AggregatedListGlobalOperationsRequest", + "AggregatedListHealthChecksRequest", + "AggregatedListInstanceGroupManagersRequest", + "AggregatedListInstanceGroupsRequest", + "AggregatedListInstancesRequest", + "AggregatedListInterconnectAttachmentsRequest", + "AggregatedListMachineTypesRequest", + "AggregatedListNetworkEndpointGroupsRequest", + "AggregatedListNodeGroupsRequest", + "AggregatedListNodeTemplatesRequest", + "AggregatedListNodeTypesRequest", + "AggregatedListPacketMirroringsRequest", + "AggregatedListRegionCommitmentsRequest", + "AggregatedListReservationsRequest", + "AggregatedListResourcePoliciesRequest", + "AggregatedListRoutersRequest", + "AggregatedListSslCertificatesRequest", + "AggregatedListSubnetworksRequest", + "AggregatedListTargetHttpProxiesRequest", + "AggregatedListTargetHttpsProxiesRequest", + "AggregatedListTargetInstancesRequest", + "AggregatedListTargetPoolsRequest", + "AggregatedListTargetVpnGatewaysRequest", + "AggregatedListUrlMapsRequest", + "AggregatedListVpnGatewaysRequest", + "AggregatedListVpnTunnelsRequest", + "AliasIpRange", + "AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk", + "AllocationSpecificSKUAllocationReservedInstanceProperties", + "AllocationSpecificSKUReservation", + "Allowed", + "ApplyUpdatesToInstancesInstanceGroupManagerRequest", + "ApplyUpdatesToInstancesRegionInstanceGroupManagerRequest", + "AttachDiskInstanceRequest", + "AttachedDisk", + "AttachedDiskInitializeParams", + "AttachNetworkEndpointsGlobalNetworkEndpointGroupRequest", + "AttachNetworkEndpointsNetworkEndpointGroupRequest", + "AuditConfig", + "AuditLogConfig", + "AuthorizationLoggingOptions", + "Autoscaler", + "AutoscalerAggregatedList", + "AutoscalerList", + "AutoscalersScopedList", + "AutoscalerStatusDetails", + "AutoscalingPolicy", + "AutoscalingPolicyCpuUtilization", + "AutoscalingPolicyCustomMetricUtilization", + "AutoscalingPolicyLoadBalancingUtilization", + "AutoscalingPolicyScaleInControl", + "Backend", + "BackendBucket", + "BackendBucketCdnPolicy", + "BackendBucketList", + "BackendService", + "BackendServiceAggregatedList", + "BackendServiceCdnPolicy", + "BackendServiceFailoverPolicy", + "BackendServiceGroupHealth", + "BackendServiceIAP", + "BackendServiceList", + "BackendServiceLogConfig", + "BackendServiceReference", + "BackendServicesScopedList", + "Binding", + "CacheInvalidationRule", + "CacheKeyPolicy", + "CircuitBreakers", + "Commitment", + "CommitmentAggregatedList", + "CommitmentList", + "CommitmentsScopedList", + "Condition", + "ConfidentialInstanceConfig", + "ConnectionDraining", + "ConsistentHashLoadBalancerSettings", + "ConsistentHashLoadBalancerSettingsHttpCookie", + "CorsPolicy", + "CreateInstancesInstanceGroupManagerRequest", + "CreateInstancesRegionInstanceGroupManagerRequest", + "CreateSnapshotDiskRequest", + "CreateSnapshotRegionDiskRequest", + "CustomerEncryptionKey", + "CustomerEncryptionKeyProtectedDisk", + "Data", + "DeleteAccessConfigInstanceRequest", + "DeleteAddressRequest", + "DeleteAutoscalerRequest", + "DeleteBackendBucketRequest", + "DeleteBackendServiceRequest", + "DeleteDiskRequest", + "DeleteExternalVpnGatewayRequest", + "DeleteFirewallRequest", + "DeleteForwardingRuleRequest", + "DeleteGlobalAddressRequest", + "DeleteGlobalForwardingRuleRequest", + "DeleteGlobalNetworkEndpointGroupRequest", + "DeleteGlobalOperationRequest", + "DeleteGlobalOperationResponse", + "DeleteGlobalOrganizationOperationRequest", + "DeleteGlobalOrganizationOperationResponse", + "DeleteHealthCheckRequest", + "DeleteImageRequest", + "DeleteInstanceGroupManagerRequest", + "DeleteInstanceGroupRequest", + "DeleteInstanceRequest", + "DeleteInstancesInstanceGroupManagerRequest", + "DeleteInstancesRegionInstanceGroupManagerRequest", + "DeleteInstanceTemplateRequest", + "DeleteInterconnectAttachmentRequest", + "DeleteInterconnectRequest", + "DeleteLicenseRequest", + "DeleteNetworkEndpointGroupRequest", + "DeleteNetworkRequest", + "DeleteNodeGroupRequest", + "DeleteNodesNodeGroupRequest", + "DeleteNodeTemplateRequest", + "DeletePacketMirroringRequest", + "DeletePerInstanceConfigsInstanceGroupManagerRequest", + "DeletePerInstanceConfigsRegionInstanceGroupManagerRequest", + "DeleteRegionAutoscalerRequest", + "DeleteRegionBackendServiceRequest", + "DeleteRegionDiskRequest", + "DeleteRegionHealthCheckRequest", + "DeleteRegionHealthCheckServiceRequest", + "DeleteRegionInstanceGroupManagerRequest", + "DeleteRegionNetworkEndpointGroupRequest", + "DeleteRegionNotificationEndpointRequest", + "DeleteRegionOperationRequest", + "DeleteRegionOperationResponse", + "DeleteRegionSslCertificateRequest", + "DeleteRegionTargetHttpProxyRequest", + "DeleteRegionTargetHttpsProxyRequest", + "DeleteRegionUrlMapRequest", + "DeleteReservationRequest", + "DeleteResourcePolicyRequest", + "DeleteRouteRequest", + "DeleteRouterRequest", + "DeleteSecurityPolicyRequest", + "DeleteSignedUrlKeyBackendBucketRequest", + "DeleteSignedUrlKeyBackendServiceRequest", + "DeleteSnapshotRequest", + "DeleteSslCertificateRequest", + "DeleteSslPolicyRequest", + "DeleteSubnetworkRequest", + "DeleteTargetGrpcProxyRequest", + "DeleteTargetHttpProxyRequest", + "DeleteTargetHttpsProxyRequest", + "DeleteTargetInstanceRequest", + "DeleteTargetPoolRequest", + "DeleteTargetSslProxyRequest", + "DeleteTargetTcpProxyRequest", + "DeleteTargetVpnGatewayRequest", + "DeleteUrlMapRequest", + "DeleteVpnGatewayRequest", + "DeleteVpnTunnelRequest", + "DeleteZoneOperationRequest", + "DeleteZoneOperationResponse", + "Denied", + "DeprecateImageRequest", + "DeprecationStatus", + "DetachDiskInstanceRequest", + "DetachNetworkEndpointsGlobalNetworkEndpointGroupRequest", + "DetachNetworkEndpointsNetworkEndpointGroupRequest", + "DisableXpnHostProjectRequest", + "DisableXpnResourceProjectRequest", + "Disk", + "DiskAggregatedList", + "DiskInstantiationConfig", + "DiskList", + "DiskMoveRequest", + "DisksAddResourcePoliciesRequest", + "DisksRemoveResourcePoliciesRequest", + "DisksResizeRequest", + "DisksScopedList", + "DiskType", + "DiskTypeAggregatedList", + "DiskTypeList", + "DiskTypesScopedList", + "DisplayDevice", + "DistributionPolicy", + "DistributionPolicyZoneConfiguration", + "Duration", + "EnableXpnHostProjectRequest", + "EnableXpnResourceProjectRequest", + "Error", + "Errors", + "ExchangedPeeringRoute", + "ExchangedPeeringRoutesList", + "ExpandIpCidrRangeSubnetworkRequest", + "Expr", + "ExternalVpnGateway", + "ExternalVpnGatewayInterface", + "ExternalVpnGatewayList", + "FileContentBuffer", + "Firewall", + "FirewallList", + "FirewallLogConfig", + "FixedOrPercent", + "ForwardingRule", + "ForwardingRuleAggregatedList", + "ForwardingRuleList", + "ForwardingRuleReference", + "ForwardingRulesScopedList", "GetAcceleratorTypeRequest", + "GetAddressRequest", + "GetAutoscalerRequest", + "GetBackendBucketRequest", + "GetBackendServiceRequest", + "GetDiagnosticsInterconnectRequest", + "GetDiskRequest", + "GetDiskTypeRequest", + "GetExternalVpnGatewayRequest", + "GetFirewallRequest", + "GetForwardingRuleRequest", + "GetFromFamilyImageRequest", + "GetGlobalAddressRequest", + "GetGlobalForwardingRuleRequest", + "GetGlobalNetworkEndpointGroupRequest", + "GetGlobalOperationRequest", + "GetGlobalOrganizationOperationRequest", + "GetGuestAttributesInstanceRequest", + "GetHealthBackendServiceRequest", + "GetHealthCheckRequest", + "GetHealthRegionBackendServiceRequest", + "GetHealthTargetPoolRequest", + "GetIamPolicyDiskRequest", + "GetIamPolicyImageRequest", + "GetIamPolicyInstanceRequest", + "GetIamPolicyInstanceTemplateRequest", + "GetIamPolicyLicenseRequest", + "GetIamPolicyNodeGroupRequest", + "GetIamPolicyNodeTemplateRequest", + "GetIamPolicyRegionDiskRequest", + "GetIamPolicyReservationRequest", + "GetIamPolicyResourcePolicyRequest", + "GetIamPolicySnapshotRequest", + "GetIamPolicySubnetworkRequest", + "GetImageRequest", + "GetInstanceGroupManagerRequest", + "GetInstanceGroupRequest", + "GetInstanceRequest", + "GetInstanceTemplateRequest", + "GetInterconnectAttachmentRequest", + "GetInterconnectLocationRequest", + "GetInterconnectRequest", + "GetLicenseCodeRequest", + "GetLicenseRequest", + "GetMachineTypeRequest", + "GetNatMappingInfoRoutersRequest", + "GetNetworkEndpointGroupRequest", + "GetNetworkRequest", + "GetNodeGroupRequest", + "GetNodeTemplateRequest", + "GetNodeTypeRequest", + "GetPacketMirroringRequest", + "GetProjectRequest", + "GetRegionAutoscalerRequest", + "GetRegionBackendServiceRequest", + "GetRegionCommitmentRequest", + "GetRegionDiskRequest", + "GetRegionDiskTypeRequest", + "GetRegionHealthCheckRequest", + "GetRegionHealthCheckServiceRequest", + "GetRegionInstanceGroupManagerRequest", + "GetRegionInstanceGroupRequest", + "GetRegionNetworkEndpointGroupRequest", + "GetRegionNotificationEndpointRequest", + "GetRegionOperationRequest", + "GetRegionRequest", + "GetRegionSslCertificateRequest", + "GetRegionTargetHttpProxyRequest", + "GetRegionTargetHttpsProxyRequest", + "GetRegionUrlMapRequest", + "GetReservationRequest", + "GetResourcePolicyRequest", + "GetRouteRequest", + "GetRouterRequest", + "GetRouterStatusRouterRequest", + "GetRuleSecurityPolicyRequest", + "GetScreenshotInstanceRequest", + "GetSecurityPolicyRequest", + "GetSerialPortOutputInstanceRequest", + "GetShieldedInstanceIdentityInstanceRequest", + "GetSnapshotRequest", + "GetSslCertificateRequest", + "GetSslPolicyRequest", + "GetStatusVpnGatewayRequest", + "GetSubnetworkRequest", + "GetTargetGrpcProxyRequest", + "GetTargetHttpProxyRequest", + "GetTargetHttpsProxyRequest", + "GetTargetInstanceRequest", + "GetTargetPoolRequest", + "GetTargetSslProxyRequest", + "GetTargetTcpProxyRequest", + "GetTargetVpnGatewayRequest", + "GetUrlMapRequest", + "GetVpnGatewayRequest", + "GetVpnTunnelRequest", + "GetXpnHostProjectRequest", + "GetXpnResourcesProjectsRequest", + "GetZoneOperationRequest", + "GetZoneRequest", + "GlobalNetworkEndpointGroupsAttachEndpointsRequest", + "GlobalNetworkEndpointGroupsDetachEndpointsRequest", + "GlobalSetLabelsRequest", + "GlobalSetPolicyRequest", + "GRPCHealthCheck", + "GuestAttributes", + "GuestAttributesEntry", + "GuestAttributesValue", + "GuestOsFeature", + "HealthCheck", + "HealthCheckList", + "HealthCheckLogConfig", + "HealthCheckReference", + "HealthChecksAggregatedList", + "HealthCheckService", + "HealthCheckServiceReference", + "HealthCheckServicesList", + "HealthChecksScopedList", + "HealthStatus", + "HealthStatusForNetworkEndpoint", + "HostRule", + "HTTP2HealthCheck", + "HttpFaultAbort", + "HttpFaultDelay", + "HttpFaultInjection", + "HttpHeaderAction", + "HttpHeaderMatch", + "HttpHeaderOption", + "HTTPHealthCheck", + "HttpQueryParameterMatch", + "HttpRedirectAction", + "HttpRetryPolicy", + "HttpRouteAction", + "HttpRouteRule", + "HttpRouteRuleMatch", + "HTTPSHealthCheck", + "Image", + "ImageList", + "InitialStateConfig", + "InsertAddressRequest", + "InsertAutoscalerRequest", + "InsertBackendBucketRequest", + "InsertBackendServiceRequest", + "InsertDiskRequest", + "InsertExternalVpnGatewayRequest", + "InsertFirewallRequest", + "InsertForwardingRuleRequest", + "InsertGlobalAddressRequest", + "InsertGlobalForwardingRuleRequest", + "InsertGlobalNetworkEndpointGroupRequest", + "InsertHealthCheckRequest", + "InsertImageRequest", + "InsertInstanceGroupManagerRequest", + "InsertInstanceGroupRequest", + "InsertInstanceRequest", + "InsertInstanceTemplateRequest", + "InsertInterconnectAttachmentRequest", + "InsertInterconnectRequest", + "InsertLicenseRequest", + "InsertNetworkEndpointGroupRequest", + "InsertNetworkRequest", + "InsertNodeGroupRequest", + "InsertNodeTemplateRequest", + "InsertPacketMirroringRequest", + "InsertRegionAutoscalerRequest", + "InsertRegionBackendServiceRequest", + "InsertRegionCommitmentRequest", + "InsertRegionDiskRequest", + "InsertRegionHealthCheckRequest", + "InsertRegionHealthCheckServiceRequest", + "InsertRegionInstanceGroupManagerRequest", + "InsertRegionNetworkEndpointGroupRequest", + "InsertRegionNotificationEndpointRequest", + "InsertRegionSslCertificateRequest", + "InsertRegionTargetHttpProxyRequest", + "InsertRegionTargetHttpsProxyRequest", + "InsertRegionUrlMapRequest", + "InsertReservationRequest", + "InsertResourcePolicyRequest", + "InsertRouteRequest", + "InsertRouterRequest", + "InsertSecurityPolicyRequest", + "InsertSslCertificateRequest", + "InsertSslPolicyRequest", + "InsertSubnetworkRequest", + "InsertTargetGrpcProxyRequest", + "InsertTargetHttpProxyRequest", + "InsertTargetHttpsProxyRequest", + "InsertTargetInstanceRequest", + "InsertTargetPoolRequest", + "InsertTargetSslProxyRequest", + "InsertTargetTcpProxyRequest", + "InsertTargetVpnGatewayRequest", + "InsertUrlMapRequest", + "InsertVpnGatewayRequest", + "InsertVpnTunnelRequest", + "Instance", + "InstanceAggregatedList", + "InstanceGroup", + "InstanceGroupAggregatedList", + "InstanceGroupList", + "InstanceGroupManager", + "InstanceGroupManagerActionsSummary", + "InstanceGroupManagerAggregatedList", + "InstanceGroupManagerAutoHealingPolicy", + "InstanceGroupManagerList", + "InstanceGroupManagersAbandonInstancesRequest", + "InstanceGroupManagersApplyUpdatesRequest", + "InstanceGroupManagersCreateInstancesRequest", + "InstanceGroupManagersDeleteInstancesRequest", + "InstanceGroupManagersDeletePerInstanceConfigsReq", + "InstanceGroupManagersListErrorsResponse", + "InstanceGroupManagersListManagedInstancesResponse", + "InstanceGroupManagersListPerInstanceConfigsResp", + "InstanceGroupManagersPatchPerInstanceConfigsReq", + "InstanceGroupManagersRecreateInstancesRequest", + "InstanceGroupManagersScopedList", + "InstanceGroupManagersSetInstanceTemplateRequest", + "InstanceGroupManagersSetTargetPoolsRequest", + "InstanceGroupManagerStatus", + "InstanceGroupManagerStatusStateful", + "InstanceGroupManagerStatusStatefulPerInstanceConfigs", + "InstanceGroupManagerStatusVersionTarget", + "InstanceGroupManagersUpdatePerInstanceConfigsReq", + "InstanceGroupManagerUpdatePolicy", + "InstanceGroupManagerVersion", + "InstanceGroupsAddInstancesRequest", + "InstanceGroupsListInstances", + "InstanceGroupsListInstancesRequest", + "InstanceGroupsRemoveInstancesRequest", + "InstanceGroupsScopedList", + "InstanceGroupsSetNamedPortsRequest", + "InstanceList", + "InstanceListReferrers", + "InstanceManagedByIgmError", + "InstanceManagedByIgmErrorInstanceActionDetails", + "InstanceManagedByIgmErrorManagedInstanceError", + "InstanceMoveRequest", + "InstanceProperties", + "InstanceReference", + "InstancesAddResourcePoliciesRequest", + "InstancesRemoveResourcePoliciesRequest", + "InstancesScopedList", + "InstancesSetLabelsRequest", + "InstancesSetMachineResourcesRequest", + "InstancesSetMachineTypeRequest", + "InstancesSetMinCpuPlatformRequest", + "InstancesSetServiceAccountRequest", + "InstancesStartWithEncryptionKeyRequest", + "InstanceTemplate", + "InstanceTemplateList", + "InstanceWithNamedPorts", + "Int64RangeMatch", + "Interconnect", + "InterconnectAttachment", + "InterconnectAttachmentAggregatedList", + "InterconnectAttachmentList", + "InterconnectAttachmentPartnerMetadata", + "InterconnectAttachmentPrivateInfo", + "InterconnectAttachmentsScopedList", + "InterconnectCircuitInfo", + "InterconnectDiagnostics", + "InterconnectDiagnosticsARPEntry", + "InterconnectDiagnosticsLinkLACPStatus", + "InterconnectDiagnosticsLinkOpticalPower", + "InterconnectDiagnosticsLinkStatus", + "InterconnectList", + "InterconnectLocation", + "InterconnectLocationList", + "InterconnectLocationRegionInfo", + "InterconnectOutageNotification", + "InterconnectsGetDiagnosticsResponse", + "InvalidateCacheUrlMapRequest", + "Items", + "License", + "LicenseCode", + "LicenseCodeLicenseAlias", + "LicenseResourceCommitment", + "LicenseResourceRequirements", + "LicensesListResponse", "ListAcceleratorTypesRequest", - "AggregatedListAddressesRequest", - "DeleteAddressRequest", - "GetAddressRequest", - "InsertAddressRequest", "ListAddressesRequest", - "AggregatedListAutoscalersRequest", - "DeleteAutoscalerRequest", - "GetAutoscalerRequest", - "InsertAutoscalerRequest", "ListAutoscalersRequest", - "PatchAutoscalerRequest", - "UpdateAutoscalerRequest", - "AddSignedUrlKeyBackendBucketRequest", - "DeleteBackendBucketRequest", - "DeleteSignedUrlKeyBackendBucketRequest", - "GetBackendBucketRequest", - "InsertBackendBucketRequest", + "ListAvailableFeaturesSslPoliciesRequest", "ListBackendBucketsRequest", - "PatchBackendBucketRequest", - "UpdateBackendBucketRequest", - "AddSignedUrlKeyBackendServiceRequest", - "AggregatedListBackendServicesRequest", - "DeleteBackendServiceRequest", - "DeleteSignedUrlKeyBackendServiceRequest", - "GetBackendServiceRequest", - "GetHealthBackendServiceRequest", - "InsertBackendServiceRequest", "ListBackendServicesRequest", - "PatchBackendServiceRequest", - "SetSecurityPolicyBackendServiceRequest", - "UpdateBackendServiceRequest", - "AggregatedListDiskTypesRequest", - "GetDiskTypeRequest", - "ListDiskTypesRequest", - "AddResourcePoliciesDiskRequest", - "AggregatedListDisksRequest", - "CreateSnapshotDiskRequest", - "DeleteDiskRequest", - "GetDiskRequest", - "GetIamPolicyDiskRequest", - "InsertDiskRequest", "ListDisksRequest", - "RemoveResourcePoliciesDiskRequest", - "ResizeDiskRequest", - "SetIamPolicyDiskRequest", - "SetLabelsDiskRequest", - "TestIamPermissionsDiskRequest", - "DeleteExternalVpnGatewayRequest", - "GetExternalVpnGatewayRequest", - "InsertExternalVpnGatewayRequest", + "ListDiskTypesRequest", + "ListErrorsInstanceGroupManagersRequest", + "ListErrorsRegionInstanceGroupManagersRequest", "ListExternalVpnGatewaysRequest", - "SetLabelsExternalVpnGatewayRequest", - "TestIamPermissionsExternalVpnGatewayRequest", - "DeleteFirewallRequest", - "GetFirewallRequest", - "InsertFirewallRequest", "ListFirewallsRequest", - "PatchFirewallRequest", - "UpdateFirewallRequest", - "AggregatedListForwardingRulesRequest", - "DeleteForwardingRuleRequest", - "GetForwardingRuleRequest", - "InsertForwardingRuleRequest", "ListForwardingRulesRequest", - "PatchForwardingRuleRequest", - "SetTargetForwardingRuleRequest", - "DeleteGlobalAddressRequest", - "GetGlobalAddressRequest", - "InsertGlobalAddressRequest", "ListGlobalAddressesRequest", - "DeleteGlobalForwardingRuleRequest", - "GetGlobalForwardingRuleRequest", - "InsertGlobalForwardingRuleRequest", "ListGlobalForwardingRulesRequest", - "PatchGlobalForwardingRuleRequest", - "SetTargetGlobalForwardingRuleRequest", - "AttachNetworkEndpointsGlobalNetworkEndpointGroupRequest", - "DeleteGlobalNetworkEndpointGroupRequest", - "DetachNetworkEndpointsGlobalNetworkEndpointGroupRequest", - "GetGlobalNetworkEndpointGroupRequest", - "InsertGlobalNetworkEndpointGroupRequest", "ListGlobalNetworkEndpointGroupsRequest", - "ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest", - "AggregatedListGlobalOperationsRequest", - "DeleteGlobalOperationRequest", - "DeleteGlobalOperationResponse", - "GetGlobalOperationRequest", "ListGlobalOperationsRequest", - "WaitGlobalOperationRequest", - "DeleteGlobalOrganizationOperationRequest", - "DeleteGlobalOrganizationOperationResponse", - "GetGlobalOrganizationOperationRequest", "ListGlobalOrganizationOperationsRequest", - "AggregatedListHealthChecksRequest", - "DeleteHealthCheckRequest", - "GetHealthCheckRequest", - "InsertHealthCheckRequest", "ListHealthChecksRequest", - "PatchHealthCheckRequest", - "UpdateHealthCheckRequest", - "DeleteImageRequest", - "DeprecateImageRequest", - "GetImageRequest", - "GetFromFamilyImageRequest", - "GetIamPolicyImageRequest", - "InsertImageRequest", "ListImagesRequest", - "PatchImageRequest", - "SetIamPolicyImageRequest", - "SetLabelsImageRequest", - "TestIamPermissionsImageRequest", - "AbandonInstancesInstanceGroupManagerRequest", - "AggregatedListInstanceGroupManagersRequest", - "ApplyUpdatesToInstancesInstanceGroupManagerRequest", - "CreateInstancesInstanceGroupManagerRequest", - "DeleteInstanceGroupManagerRequest", - "DeleteInstancesInstanceGroupManagerRequest", - "DeletePerInstanceConfigsInstanceGroupManagerRequest", - "GetInstanceGroupManagerRequest", - "InsertInstanceGroupManagerRequest", "ListInstanceGroupManagersRequest", - "ListErrorsInstanceGroupManagersRequest", - "ListManagedInstancesInstanceGroupManagersRequest", - "ListPerInstanceConfigsInstanceGroupManagersRequest", - "PatchInstanceGroupManagerRequest", - "PatchPerInstanceConfigsInstanceGroupManagerRequest", - "RecreateInstancesInstanceGroupManagerRequest", - "ResizeInstanceGroupManagerRequest", - "SetInstanceTemplateInstanceGroupManagerRequest", - "SetTargetPoolsInstanceGroupManagerRequest", - "UpdatePerInstanceConfigsInstanceGroupManagerRequest", - "AddInstancesInstanceGroupRequest", - "AggregatedListInstanceGroupsRequest", - "DeleteInstanceGroupRequest", - "GetInstanceGroupRequest", - "InsertInstanceGroupRequest", "ListInstanceGroupsRequest", "ListInstancesInstanceGroupsRequest", - "RemoveInstancesInstanceGroupRequest", - "SetNamedPortsInstanceGroupRequest", - "DeleteInstanceTemplateRequest", - "GetInstanceTemplateRequest", - "GetIamPolicyInstanceTemplateRequest", - "InsertInstanceTemplateRequest", - "ListInstanceTemplatesRequest", - "SetIamPolicyInstanceTemplateRequest", - "TestIamPermissionsInstanceTemplateRequest", - "AddAccessConfigInstanceRequest", - "AddResourcePoliciesInstanceRequest", - "AggregatedListInstancesRequest", - "AttachDiskInstanceRequest", - "DeleteInstanceRequest", - "DeleteAccessConfigInstanceRequest", - "DetachDiskInstanceRequest", - "GetInstanceRequest", - "GetGuestAttributesInstanceRequest", - "GetIamPolicyInstanceRequest", - "GetScreenshotInstanceRequest", - "GetSerialPortOutputInstanceRequest", - "GetShieldedInstanceIdentityInstanceRequest", - "InsertInstanceRequest", + "ListInstancesRegionInstanceGroupsRequest", "ListInstancesRequest", - "ListReferrersInstancesRequest", - "RemoveResourcePoliciesInstanceRequest", - "ResetInstanceRequest", - "SetDeletionProtectionInstanceRequest", - "SetDiskAutoDeleteInstanceRequest", - "SetIamPolicyInstanceRequest", - "SetLabelsInstanceRequest", - "SetMachineResourcesInstanceRequest", - "SetMachineTypeInstanceRequest", - "SetMetadataInstanceRequest", - "SetMinCpuPlatformInstanceRequest", - "SetSchedulingInstanceRequest", - "SetServiceAccountInstanceRequest", - "SetShieldedInstanceIntegrityPolicyInstanceRequest", - "SetTagsInstanceRequest", - "SimulateMaintenanceEventInstanceRequest", - "StartInstanceRequest", - "StartWithEncryptionKeyInstanceRequest", - "StopInstanceRequest", - "TestIamPermissionsInstanceRequest", - "UpdateInstanceRequest", - "UpdateAccessConfigInstanceRequest", - "UpdateDisplayDeviceInstanceRequest", - "UpdateNetworkInterfaceInstanceRequest", - "UpdateShieldedInstanceConfigInstanceRequest", - "AggregatedListInterconnectAttachmentsRequest", - "DeleteInterconnectAttachmentRequest", - "GetInterconnectAttachmentRequest", - "InsertInterconnectAttachmentRequest", + "ListInstanceTemplatesRequest", "ListInterconnectAttachmentsRequest", - "PatchInterconnectAttachmentRequest", - "GetInterconnectLocationRequest", "ListInterconnectLocationsRequest", - "DeleteInterconnectRequest", - "GetInterconnectRequest", - "GetDiagnosticsInterconnectRequest", - "InsertInterconnectRequest", "ListInterconnectsRequest", - "PatchInterconnectRequest", - "GetLicenseCodeRequest", - "TestIamPermissionsLicenseCodeRequest", - "DeleteLicenseRequest", - "GetLicenseRequest", - "GetIamPolicyLicenseRequest", - "InsertLicenseRequest", "ListLicensesRequest", - "SetIamPolicyLicenseRequest", - "TestIamPermissionsLicenseRequest", - "AggregatedListMachineTypesRequest", - "GetMachineTypeRequest", "ListMachineTypesRequest", - "AggregatedListNetworkEndpointGroupsRequest", - "AttachNetworkEndpointsNetworkEndpointGroupRequest", - "DeleteNetworkEndpointGroupRequest", - "DetachNetworkEndpointsNetworkEndpointGroupRequest", - "GetNetworkEndpointGroupRequest", - "InsertNetworkEndpointGroupRequest", + "ListManagedInstancesInstanceGroupManagersRequest", + "ListManagedInstancesRegionInstanceGroupManagersRequest", "ListNetworkEndpointGroupsRequest", + "ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest", "ListNetworkEndpointsNetworkEndpointGroupsRequest", - "TestIamPermissionsNetworkEndpointGroupRequest", - "AddPeeringNetworkRequest", - "DeleteNetworkRequest", - "GetNetworkRequest", - "InsertNetworkRequest", "ListNetworksRequest", - "ListPeeringRoutesNetworksRequest", - "PatchNetworkRequest", - "RemovePeeringNetworkRequest", - "SwitchToCustomModeNetworkRequest", - "UpdatePeeringNetworkRequest", - "AddNodesNodeGroupRequest", - "AggregatedListNodeGroupsRequest", - "DeleteNodeGroupRequest", - "DeleteNodesNodeGroupRequest", - "GetNodeGroupRequest", - "GetIamPolicyNodeGroupRequest", - "InsertNodeGroupRequest", "ListNodeGroupsRequest", "ListNodesNodeGroupsRequest", - "PatchNodeGroupRequest", - "SetIamPolicyNodeGroupRequest", - "SetNodeTemplateNodeGroupRequest", - "TestIamPermissionsNodeGroupRequest", - "AggregatedListNodeTemplatesRequest", - "DeleteNodeTemplateRequest", - "GetNodeTemplateRequest", - "GetIamPolicyNodeTemplateRequest", - "InsertNodeTemplateRequest", "ListNodeTemplatesRequest", - "SetIamPolicyNodeTemplateRequest", - "TestIamPermissionsNodeTemplateRequest", - "AggregatedListNodeTypesRequest", - "GetNodeTypeRequest", "ListNodeTypesRequest", - "AggregatedListPacketMirroringsRequest", - "DeletePacketMirroringRequest", - "GetPacketMirroringRequest", - "InsertPacketMirroringRequest", "ListPacketMirroringsRequest", - "PatchPacketMirroringRequest", - "TestIamPermissionsPacketMirroringRequest", - "DisableXpnHostProjectRequest", - "DisableXpnResourceProjectRequest", - "EnableXpnHostProjectRequest", - "EnableXpnResourceProjectRequest", - "GetProjectRequest", - "GetXpnHostProjectRequest", - "GetXpnResourcesProjectsRequest", + "ListPeeringRoutesNetworksRequest", + "ListPerInstanceConfigsInstanceGroupManagersRequest", + "ListPerInstanceConfigsRegionInstanceGroupManagersRequest", + "ListPreconfiguredExpressionSetsSecurityPoliciesRequest", + "ListReferrersInstancesRequest", + "ListRegionAutoscalersRequest", + "ListRegionBackendServicesRequest", + "ListRegionCommitmentsRequest", + "ListRegionDisksRequest", + "ListRegionDiskTypesRequest", + "ListRegionHealthCheckServicesRequest", + "ListRegionHealthChecksRequest", + "ListRegionInstanceGroupManagersRequest", + "ListRegionInstanceGroupsRequest", + "ListRegionNetworkEndpointGroupsRequest", + "ListRegionNotificationEndpointsRequest", + "ListRegionOperationsRequest", + "ListRegionsRequest", + "ListRegionSslCertificatesRequest", + "ListRegionTargetHttpProxiesRequest", + "ListRegionTargetHttpsProxiesRequest", + "ListRegionUrlMapsRequest", + "ListReservationsRequest", + "ListResourcePoliciesRequest", + "ListRoutersRequest", + "ListRoutesRequest", + "ListSecurityPoliciesRequest", + "ListSnapshotsRequest", + "ListSslCertificatesRequest", + "ListSslPoliciesRequest", + "ListSubnetworksRequest", + "ListTargetGrpcProxiesRequest", + "ListTargetHttpProxiesRequest", + "ListTargetHttpsProxiesRequest", + "ListTargetInstancesRequest", + "ListTargetPoolsRequest", + "ListTargetSslProxiesRequest", + "ListTargetTcpProxiesRequest", + "ListTargetVpnGatewaysRequest", + "ListUrlMapsRequest", + "ListUsableSubnetworksRequest", + "ListVpnGatewaysRequest", + "ListVpnTunnelsRequest", "ListXpnHostsProjectsRequest", + "ListZoneOperationsRequest", + "ListZonesRequest", + "LocalDisk", + "LogConfig", + "LogConfigCloudAuditOptions", + "LogConfigCounterOptions", + "LogConfigCounterOptionsCustomField", + "LogConfigDataAccessOptions", + "MachineType", + "MachineTypeAggregatedList", + "MachineTypeList", + "MachineTypesScopedList", + "ManagedInstance", + "ManagedInstanceInstanceHealth", + "ManagedInstanceLastAttempt", + "ManagedInstanceVersion", + "Metadata", + "MetadataFilter", + "MetadataFilterLabelMatch", "MoveDiskProjectRequest", "MoveInstanceProjectRequest", - "SetCommonInstanceMetadataProjectRequest", - "SetDefaultNetworkTierProjectRequest", - "SetUsageExportBucketProjectRequest", - "DeleteRegionAutoscalerRequest", - "GetRegionAutoscalerRequest", - "InsertRegionAutoscalerRequest", - "ListRegionAutoscalersRequest", + "NamedPort", + "Network", + "NetworkEndpoint", + "NetworkEndpointGroup", + "NetworkEndpointGroupAggregatedList", + "NetworkEndpointGroupAppEngine", + "NetworkEndpointGroupCloudFunction", + "NetworkEndpointGroupCloudRun", + "NetworkEndpointGroupList", + "NetworkEndpointGroupsAttachEndpointsRequest", + "NetworkEndpointGroupsDetachEndpointsRequest", + "NetworkEndpointGroupsListEndpointsRequest", + "NetworkEndpointGroupsListNetworkEndpoints", + "NetworkEndpointGroupsScopedList", + "NetworkEndpointWithHealthStatus", + "NetworkInterface", + "NetworkList", + "NetworkPeering", + "NetworkRoutingConfig", + "NetworksAddPeeringRequest", + "NetworksRemovePeeringRequest", + "NetworksUpdatePeeringRequest", + "NodeGroup", + "NodeGroupAggregatedList", + "NodeGroupAutoscalingPolicy", + "NodeGroupList", + "NodeGroupMaintenanceWindow", + "NodeGroupNode", + "NodeGroupsAddNodesRequest", + "NodeGroupsDeleteNodesRequest", + "NodeGroupsListNodes", + "NodeGroupsScopedList", + "NodeGroupsSetNodeTemplateRequest", + "NodeTemplate", + "NodeTemplateAggregatedList", + "NodeTemplateList", + "NodeTemplateNodeTypeFlexibility", + "NodeTemplatesScopedList", + "NodeType", + "NodeTypeAggregatedList", + "NodeTypeList", + "NodeTypesScopedList", + "NotificationEndpoint", + "NotificationEndpointGrpcSettings", + "NotificationEndpointList", + "Operation", + "OperationAggregatedList", + "OperationList", + "OperationsScopedList", + "OutlierDetection", + "PacketMirroring", + "PacketMirroringAggregatedList", + "PacketMirroringFilter", + "PacketMirroringForwardingRuleInfo", + "PacketMirroringList", + "PacketMirroringMirroredResourceInfo", + "PacketMirroringMirroredResourceInfoInstanceInfo", + "PacketMirroringMirroredResourceInfoSubnetInfo", + "PacketMirroringNetworkInfo", + "PacketMirroringsScopedList", + "PatchAutoscalerRequest", + "PatchBackendBucketRequest", + "PatchBackendServiceRequest", + "PatchFirewallRequest", + "PatchForwardingRuleRequest", + "PatchGlobalForwardingRuleRequest", + "PatchHealthCheckRequest", + "PatchImageRequest", + "PatchInstanceGroupManagerRequest", + "PatchInterconnectAttachmentRequest", + "PatchInterconnectRequest", + "PatchNetworkRequest", + "PatchNodeGroupRequest", + "PatchPacketMirroringRequest", + "PatchPerInstanceConfigsInstanceGroupManagerRequest", + "PatchPerInstanceConfigsRegionInstanceGroupManagerRequest", "PatchRegionAutoscalerRequest", - "UpdateRegionAutoscalerRequest", - "DeleteRegionBackendServiceRequest", - "GetRegionBackendServiceRequest", - "GetHealthRegionBackendServiceRequest", - "InsertRegionBackendServiceRequest", - "ListRegionBackendServicesRequest", "PatchRegionBackendServiceRequest", - "UpdateRegionBackendServiceRequest", - "AggregatedListRegionCommitmentsRequest", - "GetRegionCommitmentRequest", - "InsertRegionCommitmentRequest", - "ListRegionCommitmentsRequest", - "GetRegionDiskTypeRequest", - "ListRegionDiskTypesRequest", - "AddResourcePoliciesRegionDiskRequest", - "CreateSnapshotRegionDiskRequest", - "DeleteRegionDiskRequest", - "GetRegionDiskRequest", - "GetIamPolicyRegionDiskRequest", - "InsertRegionDiskRequest", - "ListRegionDisksRequest", + "PatchRegionHealthCheckRequest", + "PatchRegionHealthCheckServiceRequest", + "PatchRegionInstanceGroupManagerRequest", + "PatchRegionUrlMapRequest", + "PatchRouterRequest", + "PatchRuleSecurityPolicyRequest", + "PatchSecurityPolicyRequest", + "PatchSslPolicyRequest", + "PatchSubnetworkRequest", + "PatchTargetGrpcProxyRequest", + "PatchTargetHttpProxyRequest", + "PatchUrlMapRequest", + "PathMatcher", + "PathRule", + "PerInstanceConfig", + "Policy", + "PreconfiguredWafSet", + "PreservedState", + "PreservedStatePreservedDisk", + "PreviewRouterRequest", + "Project", + "ProjectsDisableXpnResourceRequest", + "ProjectsEnableXpnResourceRequest", + "ProjectsGetXpnResources", + "ProjectsListXpnHostsRequest", + "ProjectsSetDefaultNetworkTierRequest", + "Quota", + "RawDisk", + "RecreateInstancesInstanceGroupManagerRequest", + "RecreateInstancesRegionInstanceGroupManagerRequest", + "Reference", + "Region", + "RegionAutoscalerList", + "RegionDisksAddResourcePoliciesRequest", + "RegionDisksRemoveResourcePoliciesRequest", + "RegionDisksResizeRequest", + "RegionDiskTypeList", + "RegionInstanceGroupList", + "RegionInstanceGroupManagerDeleteInstanceConfigReq", + "RegionInstanceGroupManagerList", + "RegionInstanceGroupManagerPatchInstanceConfigReq", + "RegionInstanceGroupManagersAbandonInstancesRequest", + "RegionInstanceGroupManagersApplyUpdatesRequest", + "RegionInstanceGroupManagersCreateInstancesRequest", + "RegionInstanceGroupManagersDeleteInstancesRequest", + "RegionInstanceGroupManagersListErrorsResponse", + "RegionInstanceGroupManagersListInstanceConfigsResp", + "RegionInstanceGroupManagersListInstancesResponse", + "RegionInstanceGroupManagersRecreateRequest", + "RegionInstanceGroupManagersSetTargetPoolsRequest", + "RegionInstanceGroupManagersSetTemplateRequest", + "RegionInstanceGroupManagerUpdateInstanceConfigReq", + "RegionInstanceGroupsListInstances", + "RegionInstanceGroupsListInstancesRequest", + "RegionInstanceGroupsSetNamedPortsRequest", + "RegionList", + "RegionSetLabelsRequest", + "RegionSetPolicyRequest", + "RegionTargetHttpsProxiesSetSslCertificatesRequest", + "RegionUrlMapsValidateRequest", + "RemoveHealthCheckTargetPoolRequest", + "RemoveInstancesInstanceGroupRequest", + "RemoveInstanceTargetPoolRequest", + "RemovePeeringNetworkRequest", + "RemoveResourcePoliciesDiskRequest", + "RemoveResourcePoliciesInstanceRequest", "RemoveResourcePoliciesRegionDiskRequest", + "RemoveRuleSecurityPolicyRequest", + "RequestMirrorPolicy", + "Reservation", + "ReservationAffinity", + "ReservationAggregatedList", + "ReservationList", + "ReservationsResizeRequest", + "ReservationsScopedList", + "ResetInstanceRequest", + "ResizeDiskRequest", + "ResizeInstanceGroupManagerRequest", "ResizeRegionDiskRequest", - "SetIamPolicyRegionDiskRequest", - "SetLabelsRegionDiskRequest", - "TestIamPermissionsRegionDiskRequest", - "DeleteRegionHealthCheckServiceRequest", - "GetRegionHealthCheckServiceRequest", - "InsertRegionHealthCheckServiceRequest", - "ListRegionHealthCheckServicesRequest", - "PatchRegionHealthCheckServiceRequest", - "DeleteRegionHealthCheckRequest", - "GetRegionHealthCheckRequest", - "InsertRegionHealthCheckRequest", - "ListRegionHealthChecksRequest", - "PatchRegionHealthCheckRequest", - "UpdateRegionHealthCheckRequest", - "AbandonInstancesRegionInstanceGroupManagerRequest", - "ApplyUpdatesToInstancesRegionInstanceGroupManagerRequest", - "CreateInstancesRegionInstanceGroupManagerRequest", - "DeleteRegionInstanceGroupManagerRequest", - "DeleteInstancesRegionInstanceGroupManagerRequest", - "DeletePerInstanceConfigsRegionInstanceGroupManagerRequest", - "GetRegionInstanceGroupManagerRequest", - "InsertRegionInstanceGroupManagerRequest", - "ListRegionInstanceGroupManagersRequest", - "ListErrorsRegionInstanceGroupManagersRequest", - "ListManagedInstancesRegionInstanceGroupManagersRequest", - "ListPerInstanceConfigsRegionInstanceGroupManagersRequest", - "PatchRegionInstanceGroupManagerRequest", - "PatchPerInstanceConfigsRegionInstanceGroupManagerRequest", - "RecreateInstancesRegionInstanceGroupManagerRequest", "ResizeRegionInstanceGroupManagerRequest", - "SetInstanceTemplateRegionInstanceGroupManagerRequest", - "SetTargetPoolsRegionInstanceGroupManagerRequest", - "UpdatePerInstanceConfigsRegionInstanceGroupManagerRequest", - "GetRegionInstanceGroupRequest", - "ListRegionInstanceGroupsRequest", - "ListInstancesRegionInstanceGroupsRequest", - "SetNamedPortsRegionInstanceGroupRequest", - "DeleteRegionNetworkEndpointGroupRequest", - "GetRegionNetworkEndpointGroupRequest", - "InsertRegionNetworkEndpointGroupRequest", - "ListRegionNetworkEndpointGroupsRequest", - "DeleteRegionNotificationEndpointRequest", - "GetRegionNotificationEndpointRequest", - "InsertRegionNotificationEndpointRequest", - "ListRegionNotificationEndpointsRequest", - "DeleteRegionOperationRequest", - "DeleteRegionOperationResponse", - "GetRegionOperationRequest", - "ListRegionOperationsRequest", - "WaitRegionOperationRequest", - "DeleteRegionSslCertificateRequest", - "GetRegionSslCertificateRequest", - "InsertRegionSslCertificateRequest", - "ListRegionSslCertificatesRequest", - "DeleteRegionTargetHttpProxyRequest", - "GetRegionTargetHttpProxyRequest", - "InsertRegionTargetHttpProxyRequest", - "ListRegionTargetHttpProxiesRequest", - "SetUrlMapRegionTargetHttpProxyRequest", - "DeleteRegionTargetHttpsProxyRequest", - "GetRegionTargetHttpsProxyRequest", - "InsertRegionTargetHttpsProxyRequest", - "ListRegionTargetHttpsProxiesRequest", - "SetSslCertificatesRegionTargetHttpsProxyRequest", - "SetUrlMapRegionTargetHttpsProxyRequest", - "DeleteRegionUrlMapRequest", - "GetRegionUrlMapRequest", - "InsertRegionUrlMapRequest", - "ListRegionUrlMapsRequest", - "PatchRegionUrlMapRequest", - "UpdateRegionUrlMapRequest", - "ValidateRegionUrlMapRequest", - "GetRegionRequest", - "ListRegionsRequest", - "AggregatedListReservationsRequest", - "DeleteReservationRequest", - "GetReservationRequest", - "GetIamPolicyReservationRequest", - "InsertReservationRequest", - "ListReservationsRequest", "ResizeReservationRequest", + "ResourceCommitment", + "ResourceGroupReference", + "ResourcePoliciesScopedList", + "ResourcePolicy", + "ResourcePolicyAggregatedList", + "ResourcePolicyDailyCycle", + "ResourcePolicyGroupPlacementPolicy", + "ResourcePolicyHourlyCycle", + "ResourcePolicyList", + "ResourcePolicySnapshotSchedulePolicy", + "ResourcePolicySnapshotSchedulePolicyRetentionPolicy", + "ResourcePolicySnapshotSchedulePolicySchedule", + "ResourcePolicySnapshotSchedulePolicySnapshotProperties", + "ResourcePolicyWeeklyCycle", + "ResourcePolicyWeeklyCycleDayOfWeek", + "Route", + "RouteList", + "Router", + "RouterAdvertisedIpRange", + "RouterAggregatedList", + "RouterBgp", + "RouterBgpPeer", + "RouterInterface", + "RouterList", + "RouterNat", + "RouterNatLogConfig", + "RouterNatSubnetworkToNat", + "RoutersPreviewResponse", + "RoutersScopedList", + "RouterStatus", + "RouterStatusBgpPeerStatus", + "RouterStatusNatStatus", + "RouterStatusResponse", + "Rule", + "Scheduling", + "SchedulingNodeAffinity", + "ScratchDisks", + "Screenshot", + "SecurityPoliciesListPreconfiguredExpressionSetsResponse", + "SecurityPoliciesWafConfig", + "SecurityPolicy", + "SecurityPolicyList", + "SecurityPolicyReference", + "SecurityPolicyRule", + "SecurityPolicyRuleMatcher", + "SecurityPolicyRuleMatcherConfig", + "SecuritySettings", + "SerialPortOutput", + "ServerBinding", + "ServiceAccount", + "SetBackendServiceTargetSslProxyRequest", + "SetBackendServiceTargetTcpProxyRequest", + "SetBackupTargetPoolRequest", + "SetCommonInstanceMetadataProjectRequest", + "SetDefaultNetworkTierProjectRequest", + "SetDeletionProtectionInstanceRequest", + "SetDiskAutoDeleteInstanceRequest", + "SetIamPolicyDiskRequest", + "SetIamPolicyImageRequest", + "SetIamPolicyInstanceRequest", + "SetIamPolicyInstanceTemplateRequest", + "SetIamPolicyLicenseRequest", + "SetIamPolicyNodeGroupRequest", + "SetIamPolicyNodeTemplateRequest", + "SetIamPolicyRegionDiskRequest", "SetIamPolicyReservationRequest", - "TestIamPermissionsReservationRequest", - "AggregatedListResourcePoliciesRequest", - "DeleteResourcePolicyRequest", - "GetResourcePolicyRequest", - "GetIamPolicyResourcePolicyRequest", - "InsertResourcePolicyRequest", - "ListResourcePoliciesRequest", "SetIamPolicyResourcePolicyRequest", - "TestIamPermissionsResourcePolicyRequest", - "AggregatedListRoutersRequest", - "DeleteRouterRequest", - "GetRouterRequest", - "GetNatMappingInfoRoutersRequest", - "GetRouterStatusRouterRequest", - "InsertRouterRequest", - "ListRoutersRequest", - "PatchRouterRequest", - "PreviewRouterRequest", - "UpdateRouterRequest", - "DeleteRouteRequest", - "GetRouteRequest", - "InsertRouteRequest", - "ListRoutesRequest", - "AddRuleSecurityPolicyRequest", - "DeleteSecurityPolicyRequest", - "GetSecurityPolicyRequest", - "GetRuleSecurityPolicyRequest", - "InsertSecurityPolicyRequest", - "ListSecurityPoliciesRequest", - "ListPreconfiguredExpressionSetsSecurityPoliciesRequest", - "PatchSecurityPolicyRequest", - "PatchRuleSecurityPolicyRequest", - "RemoveRuleSecurityPolicyRequest", - "DeleteSnapshotRequest", - "GetSnapshotRequest", - "GetIamPolicySnapshotRequest", - "ListSnapshotsRequest", "SetIamPolicySnapshotRequest", - "SetLabelsSnapshotRequest", - "TestIamPermissionsSnapshotRequest", - "AggregatedListSslCertificatesRequest", - "DeleteSslCertificateRequest", - "GetSslCertificateRequest", - "InsertSslCertificateRequest", - "ListSslCertificatesRequest", - "DeleteSslPolicyRequest", - "GetSslPolicyRequest", - "InsertSslPolicyRequest", - "ListSslPoliciesRequest", - "ListAvailableFeaturesSslPoliciesRequest", - "PatchSslPolicyRequest", - "AggregatedListSubnetworksRequest", - "DeleteSubnetworkRequest", - "ExpandIpCidrRangeSubnetworkRequest", - "GetSubnetworkRequest", - "GetIamPolicySubnetworkRequest", - "InsertSubnetworkRequest", - "ListSubnetworksRequest", - "ListUsableSubnetworksRequest", - "PatchSubnetworkRequest", "SetIamPolicySubnetworkRequest", + "SetInstanceTemplateInstanceGroupManagerRequest", + "SetInstanceTemplateRegionInstanceGroupManagerRequest", + "SetLabelsDiskRequest", + "SetLabelsExternalVpnGatewayRequest", + "SetLabelsImageRequest", + "SetLabelsInstanceRequest", + "SetLabelsRegionDiskRequest", + "SetLabelsSnapshotRequest", + "SetLabelsVpnGatewayRequest", + "SetMachineResourcesInstanceRequest", + "SetMachineTypeInstanceRequest", + "SetMetadataInstanceRequest", + "SetMinCpuPlatformInstanceRequest", + "SetNamedPortsInstanceGroupRequest", + "SetNamedPortsRegionInstanceGroupRequest", + "SetNodeTemplateNodeGroupRequest", "SetPrivateIpGoogleAccessSubnetworkRequest", - "TestIamPermissionsSubnetworkRequest", - "DeleteTargetGrpcProxyRequest", - "GetTargetGrpcProxyRequest", - "InsertTargetGrpcProxyRequest", - "ListTargetGrpcProxiesRequest", - "PatchTargetGrpcProxyRequest", - "AggregatedListTargetHttpProxiesRequest", - "DeleteTargetHttpProxyRequest", - "GetTargetHttpProxyRequest", - "InsertTargetHttpProxyRequest", - "ListTargetHttpProxiesRequest", - "PatchTargetHttpProxyRequest", - "SetUrlMapTargetHttpProxyRequest", - "AggregatedListTargetHttpsProxiesRequest", - "DeleteTargetHttpsProxyRequest", - "GetTargetHttpsProxyRequest", - "InsertTargetHttpsProxyRequest", - "ListTargetHttpsProxiesRequest", + "SetProxyHeaderTargetSslProxyRequest", + "SetProxyHeaderTargetTcpProxyRequest", "SetQuicOverrideTargetHttpsProxyRequest", + "SetSchedulingInstanceRequest", + "SetSecurityPolicyBackendServiceRequest", + "SetServiceAccountInstanceRequest", + "SetShieldedInstanceIntegrityPolicyInstanceRequest", + "SetSslCertificatesRegionTargetHttpsProxyRequest", "SetSslCertificatesTargetHttpsProxyRequest", - "SetSslPolicyTargetHttpsProxyRequest", - "SetUrlMapTargetHttpsProxyRequest", - "AggregatedListTargetInstancesRequest", - "DeleteTargetInstanceRequest", - "GetTargetInstanceRequest", - "InsertTargetInstanceRequest", - "ListTargetInstancesRequest", - "AddHealthCheckTargetPoolRequest", - "AddInstanceTargetPoolRequest", - "AggregatedListTargetPoolsRequest", - "DeleteTargetPoolRequest", - "GetTargetPoolRequest", - "GetHealthTargetPoolRequest", - "InsertTargetPoolRequest", - "ListTargetPoolsRequest", - "RemoveHealthCheckTargetPoolRequest", - "RemoveInstanceTargetPoolRequest", - "SetBackupTargetPoolRequest", - "DeleteTargetSslProxyRequest", - "GetTargetSslProxyRequest", - "InsertTargetSslProxyRequest", - "ListTargetSslProxiesRequest", - "SetBackendServiceTargetSslProxyRequest", - "SetProxyHeaderTargetSslProxyRequest", "SetSslCertificatesTargetSslProxyRequest", + "SetSslPolicyTargetHttpsProxyRequest", "SetSslPolicyTargetSslProxyRequest", - "DeleteTargetTcpProxyRequest", - "GetTargetTcpProxyRequest", - "InsertTargetTcpProxyRequest", - "ListTargetTcpProxiesRequest", - "SetBackendServiceTargetTcpProxyRequest", - "SetProxyHeaderTargetTcpProxyRequest", - "AggregatedListTargetVpnGatewaysRequest", - "DeleteTargetVpnGatewayRequest", - "GetTargetVpnGatewayRequest", - "InsertTargetVpnGatewayRequest", - "ListTargetVpnGatewaysRequest", - "AggregatedListUrlMapsRequest", - "DeleteUrlMapRequest", - "GetUrlMapRequest", - "InsertUrlMapRequest", - "InvalidateCacheUrlMapRequest", - "ListUrlMapsRequest", - "PatchUrlMapRequest", + "SetTagsInstanceRequest", + "SetTargetForwardingRuleRequest", + "SetTargetGlobalForwardingRuleRequest", + "SetTargetPoolsInstanceGroupManagerRequest", + "SetTargetPoolsRegionInstanceGroupManagerRequest", + "SetUrlMapRegionTargetHttpProxyRequest", + "SetUrlMapRegionTargetHttpsProxyRequest", + "SetUrlMapTargetHttpProxyRequest", + "SetUrlMapTargetHttpsProxyRequest", + "SetUsageExportBucketProjectRequest", + "ShieldedInstanceConfig", + "ShieldedInstanceIdentity", + "ShieldedInstanceIdentityEntry", + "ShieldedInstanceIntegrityPolicy", + "SignedUrlKey", + "SimulateMaintenanceEventInstanceRequest", + "Snapshot", + "SnapshotList", + "SourceInstanceParams", + "SslCertificate", + "SslCertificateAggregatedList", + "SslCertificateList", + "SslCertificateManagedSslCertificate", + "SslCertificateSelfManagedSslCertificate", + "SslCertificatesScopedList", + "SSLHealthCheck", + "SslPoliciesList", + "SslPoliciesListAvailableFeaturesResponse", + "SslPolicy", + "SslPolicyReference", + "StartInstanceRequest", + "StartWithEncryptionKeyInstanceRequest", + "StatefulPolicy", + "StatefulPolicyPreservedState", + "StatefulPolicyPreservedStateDiskDevice", + "StopInstanceRequest", + "Subnetwork", + "SubnetworkAggregatedList", + "SubnetworkList", + "SubnetworkLogConfig", + "SubnetworkSecondaryRange", + "SubnetworksExpandIpCidrRangeRequest", + "SubnetworksScopedList", + "SubnetworksSetPrivateIpGoogleAccessRequest", + "SwitchToCustomModeNetworkRequest", + "Tags", + "TargetGrpcProxy", + "TargetGrpcProxyList", + "TargetHttpProxiesScopedList", + "TargetHttpProxy", + "TargetHttpProxyAggregatedList", + "TargetHttpProxyList", + "TargetHttpsProxiesScopedList", + "TargetHttpsProxiesSetQuicOverrideRequest", + "TargetHttpsProxiesSetSslCertificatesRequest", + "TargetHttpsProxy", + "TargetHttpsProxyAggregatedList", + "TargetHttpsProxyList", + "TargetInstance", + "TargetInstanceAggregatedList", + "TargetInstanceList", + "TargetInstancesScopedList", + "TargetPool", + "TargetPoolAggregatedList", + "TargetPoolInstanceHealth", + "TargetPoolList", + "TargetPoolsAddHealthCheckRequest", + "TargetPoolsAddInstanceRequest", + "TargetPoolsRemoveHealthCheckRequest", + "TargetPoolsRemoveInstanceRequest", + "TargetPoolsScopedList", + "TargetReference", + "TargetSslProxiesSetBackendServiceRequest", + "TargetSslProxiesSetProxyHeaderRequest", + "TargetSslProxiesSetSslCertificatesRequest", + "TargetSslProxy", + "TargetSslProxyList", + "TargetTcpProxiesSetBackendServiceRequest", + "TargetTcpProxiesSetProxyHeaderRequest", + "TargetTcpProxy", + "TargetTcpProxyList", + "TargetVpnGateway", + "TargetVpnGatewayAggregatedList", + "TargetVpnGatewayList", + "TargetVpnGatewaysScopedList", + "TCPHealthCheck", + "TestFailure", + "TestIamPermissionsDiskRequest", + "TestIamPermissionsExternalVpnGatewayRequest", + "TestIamPermissionsImageRequest", + "TestIamPermissionsInstanceRequest", + "TestIamPermissionsInstanceTemplateRequest", + "TestIamPermissionsLicenseCodeRequest", + "TestIamPermissionsLicenseRequest", + "TestIamPermissionsNetworkEndpointGroupRequest", + "TestIamPermissionsNodeGroupRequest", + "TestIamPermissionsNodeTemplateRequest", + "TestIamPermissionsPacketMirroringRequest", + "TestIamPermissionsRegionDiskRequest", + "TestIamPermissionsReservationRequest", + "TestIamPermissionsResourcePolicyRequest", + "TestIamPermissionsSnapshotRequest", + "TestIamPermissionsSubnetworkRequest", + "TestIamPermissionsVpnGatewayRequest", + "TestPermissionsRequest", + "TestPermissionsResponse", + "UpdateAccessConfigInstanceRequest", + "UpdateAutoscalerRequest", + "UpdateBackendBucketRequest", + "UpdateBackendServiceRequest", + "UpdateDisplayDeviceInstanceRequest", + "UpdateFirewallRequest", + "UpdateHealthCheckRequest", + "UpdateInstanceRequest", + "UpdateNetworkInterfaceInstanceRequest", + "UpdatePeeringNetworkRequest", + "UpdatePerInstanceConfigsInstanceGroupManagerRequest", + "UpdatePerInstanceConfigsRegionInstanceGroupManagerRequest", + "UpdateRegionAutoscalerRequest", + "UpdateRegionBackendServiceRequest", + "UpdateRegionHealthCheckRequest", + "UpdateRegionUrlMapRequest", + "UpdateRouterRequest", + "UpdateShieldedInstanceConfigInstanceRequest", "UpdateUrlMapRequest", + "UrlMap", + "UrlMapList", + "UrlMapReference", + "UrlMapsAggregatedList", + "UrlMapsScopedList", + "UrlMapsValidateRequest", + "UrlMapsValidateResponse", + "UrlMapTest", + "UrlMapValidationResult", + "UrlRewrite", + "UsableSubnetwork", + "UsableSubnetworksAggregatedList", + "UsableSubnetworkSecondaryRange", + "UsageExportLocation", + "ValidateRegionUrlMapRequest", "ValidateUrlMapRequest", - "AggregatedListVpnGatewaysRequest", - "DeleteVpnGatewayRequest", - "GetVpnGatewayRequest", - "GetStatusVpnGatewayRequest", - "InsertVpnGatewayRequest", - "ListVpnGatewaysRequest", - "SetLabelsVpnGatewayRequest", - "TestIamPermissionsVpnGatewayRequest", - "AggregatedListVpnTunnelsRequest", - "DeleteVpnTunnelRequest", - "GetVpnTunnelRequest", - "InsertVpnTunnelRequest", - "ListVpnTunnelsRequest", - "DeleteZoneOperationRequest", - "DeleteZoneOperationResponse", - "GetZoneOperationRequest", - "ListZoneOperationsRequest", + "VmEndpointNatMappings", + "VmEndpointNatMappingsInterfaceNatMappings", + "VmEndpointNatMappingsList", + "VpnGateway", + "VpnGatewayAggregatedList", + "VpnGatewayList", + "VpnGatewaysGetStatusResponse", + "VpnGatewaysScopedList", + "VpnGatewayStatus", + "VpnGatewayStatusHighAvailabilityRequirementState", + "VpnGatewayStatusTunnel", + "VpnGatewayStatusVpnConnection", + "VpnGatewayVpnGatewayInterface", + "VpnTunnel", + "VpnTunnelAggregatedList", + "VpnTunnelList", + "VpnTunnelsScopedList", + "WafExpressionSet", + "WafExpressionSetExpression", + "WaitGlobalOperationRequest", + "WaitRegionOperationRequest", "WaitZoneOperationRequest", - "GetZoneRequest", - "ListZonesRequest", + "Warning", + "Warnings", + "WeightedBackendService", + "XpnHostList", + "XpnResourceId", + "Zone", + "ZoneList", + "ZoneSetLabelsRequest", + "ZoneSetPolicyRequest", ) diff --git a/google/cloud/compute_v1/types/compute.py b/google/cloud/compute_v1/types/compute.py index 76de97ebc..28acaec38 100644 --- a/google/cloud/compute_v1/types/compute.py +++ b/google/cloud/compute_v1/types/compute.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -1097,14 +1095,12 @@ class AcceleratorConfig(proto.Message): Engine for a full list of accelerator types. """ - accelerator_count = proto.Field(proto.INT32, number=236444219) - - accelerator_type = proto.Field(proto.STRING, number=138031246) + accelerator_count = proto.Field(proto.INT32, number=504879675, optional=True,) + accelerator_type = proto.Field(proto.STRING, number=138031246, optional=True,) class DeprecationStatus(proto.Message): r"""Deprecation status for a public resource. - Attributes: deleted (str): An optional RFC3339 timestamp on or after @@ -1153,20 +1149,16 @@ class State(proto.Enum): result in an error. """ UNDEFINED_STATE = 0 - ACTIVE = 46297862 + ACTIVE = 314733318 DELETED = 120962041 - DEPRECATED = 194924979 + DEPRECATED = 463360435 OBSOLETE = 66532761 - deleted = proto.Field(proto.STRING, number=208285721) - - deprecated = proto.Field(proto.STRING, number=246703539) - - obsolete = proto.Field(proto.STRING, number=89212313) - - replacement = proto.Field(proto.STRING, number=162483730) - - state = proto.Field(proto.ENUM, number=109757585, enum=State,) + deleted = proto.Field(proto.STRING, number=476721177, optional=True,) + deprecated = proto.Field(proto.STRING, number=515138995, optional=True,) + obsolete = proto.Field(proto.STRING, number=357647769, optional=True,) + replacement = proto.Field(proto.STRING, number=430919186, optional=True,) + state = proto.Field(proto.ENUM, number=109757585, optional=True, enum=State,) class AcceleratorType(proto.Message): @@ -1208,30 +1200,23 @@ class AcceleratorType(proto.Message): a field in the request body. """ - creation_timestamp = proto.Field(proto.STRING, number=30525366) - + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) deprecated = proto.Field( - proto.MESSAGE, number=246703539, message="DeprecationStatus", + proto.MESSAGE, number=515138995, optional=True, message="DeprecationStatus", ) - - description = proto.Field(proto.STRING, number=154502140) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - maximum_cards_per_instance = proto.Field(proto.INT32, number=263814482) - - name = proto.Field(proto.STRING, number=3373707) - - self_link = proto.Field(proto.STRING, number=187779341) - - zone = proto.Field(proto.STRING, number=3744684) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + id = proto.Field(proto.STRING, number=3355, optional=True,) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) + maximum_cards_per_instance = proto.Field( + proto.INT32, number=263814482, optional=True, + ) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + zone = proto.Field(proto.STRING, number=3744684, optional=True,) class AcceleratorTypesScopedList(proto.Message): r""" - Attributes: accelerator_types (Sequence[google.cloud.compute_v1.types.AcceleratorType]): [Output Only] A list of accelerator types contained in this @@ -1242,15 +1227,15 @@ class AcceleratorTypesScopedList(proto.Message): """ accelerator_types = proto.RepeatedField( - proto.MESSAGE, number=252436901, message="AcceleratorType", + proto.MESSAGE, number=520872357, message="AcceleratorType", + ) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", ) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) class Data(proto.Message): r""" - Attributes: key (str): [Output Only] A key that provides more detail on the warning @@ -1266,14 +1251,12 @@ class Data(proto.Message): [Output Only] A warning data value corresponding to the key. """ - key = proto.Field(proto.STRING, number=106079) - - value = proto.Field(proto.STRING, number=111972721) + key = proto.Field(proto.STRING, number=106079, optional=True,) + value = proto.Field(proto.STRING, number=111972721, optional=True,) class Warning(proto.Message): r"""[Output Only] Informational warning message. - Attributes: code (google.cloud.compute_v1.types.Warning.Code): [Output Only] A warning code, if applicable. For example, @@ -1295,41 +1278,38 @@ class Code(proto.Enum): """ UNDEFINED_CODE = 0 CLEANUP_FAILED = 150308440 - DEPRECATED_RESOURCE_USED = 123400130 - DEPRECATED_TYPE_USED = 78090774 - DISK_SIZE_LARGER_THAN_IMAGE_SIZE = 101007511 - EXPERIMENTAL_TYPE_USED = 183518987 + DEPRECATED_RESOURCE_USED = 391835586 + DEPRECATED_TYPE_USED = 346526230 + DISK_SIZE_LARGER_THAN_IMAGE_SIZE = 369442967 + EXPERIMENTAL_TYPE_USED = 451954443 EXTERNAL_API_WARNING = 175546307 - FIELD_VALUE_OVERRIDEN = 61233967 - INJECTED_KERNELS_DEPRECATED = 148941963 - LARGE_DEPLOYMENT_WARNING = 213005222 - MISSING_TYPE_DEPENDENCY = 76070007 - NEXT_HOP_ADDRESS_NOT_ASSIGNED = 56529543 - NEXT_HOP_CANNOT_IP_FORWARD = 114947431 - NEXT_HOP_INSTANCE_NOT_FOUND = 195814990 + FIELD_VALUE_OVERRIDEN = 329669423 + INJECTED_KERNELS_DEPRECATED = 417377419 + LARGE_DEPLOYMENT_WARNING = 481440678 + MISSING_TYPE_DEPENDENCY = 344505463 + NEXT_HOP_ADDRESS_NOT_ASSIGNED = 324964999 + NEXT_HOP_CANNOT_IP_FORWARD = 383382887 + NEXT_HOP_INSTANCE_NOT_FOUND = 464250446 NEXT_HOP_INSTANCE_NOT_ON_NETWORK = 243758146 - NEXT_HOP_NOT_RUNNING = 148645809 + NEXT_HOP_NOT_RUNNING = 417081265 NOT_CRITICAL_ERROR = 105763924 NO_RESULTS_ON_PAGE = 30036744 PARTIAL_SUCCESS = 39966469 REQUIRED_TOS_AGREEMENT = 3745539 - RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING = 228293185 + RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING = 496728641 RESOURCE_NOT_DELETED = 168598460 - SCHEMA_VALIDATION_IGNORED = 6810186 + SCHEMA_VALIDATION_IGNORED = 275245642 SINGLE_INSTANCE_PROPERTY_TEMPLATE = 268305617 - UNDECLARED_PROPERTIES = 122077983 + UNDECLARED_PROPERTIES = 390513439 UNREACHABLE = 13328052 - code = proto.Field(proto.ENUM, number=3059181, enum=Code,) - + code = proto.Field(proto.ENUM, number=3059181, optional=True, enum=Code,) data = proto.RepeatedField(proto.MESSAGE, number=3076010, message="Data",) - - message = proto.Field(proto.STRING, number=149618695) + message = proto.Field(proto.STRING, number=418054151, optional=True,) class AcceleratorTypeAggregatedList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -1360,29 +1340,24 @@ class AcceleratorTypeAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="AcceleratorTypesScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 AcceleratorTypeList(proto.Message): r"""Contains a list of accelerator types. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -1409,19 +1384,16 @@ class AcceleratorTypeList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="AcceleratorType", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 AccessConfig(proto.Message): @@ -1480,8 +1452,8 @@ class NetworkTier(proto.Enum): the Address resource owning that IP. """ UNDEFINED_NETWORK_TIER = 0 - PREMIUM = 131095095 - STANDARD = 216207037 + PREMIUM = 399530551 + STANDARD = 484642493 class Type(proto.Enum): r"""The type of configuration. The default and only option is @@ -1490,19 +1462,15 @@ class Type(proto.Enum): UNDEFINED_TYPE = 0 ONE_TO_ONE_NAT = 84090205 - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - - nat_i_p = proto.Field(proto.STRING, number=117634556) - - network_tier = proto.Field(proto.ENUM, number=248962387, enum=NetworkTier,) - - public_ptr_domain_name = proto.Field(proto.STRING, number=48163711) - - set_public_ptr = proto.Field(proto.BOOL, number=255434773) - - type_ = proto.Field(proto.ENUM, number=3575610, enum=Type,) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + nat_i_p = proto.Field(proto.STRING, number=117634556, optional=True,) + network_tier = proto.Field( + proto.ENUM, number=517397843, optional=True, enum=NetworkTier, + ) + public_ptr_domain_name = proto.Field(proto.STRING, number=316599167, optional=True,) + set_public_ptr = proto.Field(proto.BOOL, number=523870229, optional=True,) + type_ = proto.Field(proto.ENUM, number=3575610, optional=True, enum=Type,) class Address(proto.Message): @@ -1631,7 +1599,7 @@ class AddressType(proto.Enum): """ UNDEFINED_ADDRESS_TYPE = 0 EXTERNAL = 35607499 - INTERNAL = 10860221 + INTERNAL = 279295677 UNSPECIFIED_TYPE = 53933922 class IpVersion(proto.Enum): @@ -1656,8 +1624,8 @@ class NetworkTier(proto.Enum): be PREMIUM. """ UNDEFINED_NETWORK_TIER = 0 - PREMIUM = 131095095 - STANDARD = 216207037 + PREMIUM = 399530551 + STANDARD = 484642493 class Purpose(proto.Enum): r"""The purpose of this resource, which can be one of the following @@ -1676,11 +1644,11 @@ class Purpose(proto.Enum): regional resources. """ UNDEFINED_PURPOSE = 0 - DNS_RESOLVER = 207679100 + DNS_RESOLVER = 476114556 GCE_ENDPOINT = 230515243 NAT_AUTO = 163666477 - SHARED_LOADBALANCER_VIP = 26012116 - VPC_PEERING = 132364714 + SHARED_LOADBALANCER_VIP = 294447572 + VPC_PEERING = 400800170 class Status(proto.Enum): r"""[Output Only] The status of the address, which can be one of @@ -1691,47 +1659,36 @@ class Status(proto.Enum): """ UNDEFINED_STATUS = 0 IN_USE = 17393485 - RESERVED = 163805992 - RESERVING = 246151769 - - address = proto.Field(proto.STRING, number=194485236) - - address_type = proto.Field(proto.ENUM, number=264307877, enum=AddressType,) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - id = proto.Field(proto.STRING, number=3355) - - ip_version = proto.Field(proto.ENUM, number=26524096, enum=IpVersion,) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - - network = proto.Field(proto.STRING, number=232872494) - - network_tier = proto.Field(proto.ENUM, number=248962387, enum=NetworkTier,) - - prefix_length = proto.Field(proto.INT32, number=185130291) - - purpose = proto.Field(proto.ENUM, number=47971614, enum=Purpose,) - - region = proto.Field(proto.STRING, number=138946292) - - self_link = proto.Field(proto.STRING, number=187779341) - - status = proto.Field(proto.ENUM, number=181260274, enum=Status,) - - subnetwork = proto.Field(proto.STRING, number=39392238) - - users = proto.RepeatedField(proto.STRING, number=111578632) + RESERVED = 432241448 + RESERVING = 514587225 + + address = proto.Field(proto.STRING, number=462920692, optional=True,) + address_type = proto.Field( + proto.ENUM, number=264307877, optional=True, enum=AddressType, + ) + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + id = proto.Field(proto.STRING, number=3355, optional=True,) + ip_version = proto.Field( + proto.ENUM, number=294959552, optional=True, enum=IpVersion, + ) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + network = proto.Field(proto.STRING, number=232872494, optional=True,) + network_tier = proto.Field( + proto.ENUM, number=517397843, optional=True, enum=NetworkTier, + ) + prefix_length = proto.Field(proto.INT32, number=453565747, optional=True,) + purpose = proto.Field(proto.ENUM, number=316407070, optional=True, enum=Purpose,) + 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,) + subnetwork = proto.Field(proto.STRING, number=307827694, optional=True,) + users = proto.RepeatedField(proto.STRING, number=111578632,) class AddressesScopedList(proto.Message): r""" - Attributes: addresses (Sequence[google.cloud.compute_v1.types.Address]): [Output Only] A list of addresses contained in this scope. @@ -1740,14 +1697,14 @@ class AddressesScopedList(proto.Message): of addresses when the list is empty. """ - addresses = proto.RepeatedField(proto.MESSAGE, number=69237666, message="Address",) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + addresses = proto.RepeatedField(proto.MESSAGE, number=337673122, message="Address",) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", + ) class AddressAggregatedList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -1777,26 +1734,21 @@ class AddressAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="AddressesScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 AddressList(proto.Message): r"""Contains a list of addresses. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -1823,17 +1775,14 @@ class AddressList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="Address",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 AliasIpRange(proto.Message): @@ -1857,16 +1806,14 @@ class AliasIpRange(proto.Message): is used. """ - ip_cidr_range = proto.Field(proto.STRING, number=98117322) - - subnetwork_range_name = proto.Field(proto.STRING, number=119560510) + ip_cidr_range = proto.Field(proto.STRING, number=98117322, optional=True,) + subnetwork_range_name = proto.Field(proto.STRING, number=387995966, optional=True,) class AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk( proto.Message ): r""" - Attributes: disk_size_gb (str): Specifies the size of the disk in base-2 GB. @@ -1888,14 +1835,14 @@ class Interface(proto.Enum): NVME = 2408800 SCSI = 2539686 - disk_size_gb = proto.Field(proto.STRING, number=47828279) - - interface = proto.Field(proto.ENUM, number=234188089, enum=Interface,) + disk_size_gb = proto.Field(proto.STRING, number=316263735, optional=True,) + interface = proto.Field( + proto.ENUM, number=502623545, optional=True, enum=Interface, + ) class AllocationSpecificSKUAllocationReservedInstanceProperties(proto.Message): r"""Properties of the SKU instances being reserved. Next ID: 9 - Attributes: guest_accelerators (Sequence[google.cloud.compute_v1.types.AcceleratorConfig]): Specifies accelerator type and count. @@ -1912,18 +1859,15 @@ class AllocationSpecificSKUAllocationReservedInstanceProperties(proto.Message): """ guest_accelerators = proto.RepeatedField( - proto.MESSAGE, number=195159663, message="AcceleratorConfig", + proto.MESSAGE, number=463595119, message="AcceleratorConfig", ) - local_ssds = proto.RepeatedField( proto.MESSAGE, number=229951299, message="AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk", ) - - machine_type = proto.Field(proto.STRING, number=227711026) - - min_cpu_platform = proto.Field(proto.STRING, number=242912759) + machine_type = proto.Field(proto.STRING, number=227711026, optional=True,) + min_cpu_platform = proto.Field(proto.STRING, number=242912759, optional=True,) class AllocationSpecificSKUReservation(proto.Message): @@ -1940,20 +1884,18 @@ class AllocationSpecificSKUReservation(proto.Message): The instance properties for the reservation. """ - count = proto.Field(proto.STRING, number=94851343) - - in_use_count = proto.Field(proto.STRING, number=225023421) - + count = proto.Field(proto.STRING, number=94851343, optional=True,) + in_use_count = proto.Field(proto.STRING, number=493458877, optional=True,) instance_properties = proto.Field( proto.MESSAGE, number=215355165, + optional=True, message="AllocationSpecificSKUAllocationReservedInstanceProperties", ) class CustomerEncryptionKey(proto.Message): r""" - Attributes: kms_key_name (str): The name of the encryption key that is stored @@ -1973,18 +1915,16 @@ class CustomerEncryptionKey(proto.Message): resource. """ - kms_key_name = proto.Field(proto.STRING, number=215938457) - - kms_key_service_account = proto.Field(proto.STRING, number=209986261) - - raw_key = proto.Field(proto.STRING, number=180761032) - - sha256 = proto.Field(proto.STRING, number=170112551) + kms_key_name = proto.Field(proto.STRING, number=484373913, optional=True,) + kms_key_service_account = proto.Field( + proto.STRING, number=209986261, optional=True, + ) + raw_key = proto.Field(proto.STRING, number=449196488, optional=True,) + sha256 = proto.Field(proto.STRING, number=170112551, optional=True,) class GuestOsFeature(proto.Message): r"""Guest OS features. - Attributes: type_ (google.cloud.compute_v1.types.GuestOsFeature.Type): The ID of a supported feature. Read Enabling @@ -1997,16 +1937,16 @@ class Type(proto.Enum): system features to see a list of available options. """ UNDEFINED_TYPE = 0 - FEATURE_TYPE_UNSPECIFIED = 263331803 + FEATURE_TYPE_UNSPECIFIED = 531767259 GVNIC = 68209305 MULTI_IP_SUBNET = 151776719 - SECURE_BOOT = 108375738 + SECURE_BOOT = 376811194 SEV_CAPABLE = 87083793 UEFI_COMPATIBLE = 195865408 VIRTIO_SCSI_MULTIQUEUE = 201597069 - WINDOWS = 188427875 + WINDOWS = 456863331 - type_ = proto.Field(proto.ENUM, number=3575610, enum=Type,) + type_ = proto.Field(proto.ENUM, number=3575610, optional=True, enum=Type,) class AttachedDiskInitializeParams(proto.Message): @@ -2125,34 +2065,26 @@ class OnUpdateAction(proto.Enum): disk. Default is to use the existing disk. """ UNDEFINED_ON_UPDATE_ACTION = 0 - RECREATE_DISK = 226332397 - RECREATE_DISK_IF_SOURCE_CHANGED = 129664256 + RECREATE_DISK = 494767853 + RECREATE_DISK_IF_SOURCE_CHANGED = 398099712 USE_EXISTING_DISK = 232682233 - description = proto.Field(proto.STRING, number=154502140) - - disk_name = proto.Field(proto.STRING, number=92807149) - - disk_size_gb = proto.Field(proto.STRING, number=47828279) - - disk_type = proto.Field(proto.STRING, number=93009052) - - labels = proto.MapField(proto.STRING, proto.STRING, number=231759871) - - on_update_action = proto.Field(proto.ENUM, number=202451980, enum=OnUpdateAction,) - - resource_policies = proto.RepeatedField(proto.STRING, number=22220385) - - source_image = proto.Field(proto.STRING, number=50443319) - + description = proto.Field(proto.STRING, number=422937596, optional=True,) + disk_name = proto.Field(proto.STRING, number=92807149, optional=True,) + disk_size_gb = proto.Field(proto.STRING, number=316263735, optional=True,) + disk_type = proto.Field(proto.STRING, number=93009052, optional=True,) + labels = proto.MapField(proto.STRING, proto.STRING, number=500195327,) + on_update_action = proto.Field( + proto.ENUM, number=202451980, optional=True, enum=OnUpdateAction, + ) + resource_policies = proto.RepeatedField(proto.STRING, number=22220385,) + source_image = proto.Field(proto.STRING, number=50443319, optional=True,) source_image_encryption_key = proto.Field( - proto.MESSAGE, number=113068203, message="CustomerEncryptionKey", + proto.MESSAGE, number=381503659, optional=True, message="CustomerEncryptionKey", ) - - source_snapshot = proto.Field(proto.STRING, number=126061928) - + source_snapshot = proto.Field(proto.STRING, number=126061928, optional=True,) source_snapshot_encryption_key = proto.Field( - proto.MESSAGE, number=35243866, message="CustomerEncryptionKey", + proto.MESSAGE, number=303679322, optional=True, message="CustomerEncryptionKey", ) @@ -2172,21 +2104,19 @@ class InitialStateConfig(proto.Message): """ dbs = proto.RepeatedField(proto.MESSAGE, number=99253, message="FileContentBuffer",) - dbxs = proto.RepeatedField( proto.MESSAGE, number=3077113, message="FileContentBuffer", ) - keks = proto.RepeatedField( proto.MESSAGE, number=3288130, message="FileContentBuffer", ) - - pk = proto.Field(proto.MESSAGE, number=3579, message="FileContentBuffer",) + pk = proto.Field( + proto.MESSAGE, number=3579, optional=True, message="FileContentBuffer", + ) class AttachedDisk(proto.Message): r"""An instance-attached disk resource. - Attributes: auto_delete (bool): Specifies whether the disk will be auto- @@ -2315,46 +2245,37 @@ class Type(proto.Enum): If not specified, the default is PERSISTENT. """ UNDEFINED_TYPE = 0 - PERSISTENT = 192248471 - SCRATCH = 228343514 - - auto_delete = proto.Field(proto.BOOL, number=196325947) - - boot = proto.Field(proto.BOOL, number=3029746) - - device_name = proto.Field(proto.STRING, number=67541716) + PERSISTENT = 460683927 + SCRATCH = 496778970 + auto_delete = proto.Field(proto.BOOL, number=464761403, optional=True,) + boot = proto.Field(proto.BOOL, number=3029746, optional=True,) + device_name = proto.Field(proto.STRING, number=67541716, optional=True,) disk_encryption_key = proto.Field( - proto.MESSAGE, number=3225221, message="CustomerEncryptionKey", + proto.MESSAGE, number=271660677, optional=True, message="CustomerEncryptionKey", ) - - disk_size_gb = proto.Field(proto.STRING, number=47828279) - + disk_size_gb = proto.Field(proto.STRING, number=316263735, optional=True,) guest_os_features = proto.RepeatedField( proto.MESSAGE, number=79294545, message="GuestOsFeature", ) - - index = proto.Field(proto.INT32, number=100346066) - + index = proto.Field(proto.INT32, number=100346066, optional=True,) initialize_params = proto.Field( - proto.MESSAGE, number=17697045, message="AttachedDiskInitializeParams", + proto.MESSAGE, + number=17697045, + optional=True, + message="AttachedDiskInitializeParams", ) - - interface = proto.Field(proto.ENUM, number=234188089, enum=Interface,) - - kind = proto.Field(proto.STRING, number=3292052) - - licenses = proto.RepeatedField(proto.STRING, number=69207122) - - mode = proto.Field(proto.ENUM, number=3357091, enum=Mode,) - + interface = proto.Field( + proto.ENUM, number=502623545, optional=True, enum=Interface, + ) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) + licenses = proto.RepeatedField(proto.STRING, number=337642578,) + mode = proto.Field(proto.ENUM, number=3357091, optional=True, enum=Mode,) shielded_instance_initial_state = proto.Field( - proto.MESSAGE, number=192356867, message="InitialStateConfig", + proto.MESSAGE, number=192356867, optional=True, message="InitialStateConfig", ) - - source = proto.Field(proto.STRING, number=177235995) - - type_ = proto.Field(proto.ENUM, number=3575610, enum=Type,) + source = proto.Field(proto.STRING, number=177235995, optional=True,) + type_ = proto.Field(proto.ENUM, number=3575610, optional=True, enum=Type,) class AuditLogConfig(proto.Message): @@ -2383,15 +2304,13 @@ class LogType(proto.Enum): r"""The log type that this config enables.""" UNDEFINED_LOG_TYPE = 0 ADMIN_READ = 128951462 - DATA_READ = 36789515 - DATA_WRITE = 71746282 + DATA_READ = 305224971 + DATA_WRITE = 340181738 LOG_TYPE_UNSPECIFIED = 154527053 - exempted_members = proto.RepeatedField(proto.STRING, number=232615576) - - ignore_child_exemptions = proto.Field(proto.BOOL, number=70141850) - - log_type = proto.Field(proto.ENUM, number=134680405, enum=LogType,) + exempted_members = proto.RepeatedField(proto.STRING, number=232615576,) + ignore_child_exemptions = proto.Field(proto.BOOL, number=70141850, optional=True,) + log_type = proto.Field(proto.ENUM, number=403115861, optional=True, enum=LogType,) class AuditConfig(proto.Message): @@ -2433,12 +2352,10 @@ class AuditConfig(proto.Message): """ audit_log_configs = proto.RepeatedField( - proto.MESSAGE, number=219985170, message="AuditLogConfig", + proto.MESSAGE, number=488420626, message="AuditLogConfig", ) - - exempted_members = proto.RepeatedField(proto.STRING, number=232615576) - - service = proto.Field(proto.STRING, number=105105077) + exempted_members = proto.RepeatedField(proto.STRING, number=232615576,) + service = proto.Field(proto.STRING, number=373540533, optional=True,) class AuthorizationLoggingOptions(proto.Message): @@ -2455,16 +2372,17 @@ class PermissionType(proto.Enum): UNDEFINED_PERMISSION_TYPE = 0 ADMIN_READ = 128951462 ADMIN_WRITE = 244412079 - DATA_READ = 36789515 - DATA_WRITE = 71746282 - PERMISSION_TYPE_UNSPECIFIED = 171877890 + DATA_READ = 305224971 + DATA_WRITE = 340181738 + PERMISSION_TYPE_UNSPECIFIED = 440313346 - permission_type = proto.Field(proto.ENUM, number=257543082, enum=PermissionType,) + permission_type = proto.Field( + proto.ENUM, number=525978538, optional=True, enum=PermissionType, + ) class AutoscalingPolicy(proto.Message): r"""Cloud Autoscaler policy. - Attributes: cool_down_period_sec (int): The number of seconds that the autoscaler @@ -2514,40 +2432,39 @@ class Mode(proto.Enum): OFF = 78159 ON = 2527 ONLY_SCALE_OUT = 152713670 - ONLY_UP = 209659918 - - cool_down_period_sec = proto.Field(proto.INT32, number=107692954) + ONLY_UP = 478095374 + cool_down_period_sec = proto.Field(proto.INT32, number=107692954, optional=True,) cpu_utilization = proto.Field( - proto.MESSAGE, number=112775691, message="AutoscalingPolicyCpuUtilization", + proto.MESSAGE, + number=381211147, + optional=True, + message="AutoscalingPolicyCpuUtilization", ) - custom_metric_utilizations = proto.RepeatedField( proto.MESSAGE, number=131972850, message="AutoscalingPolicyCustomMetricUtilization", ) - load_balancing_utilization = proto.Field( proto.MESSAGE, - number=161310947, + number=429746403, + optional=True, message="AutoscalingPolicyLoadBalancingUtilization", ) - - max_num_replicas = proto.Field(proto.INT32, number=62327375) - - min_num_replicas = proto.Field(proto.INT32, number=266894369) - - mode = proto.Field(proto.ENUM, number=3357091, enum=Mode,) - + max_num_replicas = proto.Field(proto.INT32, number=62327375, optional=True,) + min_num_replicas = proto.Field(proto.INT32, number=535329825, optional=True,) + mode = proto.Field(proto.ENUM, number=3357091, optional=True, enum=Mode,) scale_in_control = proto.Field( - proto.MESSAGE, number=259235416, message="AutoscalingPolicyScaleInControl", + proto.MESSAGE, + number=527670872, + optional=True, + message="AutoscalingPolicyScaleInControl", ) class AutoscalerStatusDetails(proto.Message): r""" - Attributes: message (str): The status message. @@ -2654,28 +2571,27 @@ class Type(proto.Enum): values might not be available in all API versions. """ UNDEFINED_TYPE = 0 - ALL_INSTANCES_UNHEALTHY = 136530021 + ALL_INSTANCES_UNHEALTHY = 404965477 BACKEND_SERVICE_DOES_NOT_EXIST = 191417626 CAPPED_AT_MAX_NUM_REPLICAS = 518617 - CUSTOM_METRIC_DATA_POINTS_TOO_SPARSE = 60529203 + CUSTOM_METRIC_DATA_POINTS_TOO_SPARSE = 328964659 CUSTOM_METRIC_INVALID = 204430550 MIN_EQUALS_MAX = 2821361 MISSING_CUSTOM_METRIC_DATA_POINTS = 94885086 - MISSING_LOAD_BALANCING_DATA_POINTS = 241423442 + MISSING_LOAD_BALANCING_DATA_POINTS = 509858898 MODE_OFF = 164169907 MODE_ONLY_SCALE_OUT = 3840994 MODE_ONLY_UP = 100969842 MORE_THAN_ONE_BACKEND_SERVICE = 151922141 - NOT_ENOUGH_QUOTA_AVAILABLE = 134666175 - REGION_RESOURCE_STOCKOUT = 260187390 + NOT_ENOUGH_QUOTA_AVAILABLE = 403101631 + REGION_RESOURCE_STOCKOUT = 528622846 SCALING_TARGET_DOES_NOT_EXIST = 122636699 - UNKNOWN = 164706346 - UNSUPPORTED_MAX_RATE_LOAD_BALANCING_CONFIGURATION = 62409553 + UNKNOWN = 433141802 + UNSUPPORTED_MAX_RATE_LOAD_BALANCING_CONFIGURATION = 330845009 ZONE_RESOURCE_STOCKOUT = 210200502 - message = proto.Field(proto.STRING, number=149618695) - - type_ = proto.Field(proto.ENUM, number=3575610, enum=Type,) + message = proto.Field(proto.STRING, number=418054151, optional=True,) + type_ = proto.Field(proto.ENUM, number=3575610, optional=True, enum=Type,) class Autoscaler(proto.Message): @@ -2781,45 +2697,32 @@ class Status(proto.Enum): in the future. """ UNDEFINED_STATUS = 0 - ACTIVE = 46297862 - DELETING = 260166568 + ACTIVE = 314733318 + DELETING = 528602024 ERROR = 66247144 PENDING = 35394935 autoscaling_policy = proto.Field( - proto.MESSAGE, number=221950041, message="AutoscalingPolicy", - ) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - - recommended_size = proto.Field(proto.INT32, number=257915749) - - region = proto.Field(proto.STRING, number=138946292) - - self_link = proto.Field(proto.STRING, number=187779341) - - status = proto.Field(proto.ENUM, number=181260274, enum=Status,) - + proto.MESSAGE, number=221950041, optional=True, message="AutoscalingPolicy", + ) + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, 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,) + recommended_size = proto.Field(proto.INT32, number=257915749, optional=True,) + 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,) status_details = proto.RepeatedField( - proto.MESSAGE, number=94918389, message="AutoscalerStatusDetails", + proto.MESSAGE, number=363353845, message="AutoscalerStatusDetails", ) - - target = proto.Field(proto.STRING, number=192835985) - - zone = proto.Field(proto.STRING, number=3744684) + target = proto.Field(proto.STRING, number=192835985, optional=True,) + zone = proto.Field(proto.STRING, number=3744684, optional=True,) class AutoscalersScopedList(proto.Message): r""" - Attributes: autoscalers (Sequence[google.cloud.compute_v1.types.Autoscaler]): [Output Only] A list of autoscalers contained in this scope. @@ -2829,15 +2732,15 @@ class AutoscalersScopedList(proto.Message): """ autoscalers = proto.RepeatedField( - proto.MESSAGE, number=197336188, message="Autoscaler", + proto.MESSAGE, number=465771644, message="Autoscaler", + ) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", ) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) class AutoscalerAggregatedList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -2867,26 +2770,21 @@ class AutoscalerAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="AutoscalersScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 AutoscalerList(proto.Message): r"""Contains a list of Autoscaler resources. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -2913,22 +2811,18 @@ class AutoscalerList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="Autoscaler",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 AutoscalingPolicyCpuUtilization(proto.Message): r"""CPU utilization policy. - Attributes: utilization_target (float): The target CPU utilization that the autoscaler maintains. @@ -2947,12 +2841,11 @@ class AutoscalingPolicyCpuUtilization(proto.Message): reaches the target utilization. """ - utilization_target = proto.Field(proto.DOUBLE, number=215905870) + utilization_target = proto.Field(proto.DOUBLE, number=215905870, optional=True,) class AutoscalingPolicyCustomMetricUtilization(proto.Message): r"""Custom utilization metric policy. - Attributes: filter (str): A filter string, compatible with a Stackdriver Monitoring @@ -3039,16 +2932,14 @@ class UtilizationTargetType(proto.Enum): DELTA_PER_SECOND = 255180029 GAUGE = 67590361 - filter = proto.Field(proto.STRING, number=67685240) - - metric = proto.Field(proto.STRING, number=264631728) - - single_instance_assignment = proto.Field(proto.DOUBLE, number=236332608) - - utilization_target = proto.Field(proto.DOUBLE, number=215905870) - + filter = proto.Field(proto.STRING, number=336120696, optional=True,) + metric = proto.Field(proto.STRING, number=533067184, optional=True,) + single_instance_assignment = proto.Field( + proto.DOUBLE, number=504768064, optional=True, + ) + utilization_target = proto.Field(proto.DOUBLE, number=215905870, optional=True,) utilization_target_type = proto.Field( - proto.ENUM, number=71733899, enum=UtilizationTargetType, + proto.ENUM, number=340169355, optional=True, enum=UtilizationTargetType, ) @@ -3064,7 +2955,7 @@ class AutoscalingPolicyLoadBalancingUtilization(proto.Message): float value. If not defined, the default is 0.8. """ - utilization_target = proto.Field(proto.DOUBLE, number=215905870) + utilization_target = proto.Field(proto.DOUBLE, number=215905870, optional=True,) class AutoscalingPolicyScaleInControl(proto.Message): @@ -3087,10 +2978,9 @@ class AutoscalingPolicyScaleInControl(proto.Message): """ max_scaled_in_replicas = proto.Field( - proto.MESSAGE, number=180710123, message="FixedOrPercent", + proto.MESSAGE, number=180710123, optional=True, message="FixedOrPercent", ) - - time_window_sec = proto.Field(proto.INT32, number=36405300) + time_window_sec = proto.Field(proto.INT32, number=36405300, optional=True,) class FixedOrPercent(proto.Message): @@ -3118,16 +3008,13 @@ class FixedOrPercent(proto.Message): 80%. """ - calculated = proto.Field(proto.INT32, number=203647422) - - fixed = proto.Field(proto.INT32, number=97445748) - - percent = proto.Field(proto.INT32, number=126379077) + calculated = proto.Field(proto.INT32, number=472082878, optional=True,) + fixed = proto.Field(proto.INT32, number=97445748, optional=True,) + percent = proto.Field(proto.INT32, number=394814533, optional=True,) 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. @@ -3365,29 +3252,24 @@ class BalancingMode(proto.Enum): RATE = 2508000 UTILIZATION = 157008386 - balancing_mode = proto.Field(proto.ENUM, number=161850761, enum=BalancingMode,) - - capacity_scaler = proto.Field(proto.FLOAT, number=47522701) - - description = proto.Field(proto.STRING, number=154502140) - - failover = proto.Field(proto.BOOL, number=138892530) - - group = proto.Field(proto.STRING, number=98629247) - - max_connections = proto.Field(proto.INT32, number=110652154) - - max_connections_per_endpoint = proto.Field(proto.INT32, number=216904604) - - max_connections_per_instance = proto.Field(proto.INT32, number=104671900) - - max_rate = proto.Field(proto.INT32, number=139599579) - - max_rate_per_endpoint = proto.Field(proto.FLOAT, number=129832283) - - max_rate_per_instance = proto.Field(proto.FLOAT, number=17599579) - - max_utilization = proto.Field(proto.FLOAT, number=148192199) + balancing_mode = proto.Field( + proto.ENUM, number=430286217, optional=True, enum=BalancingMode, + ) + capacity_scaler = proto.Field(proto.FLOAT, number=315958157, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + failover = proto.Field(proto.BOOL, number=138892530, optional=True,) + group = proto.Field(proto.STRING, number=98629247, optional=True,) + max_connections = proto.Field(proto.INT32, number=110652154, optional=True,) + max_connections_per_endpoint = proto.Field( + proto.INT32, number=216904604, optional=True, + ) + max_connections_per_instance = proto.Field( + proto.INT32, number=104671900, optional=True, + ) + max_rate = proto.Field(proto.INT32, number=408035035, optional=True,) + max_rate_per_endpoint = proto.Field(proto.FLOAT, number=129832283, optional=True,) + max_rate_per_instance = proto.Field(proto.FLOAT, number=17599579, optional=True,) + max_utilization = proto.Field(proto.FLOAT, number=148192199, optional=True,) class BackendBucketCdnPolicy(proto.Message): @@ -3482,22 +3364,21 @@ class CacheMode(proto.Enum): be cached. """ UNDEFINED_CACHE_MODE = 0 - CACHE_ALL_STATIC = 86592489 - FORCE_CACHE_ALL = 217591472 - INVALID_CACHE_MODE = 112860104 + CACHE_ALL_STATIC = 355027945 + FORCE_CACHE_ALL = 486026928 + INVALID_CACHE_MODE = 381295560 USE_ORIGIN_HEADERS = 55380261 - cache_mode = proto.Field(proto.ENUM, number=28877888, enum=CacheMode,) - - client_ttl = proto.Field(proto.INT32, number=29034360) - - default_ttl = proto.Field(proto.INT32, number=100253422) - - max_ttl = proto.Field(proto.INT32, number=39142545) - - signed_url_cache_max_age_sec = proto.Field(proto.STRING, number=939078) - - signed_url_key_names = proto.RepeatedField(proto.STRING, number=103413429) + 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,) + signed_url_cache_max_age_sec = proto.Field( + proto.STRING, number=269374534, optional=True, + ) + signed_url_key_names = proto.RepeatedField(proto.STRING, number=371848885,) class BackendBucket(proto.Message): @@ -3541,32 +3422,25 @@ class BackendBucket(proto.Message): [Output Only] Server-defined URL for the resource. """ - bucket_name = proto.Field(proto.STRING, number=15174592) - + bucket_name = proto.Field(proto.STRING, number=283610048, optional=True,) cdn_policy = proto.Field( - proto.MESSAGE, number=213976452, message="BackendBucketCdnPolicy", + proto.MESSAGE, + number=213976452, + optional=True, + message="BackendBucketCdnPolicy", ) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - custom_response_headers = proto.RepeatedField(proto.STRING, number=119103638) - - description = proto.Field(proto.STRING, number=154502140) - - enable_cdn = proto.Field(proto.BOOL, number=14506865) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - - self_link = proto.Field(proto.STRING, number=187779341) + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + custom_response_headers = proto.RepeatedField(proto.STRING, number=387539094,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + enable_cdn = proto.Field(proto.BOOL, number=282942321, 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,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) class BackendBucketList(proto.Message): r"""Contains a list of BackendBucket resources. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -3592,19 +3466,16 @@ class BackendBucketList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="BackendBucket", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 BackendServiceCdnPolicy(proto.Message): @@ -3701,26 +3572,24 @@ class CacheMode(proto.Enum): be cached. """ UNDEFINED_CACHE_MODE = 0 - CACHE_ALL_STATIC = 86592489 - FORCE_CACHE_ALL = 217591472 - INVALID_CACHE_MODE = 112860104 + CACHE_ALL_STATIC = 355027945 + FORCE_CACHE_ALL = 486026928 + INVALID_CACHE_MODE = 381295560 USE_ORIGIN_HEADERS = 55380261 cache_key_policy = proto.Field( - proto.MESSAGE, number=159263727, message="CacheKeyPolicy", + proto.MESSAGE, number=159263727, optional=True, message="CacheKeyPolicy", ) - - cache_mode = proto.Field(proto.ENUM, number=28877888, enum=CacheMode,) - - client_ttl = proto.Field(proto.INT32, number=29034360) - - default_ttl = proto.Field(proto.INT32, number=100253422) - - max_ttl = proto.Field(proto.INT32, number=39142545) - - signed_url_cache_max_age_sec = proto.Field(proto.STRING, number=939078) - - signed_url_key_names = proto.RepeatedField(proto.STRING, number=103413429) + 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,) + signed_url_cache_max_age_sec = proto.Field( + proto.STRING, number=269374534, optional=True, + ) + signed_url_key_names = proto.RepeatedField(proto.STRING, number=371848885,) class CircuitBreakers(proto.Message): @@ -3753,20 +3622,17 @@ class CircuitBreakers(proto.Message): specified, the default is 1. """ - max_connections = proto.Field(proto.INT32, number=110652154) - - max_pending_requests = proto.Field(proto.INT32, number=107123431) - - max_requests = proto.Field(proto.INT32, number=28097599) - - max_requests_per_connection = proto.Field(proto.INT32, number=93195072) - - max_retries = proto.Field(proto.INT32, number=55546219) + max_connections = proto.Field(proto.INT32, number=110652154, optional=True,) + max_pending_requests = proto.Field(proto.INT32, number=375558887, optional=True,) + max_requests = proto.Field(proto.INT32, number=28097599, optional=True,) + max_requests_per_connection = proto.Field( + proto.INT32, number=361630528, optional=True, + ) + max_retries = proto.Field(proto.INT32, number=55546219, optional=True,) 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 @@ -3774,7 +3640,7 @@ class ConnectionDraining(proto.Message): if the protocol is not UDP. The valid range is [0, 3600]. """ - draining_timeout_sec = proto.Field(proto.INT32, number=225127070) + draining_timeout_sec = proto.Field(proto.INT32, number=225127070, optional=True,) class ConsistentHashLoadBalancerSettings(proto.Message): @@ -3805,12 +3671,11 @@ class ConsistentHashLoadBalancerSettings(proto.Message): http_cookie = proto.Field( proto.MESSAGE, number=6673915, + optional=True, message="ConsistentHashLoadBalancerSettingsHttpCookie", ) - - http_header_name = proto.Field(proto.STRING, number=234798022) - - minimum_ring_size = proto.Field(proto.STRING, number=234380735) + http_header_name = proto.Field(proto.STRING, number=234798022, optional=True,) + minimum_ring_size = proto.Field(proto.STRING, number=234380735, optional=True,) class BackendServiceFailoverPolicy(proto.Message): @@ -3849,16 +3714,17 @@ class BackendServiceFailoverPolicy(proto.Message): healthy primary VMs is less than this ratio. """ - disable_connection_drain_on_failover = proto.Field(proto.BOOL, number=182150753) - - drop_traffic_if_unhealthy = proto.Field(proto.BOOL, number=112289428) - - failover_ratio = proto.Field(proto.FLOAT, number=212667006) + disable_connection_drain_on_failover = proto.Field( + proto.BOOL, number=182150753, optional=True, + ) + drop_traffic_if_unhealthy = proto.Field( + proto.BOOL, number=112289428, optional=True, + ) + failover_ratio = proto.Field(proto.FLOAT, number=212667006, optional=True,) class BackendServiceIAP(proto.Message): r"""Identity-Aware Proxy - Attributes: enabled (bool): Whether the serving infrastructure will @@ -3879,13 +3745,12 @@ class BackendServiceIAP(proto.Message): oauth2_client_secret above. """ - enabled = proto.Field(proto.BOOL, number=1018689) - - oauth2_client_id = proto.Field(proto.STRING, number=45582155) - - oauth2_client_secret = proto.Field(proto.STRING, number=50999520) - - oauth2_client_secret_sha256 = proto.Field(proto.STRING, number=112903782) + enabled = proto.Field(proto.BOOL, number=1018689, optional=True,) + oauth2_client_id = proto.Field(proto.STRING, number=314017611, optional=True,) + oauth2_client_secret = proto.Field(proto.STRING, number=50999520, optional=True,) + oauth2_client_secret_sha256 = proto.Field( + proto.STRING, number=112903782, optional=True, + ) class BackendServiceLogConfig(proto.Message): @@ -3906,9 +3771,8 @@ class BackendServiceLogConfig(proto.Message): default value is 1.0. """ - enable = proto.Field(proto.BOOL, number=43328899) - - sample_rate = proto.Field(proto.FLOAT, number=153193045) + enable = proto.Field(proto.BOOL, number=311764355, optional=True,) + sample_rate = proto.Field(proto.FLOAT, number=153193045, optional=True,) class OutlierDetection(proto.Message): @@ -3986,28 +3850,32 @@ class OutlierDetection(proto.Message): """ base_ejection_time = proto.Field( - proto.MESSAGE, number=80997255, message="Duration", + proto.MESSAGE, number=80997255, optional=True, message="Duration", + ) + consecutive_errors = proto.Field(proto.INT32, number=387193248, optional=True,) + consecutive_gateway_failure = proto.Field( + proto.INT32, number=417504250, optional=True, + ) + enforcing_consecutive_errors = proto.Field( + proto.INT32, number=213133760, optional=True, + ) + enforcing_consecutive_gateway_failure = proto.Field( + proto.INT32, number=394440666, optional=True, + ) + enforcing_success_rate = proto.Field(proto.INT32, number=194508732, optional=True,) + interval = proto.Field( + proto.MESSAGE, number=33547461, optional=True, message="Duration", + ) + max_ejection_percent = proto.Field(proto.INT32, number=18436888, optional=True,) + success_rate_minimum_hosts = proto.Field( + proto.INT32, number=525766903, optional=True, + ) + success_rate_request_volume = proto.Field( + proto.INT32, number=281425357, optional=True, + ) + success_rate_stdev_factor = proto.Field( + proto.INT32, number=174735773, optional=True, ) - - consecutive_errors = proto.Field(proto.INT32, number=118757792) - - consecutive_gateway_failure = proto.Field(proto.INT32, number=149068794) - - enforcing_consecutive_errors = proto.Field(proto.INT32, number=213133760) - - enforcing_consecutive_gateway_failure = proto.Field(proto.INT32, number=126005210) - - enforcing_success_rate = proto.Field(proto.INT32, number=194508732) - - interval = proto.Field(proto.MESSAGE, number=33547461, message="Duration",) - - max_ejection_percent = proto.Field(proto.INT32, number=18436888) - - success_rate_minimum_hosts = proto.Field(proto.INT32, number=257331447) - - success_rate_request_volume = proto.Field(proto.INT32, number=12989901) - - success_rate_stdev_factor = proto.Field(proto.INT32, number=174735773) class SecuritySettings(proto.Message): @@ -4042,9 +3910,8 @@ class SecuritySettings(proto.Message): mode). Note: This field currently has no impact. """ - client_tls_policy = proto.Field(proto.STRING, number=193889770) - - subject_alt_names = proto.RepeatedField(proto.STRING, number=61594079) + client_tls_policy = proto.Field(proto.STRING, number=462325226, optional=True,) + subject_alt_names = proto.RepeatedField(proto.STRING, number=330029535,) class BackendService(proto.Message): @@ -4361,10 +4228,10 @@ class LoadBalancingScheme(proto.Enum): """ UNDEFINED_LOAD_BALANCING_SCHEME = 0 EXTERNAL = 35607499 - INTERNAL = 10860221 + INTERNAL = 279295677 INTERNAL_MANAGED = 37350397 INTERNAL_SELF_MANAGED = 236211150 - INVALID_LOAD_BALANCING_SCHEME = 6916604 + INVALID_LOAD_BALANCING_SCHEME = 275352060 class LocalityLbPolicy(proto.Enum): r"""The load balancing algorithm used within the scope of the locality. @@ -4406,12 +4273,12 @@ class LocalityLbPolicy(proto.Enum): proxy that has validateForProxyless field set to true. """ UNDEFINED_LOCALITY_LB_POLICY = 0 - INVALID_LB_POLICY = 54883251 + INVALID_LB_POLICY = 323318707 LEAST_REQUEST = 46604921 MAGLEV = 119180266 ORIGINAL_DESTINATION = 166297216 RANDOM = 262527171 - RING_HASH = 164359613 + RING_HASH = 432795069 ROUND_ROBIN = 153895801 class Protocol(proto.Enum): @@ -4455,102 +4322,86 @@ class SessionAffinity(proto.Enum): field set to true. """ UNDEFINED_SESSION_AFFINITY = 0 - CLIENT_IP = 77229595 + CLIENT_IP = 345665051 CLIENT_IP_PORT_PROTO = 221722926 CLIENT_IP_PROTO = 25322148 - GENERATED_COOKIE = 101885748 + GENERATED_COOKIE = 370321204 HEADER_FIELD = 200737960 - HTTP_COOKIE = 226546171 + HTTP_COOKIE = 494981627 NONE = 2402104 - affinity_cookie_ttl_sec = proto.Field(proto.INT32, number=101561498) - - backends = proto.RepeatedField(proto.MESSAGE, number=242404447, message="Backend",) - + affinity_cookie_ttl_sec = proto.Field(proto.INT32, number=369996954, optional=True,) + backends = proto.RepeatedField(proto.MESSAGE, number=510839903, message="Backend",) cdn_policy = proto.Field( - proto.MESSAGE, number=213976452, message="BackendServiceCdnPolicy", + proto.MESSAGE, + number=213976452, + optional=True, + message="BackendServiceCdnPolicy", ) - circuit_breakers = proto.Field( - proto.MESSAGE, number=152904605, message="CircuitBreakers", + proto.MESSAGE, number=421340061, optional=True, message="CircuitBreakers", ) - connection_draining = proto.Field( - proto.MESSAGE, number=192661291, message="ConnectionDraining", + proto.MESSAGE, number=461096747, optional=True, message="ConnectionDraining", ) - consistent_hash = proto.Field( - proto.MESSAGE, number=905883, message="ConsistentHashLoadBalancerSettings", - ) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - custom_request_headers = proto.RepeatedField(proto.STRING, number=27977992) - - custom_response_headers = proto.RepeatedField(proto.STRING, number=119103638) - - description = proto.Field(proto.STRING, number=154502140) - - enable_c_d_n = proto.Field(proto.BOOL, number=250733499) - + proto.MESSAGE, + number=905883, + optional=True, + message="ConsistentHashLoadBalancerSettings", + ) + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + custom_request_headers = proto.RepeatedField(proto.STRING, number=27977992,) + custom_response_headers = proto.RepeatedField(proto.STRING, number=387539094,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + enable_c_d_n = proto.Field(proto.BOOL, number=250733499, optional=True,) failover_policy = proto.Field( - proto.MESSAGE, number=105658655, message="BackendServiceFailoverPolicy", + proto.MESSAGE, + number=105658655, + optional=True, + message="BackendServiceFailoverPolicy", ) - - fingerprint = proto.Field(proto.STRING, number=234678500) - - health_checks = proto.RepeatedField(proto.STRING, number=179935150) - - iap = proto.Field(proto.MESSAGE, number=104024, message="BackendServiceIAP",) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - + fingerprint = proto.Field(proto.STRING, number=234678500, optional=True,) + health_checks = proto.RepeatedField(proto.STRING, number=448370606,) + iap = proto.Field( + proto.MESSAGE, number=104024, optional=True, message="BackendServiceIAP", + ) + id = proto.Field(proto.STRING, number=3355, optional=True,) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) load_balancing_scheme = proto.Field( - proto.ENUM, number=95454788, enum=LoadBalancingScheme, + proto.ENUM, number=363890244, optional=True, enum=LoadBalancingScheme, ) - locality_lb_policy = proto.Field( - proto.ENUM, number=131431487, enum=LocalityLbPolicy, + proto.ENUM, number=131431487, optional=True, enum=LocalityLbPolicy, ) - log_config = proto.Field( - proto.MESSAGE, number=82864285, message="BackendServiceLogConfig", + proto.MESSAGE, + number=351299741, + optional=True, + message="BackendServiceLogConfig", ) - - name = proto.Field(proto.STRING, number=3373707) - - network = proto.Field(proto.STRING, number=232872494) - + name = proto.Field(proto.STRING, number=3373707, optional=True,) + network = proto.Field(proto.STRING, number=232872494, optional=True,) outlier_detection = proto.Field( - proto.MESSAGE, number=86189630, message="OutlierDetection", + proto.MESSAGE, number=354625086, optional=True, message="OutlierDetection", ) - - port = proto.Field(proto.INT32, number=3446913) - - port_name = proto.Field(proto.STRING, number=41534345) - - protocol = proto.Field(proto.ENUM, number=84577944, enum=Protocol,) - - region = proto.Field(proto.STRING, number=138946292) - - security_policy = proto.Field(proto.STRING, number=171082513) - + port = proto.Field(proto.INT32, number=3446913, optional=True,) + port_name = proto.Field(proto.STRING, number=41534345, optional=True,) + protocol = proto.Field(proto.ENUM, number=84577944, optional=True, enum=Protocol,) + region = proto.Field(proto.STRING, number=138946292, optional=True,) + security_policy = proto.Field(proto.STRING, number=171082513, optional=True,) security_settings = proto.Field( - proto.MESSAGE, number=210214466, message="SecuritySettings", + proto.MESSAGE, number=478649922, optional=True, message="SecuritySettings", ) - - self_link = proto.Field(proto.STRING, number=187779341) - - session_affinity = proto.Field(proto.ENUM, number=195453105, enum=SessionAffinity,) - - timeout_sec = proto.Field(proto.INT32, number=79994995) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + session_affinity = proto.Field( + proto.ENUM, number=463888561, optional=True, enum=SessionAffinity, + ) + timeout_sec = proto.Field(proto.INT32, number=79994995, optional=True,) class BackendServicesScopedList(proto.Message): r""" - Attributes: backend_services (Sequence[google.cloud.compute_v1.types.BackendService]): A list of BackendServices contained in this @@ -4561,15 +4412,15 @@ class BackendServicesScopedList(proto.Message): """ backend_services = proto.RepeatedField( - proto.MESSAGE, number=120086953, message="BackendService", + proto.MESSAGE, number=388522409, message="BackendService", + ) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", ) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) class BackendServiceAggregatedList(proto.Message): r"""Contains a list of BackendServicesScopedList. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -4598,24 +4449,20 @@ class BackendServiceAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="BackendServicesScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 CacheKeyPolicy(proto.Message): @@ -4649,20 +4496,15 @@ class CacheKeyPolicy(proto.Message): delimiters. """ - include_host = proto.Field(proto.BOOL, number=218432223) - - include_protocol = proto.Field(proto.BOOL, number=35072079) - - include_query_string = proto.Field(proto.BOOL, number=205601183) - - query_string_blacklist = proto.RepeatedField(proto.STRING, number=86529286) - - query_string_whitelist = proto.RepeatedField(proto.STRING, number=52456496) + include_host = proto.Field(proto.BOOL, number=486867679, optional=True,) + include_protocol = proto.Field(proto.BOOL, number=303507535, optional=True,) + include_query_string = proto.Field(proto.BOOL, number=474036639, optional=True,) + query_string_blacklist = proto.RepeatedField(proto.STRING, number=354964742,) + query_string_whitelist = proto.RepeatedField(proto.STRING, number=52456496,) class HealthStatus(proto.Message): r""" - Attributes: annotations (Sequence[google.cloud.compute_v1.types.HealthStatus.AnnotationsEntry]): Metadata defined as annotations for network @@ -4686,35 +4528,32 @@ class HealthStatus(proto.Message): class HealthState(proto.Enum): r"""Health state of the instance.""" UNDEFINED_HEALTH_STATE = 0 - HEALTHY = 171365757 - UNHEALTHY = 193682628 + HEALTHY = 439801213 + UNHEALTHY = 462118084 class WeightError(proto.Enum): r"""""" UNDEFINED_WEIGHT_ERROR = 0 - INVALID_WEIGHT = 115262944 - MISSING_WEIGHT = 115592081 - UNAVAILABLE_WEIGHT = 171028839 - WEIGHT_NONE = 233993375 - - annotations = proto.MapField(proto.STRING, proto.STRING, number=112032548) - - health_state = proto.Field(proto.ENUM, number=55571694, enum=HealthState,) + INVALID_WEIGHT = 383698400 + MISSING_WEIGHT = 384027537 + UNAVAILABLE_WEIGHT = 439464295 + WEIGHT_NONE = 502428831 - instance = proto.Field(proto.STRING, number=18257045) - - ip_address = proto.Field(proto.STRING, number=137836764) - - port = proto.Field(proto.INT32, number=3446913) - - weight = proto.Field(proto.STRING, number=13714040) - - weight_error = proto.Field(proto.ENUM, number=254066049, enum=WeightError,) + annotations = proto.MapField(proto.STRING, proto.STRING, number=112032548,) + health_state = proto.Field( + proto.ENUM, number=324007150, optional=True, enum=HealthState, + ) + instance = proto.Field(proto.STRING, number=18257045, optional=True,) + ip_address = proto.Field(proto.STRING, number=406272220, optional=True,) + port = proto.Field(proto.INT32, number=3446913, optional=True,) + weight = proto.Field(proto.STRING, number=282149496, optional=True,) + weight_error = proto.Field( + proto.ENUM, number=522501505, optional=True, enum=WeightError, + ) class BackendServiceGroupHealth(proto.Message): r""" - Attributes: annotations (Sequence[google.cloud.compute_v1.types.BackendServiceGroupHealth.AnnotationsEntry]): Metadata defined as annotations on the @@ -4730,18 +4569,15 @@ class BackendServiceGroupHealth(proto.Message): services. """ - annotations = proto.MapField(proto.STRING, proto.STRING, number=112032548) - + annotations = proto.MapField(proto.STRING, proto.STRING, number=112032548,) health_status = proto.RepeatedField( - proto.MESSAGE, number=112110389, message="HealthStatus", + proto.MESSAGE, number=380545845, message="HealthStatus", ) - - kind = proto.Field(proto.STRING, number=3292052) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) class BackendServiceList(proto.Message): r"""Contains a list of BackendService resources. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -4768,30 +4604,26 @@ class BackendServiceList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="BackendService", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 BackendServiceReference(proto.Message): r""" - Attributes: backend_service (str): """ - backend_service = proto.Field(proto.STRING, number=38510602) + backend_service = proto.Field(proto.STRING, number=306946058, optional=True,) class Expr(proto.Message): @@ -4846,18 +4678,14 @@ class Expr(proto.Message): expression. """ - description = proto.Field(proto.STRING, number=154502140) - - expression = proto.Field(proto.STRING, number=83595928) - - location = proto.Field(proto.STRING, number=21995445) - - title = proto.Field(proto.STRING, number=110371416) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + expression = proto.Field(proto.STRING, number=352031384, optional=True,) + location = proto.Field(proto.STRING, number=290430901, optional=True,) + title = proto.Field(proto.STRING, number=110371416, optional=True,) class Binding(proto.Message): r"""Associates ``members`` with a ``role``. - Attributes: binding_id (str): @@ -4931,18 +4759,16 @@ class Binding(proto.Message): ``roles/viewer``, ``roles/editor``, or ``roles/owner``. """ - binding_id = proto.Field(proto.STRING, number=172652821) - - condition = proto.Field(proto.MESSAGE, number=212430107, message="Expr",) - - members = proto.RepeatedField(proto.STRING, number=143575321) - - role = proto.Field(proto.STRING, number=3506294) + binding_id = proto.Field(proto.STRING, number=441088277, optional=True,) + condition = proto.Field( + proto.MESSAGE, number=212430107, optional=True, message="Expr", + ) + members = proto.RepeatedField(proto.STRING, number=412010777,) + role = proto.Field(proto.STRING, number=3506294, optional=True,) class CacheInvalidationRule(proto.Message): r""" - Attributes: host (str): If set, this invalidation rule will only @@ -4952,14 +4778,12 @@ class CacheInvalidationRule(proto.Message): """ - host = proto.Field(proto.STRING, number=3208616) - - path = proto.Field(proto.STRING, number=3433509) + host = proto.Field(proto.STRING, number=3208616, optional=True,) + path = proto.Field(proto.STRING, number=3433509, optional=True,) class LicenseResourceCommitment(proto.Message): r"""Commitment for a particular license resource. - Attributes: amount (str): The number of licenses purchased. @@ -4970,11 +4794,9 @@ class LicenseResourceCommitment(proto.Message): Any applicable license URI. """ - amount = proto.Field(proto.STRING, number=196759640) - - cores_per_license = proto.Field(proto.STRING, number=32482324) - - license_ = proto.Field(proto.STRING, number=166757441) + amount = proto.Field(proto.STRING, number=196759640, optional=True,) + cores_per_license = proto.Field(proto.STRING, number=32482324, optional=True,) + license_ = proto.Field(proto.STRING, number=166757441, optional=True,) class Reservation(proto.Message): @@ -5032,35 +4854,30 @@ class Reservation(proto.Message): class Status(proto.Enum): r"""[Output Only] The status of the reservation.""" UNDEFINED_STATUS = 0 - CREATING = 187129529 - DELETING = 260166568 - INVALID = 261848535 + CREATING = 455564985 + DELETING = 528602024 + INVALID = 530283991 READY = 77848963 - UPDATING = 226178886 - - commitment = proto.Field(proto.STRING, number=213699349) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - - self_link = proto.Field(proto.STRING, number=187779341) - + UPDATING = 494614342 + + commitment = proto.Field(proto.STRING, number=482134805, optional=True,) + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, 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,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) specific_reservation = proto.Field( - proto.MESSAGE, number=136466495, message="AllocationSpecificSKUReservation", + proto.MESSAGE, + number=404901951, + optional=True, + message="AllocationSpecificSKUReservation", ) - - specific_reservation_required = proto.Field(proto.BOOL, number=226550687) - - status = proto.Field(proto.ENUM, number=181260274, enum=Status,) - - zone = proto.Field(proto.STRING, number=3744684) + specific_reservation_required = proto.Field( + proto.BOOL, number=226550687, optional=True, + ) + status = proto.Field(proto.ENUM, number=181260274, optional=True, enum=Status,) + zone = proto.Field(proto.STRING, number=3744684, optional=True,) class ResourceCommitment(proto.Message): @@ -5088,17 +4905,15 @@ class Type(proto.Enum): values are VCPU and MEMORY """ UNDEFINED_TYPE = 0 - ACCELERATOR = 161379915 - LOCAL_SSD = 240499440 + ACCELERATOR = 429815371 + LOCAL_SSD = 508934896 MEMORY = 123056385 - UNSPECIFIED = 258350871 + UNSPECIFIED = 526786327 VCPU = 2628978 - accelerator_type = proto.Field(proto.STRING, number=138031246) - - amount = proto.Field(proto.STRING, number=196759640) - - type_ = proto.Field(proto.ENUM, number=3575610, enum=Type,) + accelerator_type = proto.Field(proto.STRING, number=138031246, optional=True,) + amount = proto.Field(proto.STRING, number=196759640, optional=True,) + type_ = proto.Field(proto.ENUM, number=3575610, optional=True, enum=Type,) class Commitment(proto.Message): @@ -5182,9 +4997,9 @@ class Category(proto.Enum): a Type specified. """ UNDEFINED_CATEGORY = 0 - CATEGORY_UNSPECIFIED = 240754006 - LICENSE = 79433761 - MACHINE = 201117735 + CATEGORY_UNSPECIFIED = 509189462 + LICENSE = 347869217 + MACHINE = 469553191 class Plan(proto.Enum): r"""The plan for this commitment, which determines duration and discount @@ -5192,7 +5007,7 @@ class Plan(proto.Enum): THIRTY_SIX_MONTH (3 years). """ UNDEFINED_PLAN = 0 - INVALID = 261848535 + INVALID = 530283991 THIRTY_SIX_MONTH = 266295942 TWELVE_MONTH = 173083962 @@ -5202,53 +5017,40 @@ class Status(proto.Enum): following values: NOT_YET_ACTIVE, ACTIVE, EXPIRED. """ UNDEFINED_STATUS = 0 - ACTIVE = 46297862 - CREATING = 187129529 - EXPIRED = 214053637 + ACTIVE = 314733318 + CREATING = 455564985 + EXPIRED = 482489093 NOT_YET_ACTIVE = 20607337 - category = proto.Field(proto.ENUM, number=50511102, enum=Category,) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - end_timestamp = proto.Field(proto.STRING, number=199661234) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - + category = proto.Field(proto.ENUM, number=50511102, optional=True, enum=Category,) + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + end_timestamp = proto.Field(proto.STRING, number=468096690, optional=True,) + id = proto.Field(proto.STRING, number=3355, optional=True,) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) license_resource = proto.Field( - proto.MESSAGE, number=169519692, message="LicenseResourceCommitment", + proto.MESSAGE, + number=437955148, + optional=True, + message="LicenseResourceCommitment", ) - - name = proto.Field(proto.STRING, number=3373707) - - plan = proto.Field(proto.ENUM, number=3443497, enum=Plan,) - - region = proto.Field(proto.STRING, number=138946292) - + name = proto.Field(proto.STRING, number=3373707, optional=True,) + plan = proto.Field(proto.ENUM, number=3443497, optional=True, enum=Plan,) + region = proto.Field(proto.STRING, number=138946292, optional=True,) reservations = proto.RepeatedField( - proto.MESSAGE, number=131282471, message="Reservation", + proto.MESSAGE, number=399717927, message="Reservation", ) - resources = proto.RepeatedField( proto.MESSAGE, number=164412965, message="ResourceCommitment", ) - - self_link = proto.Field(proto.STRING, number=187779341) - - start_timestamp = proto.Field(proto.STRING, number=83645817) - - status = proto.Field(proto.ENUM, number=181260274, enum=Status,) - - status_message = proto.Field(proto.STRING, number=28992698) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + start_timestamp = proto.Field(proto.STRING, number=83645817, optional=True,) + status = proto.Field(proto.ENUM, number=181260274, optional=True, enum=Status,) + status_message = proto.Field(proto.STRING, number=297428154, optional=True,) class CommitmentsScopedList(proto.Message): r""" - Attributes: commitments (Sequence[google.cloud.compute_v1.types.Commitment]): [Output Only] A list of commitments contained in this scope. @@ -5258,15 +5060,15 @@ class CommitmentsScopedList(proto.Message): """ commitments = proto.RepeatedField( - proto.MESSAGE, number=182228990, message="Commitment", + proto.MESSAGE, number=450664446, message="Commitment", + ) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", ) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) class CommitmentAggregatedList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -5296,26 +5098,21 @@ class CommitmentAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="CommitmentsScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 CommitmentList(proto.Message): r"""Contains a list of Commitment resources. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -5342,22 +5139,18 @@ class CommitmentList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="Commitment",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 Condition(proto.Message): r"""A condition to be met. - Attributes: iam (str): Trusted attributes supplied by the IAM @@ -5374,27 +5167,24 @@ class Condition(proto.Message): The objects of the condition. """ - iam = proto.Field(proto.STRING, number=104021) - - op = proto.Field(proto.STRING, number=3553) - - svc = proto.Field(proto.STRING, number=114272) - - sys = proto.Field(proto.STRING, number=114381) - - values = proto.RepeatedField(proto.STRING, number=249928994) + iam = proto.Field(proto.STRING, number=104021, optional=True,) + op = proto.Field(proto.STRING, number=3553, optional=True,) + svc = proto.Field(proto.STRING, number=114272, optional=True,) + sys = proto.Field(proto.STRING, number=114381, optional=True,) + values = proto.RepeatedField(proto.STRING, number=249928994,) class ConfidentialInstanceConfig(proto.Message): r"""A set of Confidential Instance options. - Attributes: enable_confidential_compute (bool): Defines whether the instance should have confidential compute enabled. """ - enable_confidential_compute = proto.Field(proto.BOOL, number=102135228) + enable_confidential_compute = proto.Field( + proto.BOOL, number=102135228, optional=True, + ) class ConsistentHashLoadBalancerSettingsHttpCookie(proto.Message): @@ -5411,11 +5201,9 @@ class ConsistentHashLoadBalancerSettingsHttpCookie(proto.Message): Lifetime of the cookie. """ - name = proto.Field(proto.STRING, number=3373707) - - path = proto.Field(proto.STRING, number=3433509) - - ttl = proto.Field(proto.MESSAGE, number=115180, message="Duration",) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + path = proto.Field(proto.STRING, number=3433509, optional=True,) + ttl = proto.Field(proto.MESSAGE, number=115180, optional=True, message="Duration",) class Duration(proto.Message): @@ -5437,9 +5225,8 @@ class Duration(proto.Message): days/year \* 10000 years """ - nanos = proto.Field(proto.INT32, number=104586303) - - seconds = proto.Field(proto.STRING, number=91048575) + nanos = proto.Field(proto.INT32, number=104586303, optional=True,) + seconds = proto.Field(proto.STRING, number=359484031, optional=True,) class CorsPolicy(proto.Message): @@ -5486,26 +5273,18 @@ class CorsPolicy(proto.Message): translates to the Access-Control-Max-Age header. """ - allow_credentials = proto.Field(proto.BOOL, number=212827910) - - allow_headers = proto.RepeatedField(proto.STRING, number=45179024) - - allow_methods = proto.RepeatedField(proto.STRING, number=205405372) - - allow_origin_regexes = proto.RepeatedField(proto.STRING, number=215385810) - - allow_origins = proto.RepeatedField(proto.STRING, number=194914071) - - disabled = proto.Field(proto.BOOL, number=2505340) - - expose_headers = proto.RepeatedField(proto.STRING, number=247604747) - - max_age = proto.Field(proto.INT32, number=39123876) + allow_credentials = proto.Field(proto.BOOL, number=481263366, optional=True,) + allow_headers = proto.RepeatedField(proto.STRING, number=45179024,) + allow_methods = proto.RepeatedField(proto.STRING, number=205405372,) + allow_origin_regexes = proto.RepeatedField(proto.STRING, number=215385810,) + allow_origins = proto.RepeatedField(proto.STRING, number=194914071,) + disabled = proto.Field(proto.BOOL, number=270940796, optional=True,) + expose_headers = proto.RepeatedField(proto.STRING, number=247604747,) + max_age = proto.Field(proto.INT32, number=307559332, optional=True,) class CustomerEncryptionKeyProtectedDisk(proto.Message): r""" - Attributes: disk_encryption_key (google.cloud.compute_v1.types.CustomerEncryptionKey): Decrypts data associated with the disk with a @@ -5517,10 +5296,9 @@ class CustomerEncryptionKeyProtectedDisk(proto.Message): """ disk_encryption_key = proto.Field( - proto.MESSAGE, number=3225221, message="CustomerEncryptionKey", + proto.MESSAGE, number=271660677, optional=True, message="CustomerEncryptionKey", ) - - source = proto.Field(proto.STRING, number=177235995) + source = proto.Field(proto.STRING, number=177235995, optional=True,) class Disk(proto.Message): @@ -5746,88 +5524,58 @@ class Status(proto.Enum): DELETING: Disk is deleting. """ UNDEFINED_STATUS = 0 - CREATING = 187129529 - DELETING = 260166568 - FAILED = 187271229 + CREATING = 455564985 + DELETING = 528602024 + FAILED = 455706685 READY = 77848963 - RESTORING = 135828395 - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) + RESTORING = 404263851 + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) disk_encryption_key = proto.Field( - proto.MESSAGE, number=3225221, message="CustomerEncryptionKey", + proto.MESSAGE, number=271660677, optional=True, message="CustomerEncryptionKey", ) - guest_os_features = proto.RepeatedField( proto.MESSAGE, number=79294545, message="GuestOsFeature", ) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - label_fingerprint = proto.Field(proto.STRING, number=178124825) - - labels = proto.MapField(proto.STRING, proto.STRING, number=231759871) - - last_attach_timestamp = proto.Field(proto.STRING, number=42159653) - - last_detach_timestamp = proto.Field(proto.STRING, number=56471027) - - license_codes = proto.RepeatedField(proto.STRING, number=45482664) - - licenses = proto.RepeatedField(proto.STRING, number=69207122) - - name = proto.Field(proto.STRING, number=3373707) - - options = proto.Field(proto.STRING, number=92702366) - - physical_block_size_bytes = proto.Field(proto.STRING, number=151572487) - - region = proto.Field(proto.STRING, number=138946292) - - replica_zones = proto.RepeatedField(proto.STRING, number=48438272) - - resource_policies = proto.RepeatedField(proto.STRING, number=22220385) - - self_link = proto.Field(proto.STRING, number=187779341) - - size_gb = proto.Field(proto.STRING, number=226493913) - - source_disk = proto.Field(proto.STRING, number=183318337) - - source_disk_id = proto.Field(proto.STRING, number=185755353) - - source_image = proto.Field(proto.STRING, number=50443319) - + id = proto.Field(proto.STRING, number=3355, 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,) + last_attach_timestamp = proto.Field(proto.STRING, number=42159653, optional=True,) + 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,) + 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, + ) + 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,) + 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,) + source_disk_id = proto.Field(proto.STRING, number=454190809, optional=True,) + source_image = proto.Field(proto.STRING, number=50443319, optional=True,) source_image_encryption_key = proto.Field( - proto.MESSAGE, number=113068203, message="CustomerEncryptionKey", + proto.MESSAGE, number=381503659, optional=True, message="CustomerEncryptionKey", ) - - source_image_id = proto.Field(proto.STRING, number=55328291) - - source_snapshot = proto.Field(proto.STRING, number=126061928) - + source_image_id = proto.Field(proto.STRING, number=55328291, optional=True,) + source_snapshot = proto.Field(proto.STRING, number=126061928, optional=True,) source_snapshot_encryption_key = proto.Field( - proto.MESSAGE, number=35243866, message="CustomerEncryptionKey", + proto.MESSAGE, number=303679322, optional=True, message="CustomerEncryptionKey", ) - - source_snapshot_id = proto.Field(proto.STRING, number=98962258) - - status = proto.Field(proto.ENUM, number=181260274, enum=Status,) - - type_ = proto.Field(proto.STRING, number=3575610) - - users = proto.RepeatedField(proto.STRING, number=111578632) - - zone = proto.Field(proto.STRING, number=3744684) + source_snapshot_id = proto.Field(proto.STRING, number=98962258, 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,) + zone = proto.Field(proto.STRING, number=3744684, optional=True,) class DisksScopedList(proto.Message): r""" - Attributes: disks (Sequence[google.cloud.compute_v1.types.Disk]): [Output Only] A list of disks contained in this scope. @@ -5837,13 +5585,13 @@ class DisksScopedList(proto.Message): """ disks = proto.RepeatedField(proto.MESSAGE, number=95594102, message="Disk",) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", + ) class DiskAggregatedList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -5873,21 +5621,17 @@ class DiskAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="DisksScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 DiskInstantiationConfig(proto.Message): @@ -5943,7 +5687,7 @@ class InstantiateFrom(proto.Enum): and read-only disks. """ UNDEFINED_INSTANTIATE_FROM = 0 - ATTACH_READ_ONLY = 245339963 + ATTACH_READ_ONLY = 513775419 BLANK = 63281460 CUSTOM_IMAGE = 196311789 DEFAULT = 115302945 @@ -5951,18 +5695,16 @@ class InstantiateFrom(proto.Enum): SOURCE_IMAGE = 62631959 SOURCE_IMAGE_FAMILY = 76850316 - auto_delete = proto.Field(proto.BOOL, number=196325947) - - custom_image = proto.Field(proto.STRING, number=184123149) - - device_name = proto.Field(proto.STRING, number=67541716) - - instantiate_from = proto.Field(proto.ENUM, number=124948447, enum=InstantiateFrom,) + auto_delete = proto.Field(proto.BOOL, number=464761403, optional=True,) + custom_image = proto.Field(proto.STRING, number=184123149, optional=True,) + device_name = proto.Field(proto.STRING, number=67541716, optional=True,) + instantiate_from = proto.Field( + proto.ENUM, number=393383903, optional=True, enum=InstantiateFrom, + ) class DiskList(proto.Message): r"""A list of Disk resources. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -5989,22 +5731,18 @@ class DiskList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="Disk",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 DiskMoveRequest(proto.Message): r""" - Attributes: destination_zone (str): The URL of the destination zone to move the @@ -6023,9 +5761,8 @@ class DiskMoveRequest(proto.Message): - zones/zone/disks/disk """ - destination_zone = proto.Field(proto.STRING, number=131854653) - - target_disk = proto.Field(proto.STRING, number=62433163) + destination_zone = proto.Field(proto.STRING, number=131854653, optional=True,) + target_disk = proto.Field(proto.STRING, number=62433163, optional=True,) class DiskType(proto.Message): @@ -6082,34 +5819,23 @@ class DiskType(proto.Message): It is not settable as a field in the request body. """ - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - default_disk_size_gb = proto.Field(proto.STRING, number=2183797) - + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + default_disk_size_gb = proto.Field(proto.STRING, number=270619253, optional=True,) deprecated = proto.Field( - proto.MESSAGE, number=246703539, message="DeprecationStatus", + proto.MESSAGE, number=515138995, optional=True, message="DeprecationStatus", ) - - description = proto.Field(proto.STRING, number=154502140) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - - region = proto.Field(proto.STRING, number=138946292) - - self_link = proto.Field(proto.STRING, number=187779341) - - valid_disk_size = proto.Field(proto.STRING, number=225527008) - - zone = proto.Field(proto.STRING, number=3744684) + description = proto.Field(proto.STRING, number=422937596, 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,) + region = proto.Field(proto.STRING, number=138946292, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + valid_disk_size = proto.Field(proto.STRING, number=493962464, optional=True,) + zone = proto.Field(proto.STRING, number=3744684, optional=True,) class DiskTypesScopedList(proto.Message): r""" - Attributes: disk_types (Sequence[google.cloud.compute_v1.types.DiskType]): [Output Only] A list of disk types contained in this scope. @@ -6121,13 +5847,13 @@ class DiskTypesScopedList(proto.Message): disk_types = proto.RepeatedField( proto.MESSAGE, number=198926167, message="DiskType", ) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", + ) class DiskTypeAggregatedList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -6156,26 +5882,21 @@ class DiskTypeAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="DiskTypesScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 DiskTypeList(proto.Message): r"""Contains a list of disk types. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -6202,70 +5923,62 @@ class DiskTypeList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="DiskType",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 DisksAddResourcePoliciesRequest(proto.Message): r""" - Attributes: resource_policies (Sequence[str]): Resource policies to be added to this disk. Currently you can only specify one policy here. """ - resource_policies = proto.RepeatedField(proto.STRING, number=22220385) + resource_policies = proto.RepeatedField(proto.STRING, number=22220385,) class DisksRemoveResourcePoliciesRequest(proto.Message): r""" - Attributes: resource_policies (Sequence[str]): Resource policies to be removed from this disk. """ - resource_policies = proto.RepeatedField(proto.STRING, number=22220385) + resource_policies = proto.RepeatedField(proto.STRING, number=22220385,) class DisksResizeRequest(proto.Message): r""" - Attributes: size_gb (str): The new size of the persistent disk, which is specified in GB. """ - size_gb = proto.Field(proto.STRING, number=226493913) + size_gb = proto.Field(proto.STRING, number=494929369, optional=True,) class DisplayDevice(proto.Message): r"""A set of Display Device options - Attributes: enable_display (bool): Defines whether the instance has Display enabled. """ - enable_display = proto.Field(proto.BOOL, number=14266886) + enable_display = proto.Field(proto.BOOL, number=14266886, optional=True,) class DistributionPolicyZoneConfiguration(proto.Message): r""" - Attributes: zone (str): The URL of the zone. The zone must exist in @@ -6273,12 +5986,11 @@ class DistributionPolicyZoneConfiguration(proto.Message): located. """ - zone = proto.Field(proto.STRING, number=3744684) + zone = proto.Field(proto.STRING, number=3744684, optional=True,) class DistributionPolicy(proto.Message): r""" - Attributes: zones (Sequence[google.cloud.compute_v1.types.DistributionPolicyZoneConfiguration]): Zones where the regional managed instance @@ -6292,7 +6004,6 @@ class DistributionPolicy(proto.Message): class ExchangedPeeringRoute(proto.Message): r""" - Attributes: dest_range (str): The destination range of the route. @@ -6316,24 +6027,19 @@ class ExchangedPeeringRoute(proto.Message): class Type(proto.Enum): r"""The type of the peering route.""" UNDEFINED_TYPE = 0 - DYNAMIC_PEERING_ROUTE = 201359402 - STATIC_PEERING_ROUTE = 204972089 - SUBNET_PEERING_ROUTE = 197347048 - - dest_range = proto.Field(proto.STRING, number=112892256) + DYNAMIC_PEERING_ROUTE = 469794858 + STATIC_PEERING_ROUTE = 473407545 + SUBNET_PEERING_ROUTE = 465782504 - imported = proto.Field(proto.BOOL, number=114502404) - - next_hop_region = proto.Field(proto.STRING, number=122577014) - - priority = proto.Field(proto.UINT32, number=176716196) - - type_ = proto.Field(proto.ENUM, number=3575610, enum=Type,) + dest_range = proto.Field(proto.STRING, number=381327712, optional=True,) + imported = proto.Field(proto.BOOL, number=114502404, optional=True,) + next_hop_region = proto.Field(proto.STRING, number=122577014, optional=True,) + priority = proto.Field(proto.UINT32, number=445151652, optional=True,) + type_ = proto.Field(proto.ENUM, number=3575610, optional=True, enum=Type,) class ExchangedPeeringRoutesList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -6361,24 +6067,20 @@ class ExchangedPeeringRoutesList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="ExchangedPeeringRoute", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 ExternalVpnGatewayInterface(proto.Message): r"""The interface for the external VPN gateway. - Attributes: id (int): The numeric ID of this interface. The allowed input values @@ -6394,9 +6096,8 @@ class ExternalVpnGatewayInterface(proto.Message): Engine. """ - id = proto.Field(proto.UINT32, number=3355) - - ip_address = proto.Field(proto.STRING, number=137836764) + id = proto.Field(proto.UINT32, number=3355, optional=True,) + ip_address = proto.Field(proto.STRING, number=406272220, optional=True,) class ExternalVpnGateway(proto.Message): @@ -6470,31 +6171,24 @@ class RedundancyType(proto.Enum): VPN gateway. """ UNDEFINED_REDUNDANCY_TYPE = 0 - FOUR_IPS_REDUNDANCY = 251652457 + FOUR_IPS_REDUNDANCY = 520087913 SINGLE_IP_INTERNALLY_REDUNDANT = 133914873 - TWO_IPS_REDUNDANCY = 98614179 - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - id = proto.Field(proto.STRING, number=3355) + TWO_IPS_REDUNDANCY = 367049635 + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + id = proto.Field(proto.STRING, number=3355, optional=True,) interfaces = proto.RepeatedField( proto.MESSAGE, number=12073562, message="ExternalVpnGatewayInterface", ) - - kind = proto.Field(proto.STRING, number=3292052) - - label_fingerprint = proto.Field(proto.STRING, number=178124825) - - labels = proto.MapField(proto.STRING, proto.STRING, number=231759871) - - name = proto.Field(proto.STRING, number=3373707) - - redundancy_type = proto.Field(proto.ENUM, number=3008284, enum=RedundancyType,) - - self_link = proto.Field(proto.STRING, number=187779341) + 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,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + redundancy_type = proto.Field( + proto.ENUM, number=271443740, optional=True, enum=RedundancyType, + ) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) class ExternalVpnGatewayList(proto.Message): @@ -6530,26 +6224,21 @@ class ExternalVpnGatewayList(proto.Message): def raw_page(self): return self - etag = proto.Field(proto.STRING, number=3123477) - - id = proto.Field(proto.STRING, number=3355) - + etag = proto.Field(proto.STRING, number=3123477, optional=True,) + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="ExternalVpnGateway", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 FileContentBuffer(proto.Message): r""" - Attributes: content (str): The raw content in the secure keys file. @@ -6564,14 +6253,12 @@ class FileType(proto.Enum): UNDEFINED = 137851184 X509 = 2674086 - content = proto.Field(proto.STRING, number=146224249) - - file_type = proto.Field(proto.ENUM, number=25911325, enum=FileType,) + content = proto.Field(proto.STRING, number=414659705, optional=True,) + file_type = proto.Field(proto.ENUM, number=294346781, optional=True, enum=FileType,) class Allowed(proto.Message): r""" - Attributes: i_p_protocol (str): The IP protocol to which this rule applies. @@ -6591,14 +6278,12 @@ class Allowed(proto.Message): ["12345-12349"]. """ - i_p_protocol = proto.Field(proto.STRING, number=55338781) - - ports = proto.RepeatedField(proto.STRING, number=106854418) + i_p_protocol = proto.Field(proto.STRING, number=323774237, optional=True,) + ports = proto.RepeatedField(proto.STRING, number=106854418,) class Denied(proto.Message): r""" - Attributes: i_p_protocol (str): The IP protocol to which this rule applies. @@ -6618,14 +6303,12 @@ class Denied(proto.Message): ["12345-12349"]. """ - i_p_protocol = proto.Field(proto.STRING, number=55338781) - - ports = proto.RepeatedField(proto.STRING, number=106854418) + i_p_protocol = proto.Field(proto.STRING, number=323774237, optional=True,) + ports = proto.RepeatedField(proto.STRING, number=106854418,) class FirewallLogConfig(proto.Message): r"""The available logging options for a firewall rule. - Attributes: enable (bool): This field denotes whether to enable logging @@ -6643,12 +6326,11 @@ class Metadata(proto.Enum): whether to include or exclude metadata for firewall logs. """ UNDEFINED_METADATA = 0 - EXCLUDE_ALL_METADATA = 66084498 + EXCLUDE_ALL_METADATA = 334519954 INCLUDE_ALL_METADATA = 164619908 - enable = proto.Field(proto.BOOL, number=43328899) - - metadata = proto.Field(proto.ENUM, number=86866735, enum=Metadata,) + enable = proto.Field(proto.BOOL, number=311764355, optional=True,) + metadata = proto.Field(proto.ENUM, number=86866735, optional=True, enum=Metadata,) class Firewall(proto.Message): @@ -6809,53 +6491,36 @@ class Direction(proto.Enum): sourceTags fields. """ UNDEFINED_DIRECTION = 0 - EGRESS = 164445045 - INGRESS = 248495765 + EGRESS = 432880501 + INGRESS = 516931221 allowed = proto.RepeatedField(proto.MESSAGE, number=162398632, message="Allowed",) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - denied = proto.RepeatedField(proto.MESSAGE, number=6781851, message="Denied",) - - description = proto.Field(proto.STRING, number=154502140) - - destination_ranges = proto.RepeatedField(proto.STRING, number=37264423) - - direction = proto.Field(proto.ENUM, number=111150975, enum=Direction,) - - disabled = proto.Field(proto.BOOL, number=2505340) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + denied = proto.RepeatedField(proto.MESSAGE, number=275217307, message="Denied",) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + destination_ranges = proto.RepeatedField(proto.STRING, number=305699879,) + direction = proto.Field( + proto.ENUM, number=111150975, optional=True, enum=Direction, + ) + disabled = proto.Field(proto.BOOL, number=270940796, optional=True,) + id = proto.Field(proto.STRING, number=3355, optional=True,) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) log_config = proto.Field( - proto.MESSAGE, number=82864285, message="FirewallLogConfig", + proto.MESSAGE, number=351299741, optional=True, message="FirewallLogConfig", ) - - name = proto.Field(proto.STRING, number=3373707) - - network = proto.Field(proto.STRING, number=232872494) - - priority = proto.Field(proto.INT32, number=176716196) - - self_link = proto.Field(proto.STRING, number=187779341) - - source_ranges = proto.RepeatedField(proto.STRING, number=200097658) - - source_service_accounts = proto.RepeatedField(proto.STRING, number=105100756) - - source_tags = proto.RepeatedField(proto.STRING, number=183786941) - - target_service_accounts = proto.RepeatedField(proto.STRING, number=189204254) - - target_tags = proto.RepeatedField(proto.STRING, number=62901767) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + network = proto.Field(proto.STRING, number=232872494, optional=True,) + priority = proto.Field(proto.INT32, number=445151652, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + source_ranges = proto.RepeatedField(proto.STRING, number=200097658,) + source_service_accounts = proto.RepeatedField(proto.STRING, number=105100756,) + source_tags = proto.RepeatedField(proto.STRING, number=452222397,) + target_service_accounts = proto.RepeatedField(proto.STRING, number=457639710,) + target_tags = proto.RepeatedField(proto.STRING, number=62901767,) class FirewallList(proto.Message): r"""Contains a list of firewalls. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -6882,17 +6547,14 @@ class FirewallList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="Firewall",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 MetadataFilter(proto.Message): @@ -6946,11 +6608,10 @@ class FilterMatchCriteria(proto.Enum): NOT_SET = 163646646 filter_labels = proto.RepeatedField( - proto.MESSAGE, number=39467686, message="MetadataFilterLabelMatch", + proto.MESSAGE, number=307903142, message="MetadataFilterLabelMatch", ) - filter_match_criteria = proto.Field( - proto.ENUM, number=239970368, enum=FilterMatchCriteria, + proto.ENUM, number=239970368, optional=True, enum=FilterMatchCriteria, ) @@ -7312,10 +6973,10 @@ class LoadBalancingScheme(proto.Enum): """ UNDEFINED_LOAD_BALANCING_SCHEME = 0 EXTERNAL = 35607499 - INTERNAL = 10860221 + INTERNAL = 279295677 INTERNAL_MANAGED = 37350397 INTERNAL_SELF_MANAGED = 236211150 - INVALID = 261848535 + INVALID = 530283991 class NetworkTier(proto.Enum): r"""This signifies the networking tier used for configuring this @@ -7328,67 +6989,48 @@ class NetworkTier(proto.Enum): networkTier of the Address. """ UNDEFINED_NETWORK_TIER = 0 - PREMIUM = 131095095 - STANDARD = 216207037 - - all_ports = proto.Field(proto.BOOL, number=176740340) - - allow_global_access = proto.Field(proto.BOOL, number=230974218) - - backend_service = proto.Field(proto.STRING, number=38510602) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - fingerprint = proto.Field(proto.STRING, number=234678500) - - i_p_address = proto.Field(proto.STRING, number=254156495) - - i_p_protocol = proto.Field(proto.ENUM, number=55338781, enum=IPProtocol,) - - id = proto.Field(proto.STRING, number=3355) - - ip_version = proto.Field(proto.ENUM, number=26524096, enum=IpVersion,) - - is_mirroring_collector = proto.Field(proto.BOOL, number=119255164) - - kind = proto.Field(proto.STRING, number=3292052) - + PREMIUM = 399530551 + STANDARD = 484642493 + + 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,) load_balancing_scheme = proto.Field( - proto.ENUM, number=95454788, enum=LoadBalancingScheme, + proto.ENUM, number=363890244, optional=True, enum=LoadBalancingScheme, ) - metadata_filters = proto.RepeatedField( - proto.MESSAGE, number=196290283, message="MetadataFilter", + proto.MESSAGE, number=464725739, message="MetadataFilter", ) - - name = proto.Field(proto.STRING, number=3373707) - - network = proto.Field(proto.STRING, number=232872494) - - network_tier = proto.Field(proto.ENUM, number=248962387, enum=NetworkTier,) - - port_range = proto.Field(proto.STRING, number=217518079) - - ports = proto.RepeatedField(proto.STRING, number=106854418) - - region = proto.Field(proto.STRING, number=138946292) - - self_link = proto.Field(proto.STRING, number=187779341) - - service_label = proto.Field(proto.STRING, number=148573418) - - service_name = proto.Field(proto.STRING, number=91444693) - - subnetwork = proto.Field(proto.STRING, number=39392238) - - target = proto.Field(proto.STRING, number=192835985) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + network = proto.Field(proto.STRING, number=232872494, optional=True,) + network_tier = proto.Field( + proto.ENUM, number=517397843, optional=True, enum=NetworkTier, + ) + port_range = proto.Field(proto.STRING, number=217518079, optional=True,) + ports = proto.RepeatedField(proto.STRING, number=106854418,) + region = proto.Field(proto.STRING, number=138946292, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + 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,) + target = proto.Field(proto.STRING, number=192835985, optional=True,) class ForwardingRulesScopedList(proto.Message): r""" - Attributes: forwarding_rules (Sequence[google.cloud.compute_v1.types.ForwardingRule]): A list of forwarding rules contained in this @@ -7399,15 +7041,15 @@ class ForwardingRulesScopedList(proto.Message): """ forwarding_rules = proto.RepeatedField( - proto.MESSAGE, number=47385909, message="ForwardingRule", + proto.MESSAGE, number=315821365, message="ForwardingRule", + ) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", ) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) class ForwardingRuleAggregatedList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -7438,29 +7080,24 @@ class ForwardingRuleAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="ForwardingRulesScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 ForwardingRuleList(proto.Message): r"""Contains a list of ForwardingRule resources. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -7486,35 +7123,30 @@ class ForwardingRuleList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="ForwardingRule", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 ForwardingRuleReference(proto.Message): r""" - Attributes: forwarding_rule (str): """ - forwarding_rule = proto.Field(proto.STRING, number=1528574) + forwarding_rule = proto.Field(proto.STRING, number=269964030, optional=True,) class GRPCHealthCheck(proto.Message): r""" - Attributes: grpc_service_name (str): The gRPC service name for the health check. This field is @@ -7563,23 +7195,19 @@ class PortSpecification(proto.Enum): """ UNDEFINED_PORT_SPECIFICATION = 0 USE_FIXED_PORT = 190235748 - USE_NAMED_PORT = 80865215 - USE_SERVING_PORT = 94202060 - - grpc_service_name = proto.Field(proto.STRING, number=136533078) - - port = proto.Field(proto.INT32, number=3446913) - - port_name = proto.Field(proto.STRING, number=41534345) + USE_NAMED_PORT = 349300671 + USE_SERVING_PORT = 362637516 + grpc_service_name = proto.Field(proto.STRING, number=136533078, optional=True,) + port = proto.Field(proto.INT32, number=3446913, optional=True,) + port_name = proto.Field(proto.STRING, number=41534345, optional=True,) port_specification = proto.Field( - proto.ENUM, number=51590597, enum=PortSpecification, + proto.ENUM, number=51590597, optional=True, enum=PortSpecification, ) class NetworkEndpoint(proto.Message): r"""The network endpoint. - Attributes: annotations (Sequence[google.cloud.compute_v1.types.NetworkEndpoint.AnnotationsEntry]): Metadata defined as annotations on the @@ -7612,20 +7240,15 @@ class NetworkEndpoint(proto.Message): will be used. """ - annotations = proto.MapField(proto.STRING, proto.STRING, number=112032548) - - fqdn = proto.Field(proto.STRING, number=3150485) - - instance = proto.Field(proto.STRING, number=18257045) - - ip_address = proto.Field(proto.STRING, number=137836764) - - port = proto.Field(proto.INT32, number=3446913) + annotations = proto.MapField(proto.STRING, proto.STRING, number=112032548,) + fqdn = proto.Field(proto.STRING, number=3150485, optional=True,) + instance = proto.Field(proto.STRING, number=18257045, optional=True,) + ip_address = proto.Field(proto.STRING, number=406272220, optional=True,) + port = proto.Field(proto.INT32, number=3446913, optional=True,) class GlobalNetworkEndpointGroupsAttachEndpointsRequest(proto.Message): r""" - Attributes: network_endpoints (Sequence[google.cloud.compute_v1.types.NetworkEndpoint]): The list of network endpoints to be attached. @@ -7638,7 +7261,6 @@ class GlobalNetworkEndpointGroupsAttachEndpointsRequest(proto.Message): class GlobalNetworkEndpointGroupsDetachEndpointsRequest(proto.Message): r""" - Attributes: network_endpoints (Sequence[google.cloud.compute_v1.types.NetworkEndpoint]): The list of network endpoints to be detached. @@ -7651,7 +7273,6 @@ class GlobalNetworkEndpointGroupsDetachEndpointsRequest(proto.Message): class GlobalSetLabelsRequest(proto.Message): r""" - Attributes: label_fingerprint (str): The fingerprint of the previous set of labels @@ -7676,9 +7297,8 @@ class GlobalSetLabelsRequest(proto.Message): can also be empty (e.g. "my-label": ""). """ - label_fingerprint = proto.Field(proto.STRING, number=178124825) - - labels = proto.MapField(proto.STRING, proto.STRING, number=231759871) + label_fingerprint = proto.Field(proto.STRING, number=178124825, optional=True,) + labels = proto.MapField(proto.STRING, proto.STRING, number=500195327,) class Policy(proto.Message): @@ -7796,23 +7416,17 @@ class Policy(proto.Message): """ audit_configs = proto.RepeatedField( - proto.MESSAGE, number=59645197, message="AuditConfig", + proto.MESSAGE, number=328080653, message="AuditConfig", ) - - bindings = proto.RepeatedField(proto.MESSAGE, number=134816398, message="Binding",) - - etag = proto.Field(proto.STRING, number=3123477) - - iam_owned = proto.Field(proto.BOOL, number=182130747) - + bindings = proto.RepeatedField(proto.MESSAGE, number=403251854, message="Binding",) + etag = proto.Field(proto.STRING, number=3123477, optional=True,) + iam_owned = proto.Field(proto.BOOL, number=450566203, optional=True,) rules = proto.RepeatedField(proto.MESSAGE, number=108873975, message="Rule",) - - version = proto.Field(proto.INT32, number=83172568) + version = proto.Field(proto.INT32, number=351608024, optional=True,) class GlobalSetPolicyRequest(proto.Message): r""" - Attributes: bindings (Sequence[google.cloud.compute_v1.types.Binding]): Flatten Policy to create a backward @@ -7830,16 +7444,15 @@ class GlobalSetPolicyRequest(proto.Message): (like Projects) might reject them. """ - bindings = proto.RepeatedField(proto.MESSAGE, number=134816398, message="Binding",) - - etag = proto.Field(proto.STRING, number=3123477) - - policy = proto.Field(proto.MESSAGE, number=91071794, message="Policy",) + 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 GuestAttributesValue(proto.Message): r"""Array of guest attribute namespace/key/value tuples. - Attributes: items (Sequence[google.cloud.compute_v1.types.GuestAttributesEntry]): @@ -7852,7 +7465,6 @@ class GuestAttributesValue(proto.Message): class GuestAttributes(proto.Message): r"""A guest attributes entry. - Attributes: kind (str): [Output Only] Type of the resource. Always @@ -7871,24 +7483,18 @@ class GuestAttributes(proto.Message): [Output Only] The value found for the requested key. """ - kind = proto.Field(proto.STRING, number=3292052) - - query_path = proto.Field(proto.STRING, number=100155708) - + kind = proto.Field(proto.STRING, number=3292052, optional=True,) + query_path = proto.Field(proto.STRING, number=368591164, optional=True,) query_value = proto.Field( - proto.MESSAGE, number=157570874, message="GuestAttributesValue", + proto.MESSAGE, number=157570874, optional=True, message="GuestAttributesValue", ) - - self_link = proto.Field(proto.STRING, number=187779341) - - variable_key = proto.Field(proto.STRING, number=164364828) - - variable_value = proto.Field(proto.STRING, number=124582382) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + variable_key = proto.Field(proto.STRING, number=164364828, optional=True,) + variable_value = proto.Field(proto.STRING, number=124582382, optional=True,) class GuestAttributesEntry(proto.Message): r"""A guest attributes namespace/key/value entry. - Attributes: key (str): Key for the guest attribute entry. @@ -7898,16 +7504,13 @@ class GuestAttributesEntry(proto.Message): Value for the guest attribute entry. """ - key = proto.Field(proto.STRING, number=106079) - - namespace = proto.Field(proto.STRING, number=178476379) - - value = proto.Field(proto.STRING, number=111972721) + key = proto.Field(proto.STRING, number=106079, optional=True,) + namespace = proto.Field(proto.STRING, number=178476379, optional=True,) + value = proto.Field(proto.STRING, number=111972721, optional=True,) class HTTP2HealthCheck(proto.Message): r""" - Attributes: host (str): The value of the host header in the HTTP/2 @@ -7961,8 +7564,8 @@ class PortSpecification(proto.Enum): """ UNDEFINED_PORT_SPECIFICATION = 0 USE_FIXED_PORT = 190235748 - USE_NAMED_PORT = 80865215 - USE_SERVING_PORT = 94202060 + USE_NAMED_PORT = 349300671 + USE_SERVING_PORT = 362637516 class ProxyHeader(proto.Enum): r"""Specifies the type of proxy header to append before sending data to @@ -7970,28 +7573,23 @@ class ProxyHeader(proto.Enum): """ UNDEFINED_PROXY_HEADER = 0 NONE = 2402104 - PROXY_V1 = 65917484 - - host = proto.Field(proto.STRING, number=3208616) - - port = proto.Field(proto.INT32, number=3446913) - - port_name = proto.Field(proto.STRING, number=41534345) + PROXY_V1 = 334352940 + host = proto.Field(proto.STRING, number=3208616, optional=True,) + port = proto.Field(proto.INT32, number=3446913, optional=True,) + port_name = proto.Field(proto.STRING, number=41534345, optional=True,) port_specification = proto.Field( - proto.ENUM, number=51590597, enum=PortSpecification, + proto.ENUM, number=51590597, optional=True, enum=PortSpecification, ) - - proxy_header = proto.Field(proto.ENUM, number=160374142, enum=ProxyHeader,) - - request_path = proto.Field(proto.STRING, number=229403605) - - response = proto.Field(proto.STRING, number=196547649) + proxy_header = proto.Field( + proto.ENUM, number=160374142, optional=True, enum=ProxyHeader, + ) + request_path = proto.Field(proto.STRING, number=229403605, optional=True,) + response = proto.Field(proto.STRING, number=196547649, optional=True,) class HTTPHealthCheck(proto.Message): r""" - Attributes: host (str): The value of the host header in the HTTP @@ -8045,8 +7643,8 @@ class PortSpecification(proto.Enum): """ UNDEFINED_PORT_SPECIFICATION = 0 USE_FIXED_PORT = 190235748 - USE_NAMED_PORT = 80865215 - USE_SERVING_PORT = 94202060 + USE_NAMED_PORT = 349300671 + USE_SERVING_PORT = 362637516 class ProxyHeader(proto.Enum): r"""Specifies the type of proxy header to append before sending data to @@ -8054,28 +7652,23 @@ class ProxyHeader(proto.Enum): """ UNDEFINED_PROXY_HEADER = 0 NONE = 2402104 - PROXY_V1 = 65917484 - - host = proto.Field(proto.STRING, number=3208616) - - port = proto.Field(proto.INT32, number=3446913) - - port_name = proto.Field(proto.STRING, number=41534345) + PROXY_V1 = 334352940 + host = proto.Field(proto.STRING, number=3208616, optional=True,) + port = proto.Field(proto.INT32, number=3446913, optional=True,) + port_name = proto.Field(proto.STRING, number=41534345, optional=True,) port_specification = proto.Field( - proto.ENUM, number=51590597, enum=PortSpecification, + proto.ENUM, number=51590597, optional=True, enum=PortSpecification, ) - - proxy_header = proto.Field(proto.ENUM, number=160374142, enum=ProxyHeader,) - - request_path = proto.Field(proto.STRING, number=229403605) - - response = proto.Field(proto.STRING, number=196547649) + proxy_header = proto.Field( + proto.ENUM, number=160374142, optional=True, enum=ProxyHeader, + ) + request_path = proto.Field(proto.STRING, number=229403605, optional=True,) + response = proto.Field(proto.STRING, number=196547649, optional=True,) class HTTPSHealthCheck(proto.Message): r""" - Attributes: host (str): The value of the host header in the HTTPS @@ -8129,8 +7722,8 @@ class PortSpecification(proto.Enum): """ UNDEFINED_PORT_SPECIFICATION = 0 USE_FIXED_PORT = 190235748 - USE_NAMED_PORT = 80865215 - USE_SERVING_PORT = 94202060 + USE_NAMED_PORT = 349300671 + USE_SERVING_PORT = 362637516 class ProxyHeader(proto.Enum): r"""Specifies the type of proxy header to append before sending data to @@ -8138,23 +7731,19 @@ class ProxyHeader(proto.Enum): """ UNDEFINED_PROXY_HEADER = 0 NONE = 2402104 - PROXY_V1 = 65917484 - - host = proto.Field(proto.STRING, number=3208616) - - port = proto.Field(proto.INT32, number=3446913) - - port_name = proto.Field(proto.STRING, number=41534345) + PROXY_V1 = 334352940 + host = proto.Field(proto.STRING, number=3208616, optional=True,) + port = proto.Field(proto.INT32, number=3446913, optional=True,) + port_name = proto.Field(proto.STRING, number=41534345, optional=True,) port_specification = proto.Field( - proto.ENUM, number=51590597, enum=PortSpecification, + proto.ENUM, number=51590597, optional=True, enum=PortSpecification, ) - - proxy_header = proto.Field(proto.ENUM, number=160374142, enum=ProxyHeader,) - - request_path = proto.Field(proto.STRING, number=229403605) - - response = proto.Field(proto.STRING, number=196547649) + proxy_header = proto.Field( + proto.ENUM, number=160374142, optional=True, enum=ProxyHeader, + ) + request_path = proto.Field(proto.STRING, number=229403605, optional=True,) + response = proto.Field(proto.STRING, number=196547649, optional=True,) class HealthCheckLogConfig(proto.Message): @@ -8168,12 +7757,11 @@ class HealthCheckLogConfig(proto.Message): logging will be done. """ - enable = proto.Field(proto.BOOL, number=43328899) + enable = proto.Field(proto.BOOL, number=311764355, optional=True,) class SSLHealthCheck(proto.Message): r""" - Attributes: port (int): The TCP port number for the health check @@ -8226,8 +7814,8 @@ class PortSpecification(proto.Enum): """ UNDEFINED_PORT_SPECIFICATION = 0 USE_FIXED_PORT = 190235748 - USE_NAMED_PORT = 80865215 - USE_SERVING_PORT = 94202060 + USE_NAMED_PORT = 349300671 + USE_SERVING_PORT = 362637516 class ProxyHeader(proto.Enum): r"""Specifies the type of proxy header to append before sending data to @@ -8235,26 +7823,22 @@ class ProxyHeader(proto.Enum): """ UNDEFINED_PROXY_HEADER = 0 NONE = 2402104 - PROXY_V1 = 65917484 - - port = proto.Field(proto.INT32, number=3446913) - - port_name = proto.Field(proto.STRING, number=41534345) + PROXY_V1 = 334352940 + port = proto.Field(proto.INT32, number=3446913, optional=True,) + port_name = proto.Field(proto.STRING, number=41534345, optional=True,) port_specification = proto.Field( - proto.ENUM, number=51590597, enum=PortSpecification, + proto.ENUM, number=51590597, optional=True, enum=PortSpecification, ) - - proxy_header = proto.Field(proto.ENUM, number=160374142, enum=ProxyHeader,) - - request = proto.Field(proto.STRING, number=21951119) - - response = proto.Field(proto.STRING, number=196547649) + proxy_header = proto.Field( + proto.ENUM, number=160374142, optional=True, enum=ProxyHeader, + ) + request = proto.Field(proto.STRING, number=21951119, optional=True,) + response = proto.Field(proto.STRING, number=196547649, optional=True,) class TCPHealthCheck(proto.Message): r""" - Attributes: port (int): The TCP port number for the health check @@ -8307,8 +7891,8 @@ class PortSpecification(proto.Enum): """ UNDEFINED_PORT_SPECIFICATION = 0 USE_FIXED_PORT = 190235748 - USE_NAMED_PORT = 80865215 - USE_SERVING_PORT = 94202060 + USE_NAMED_PORT = 349300671 + USE_SERVING_PORT = 362637516 class ProxyHeader(proto.Enum): r"""Specifies the type of proxy header to append before sending data to @@ -8316,21 +7900,18 @@ class ProxyHeader(proto.Enum): """ UNDEFINED_PROXY_HEADER = 0 NONE = 2402104 - PROXY_V1 = 65917484 - - port = proto.Field(proto.INT32, number=3446913) - - port_name = proto.Field(proto.STRING, number=41534345) + PROXY_V1 = 334352940 + port = proto.Field(proto.INT32, number=3446913, optional=True,) + port_name = proto.Field(proto.STRING, number=41534345, optional=True,) port_specification = proto.Field( - proto.ENUM, number=51590597, enum=PortSpecification, + proto.ENUM, number=51590597, optional=True, enum=PortSpecification, ) - - proxy_header = proto.Field(proto.ENUM, number=160374142, enum=ProxyHeader,) - - request = proto.Field(proto.STRING, number=21951119) - - response = proto.Field(proto.STRING, number=196547649) + proxy_header = proto.Field( + proto.ENUM, number=160374142, optional=True, enum=ProxyHeader, + ) + request = proto.Field(proto.STRING, number=21951119, optional=True,) + response = proto.Field(proto.STRING, number=196547649, optional=True,) class HealthCheck(proto.Message): @@ -8436,66 +8017,47 @@ class Type(proto.Enum): HTTP = 2228360 HTTP2 = 69079210 HTTPS = 69079243 - INVALID = 261848535 + INVALID = 530283991 SSL = 82412 TCP = 82881 - check_interval_sec = proto.Field(proto.INT32, number=77125550) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - + check_interval_sec = proto.Field(proto.INT32, number=345561006, optional=True,) + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) grpc_health_check = proto.Field( - proto.MESSAGE, number=85529574, message="GRPCHealthCheck", + proto.MESSAGE, number=85529574, optional=True, message="GRPCHealthCheck", ) - - healthy_threshold = proto.Field(proto.INT32, number=134776905) - + healthy_threshold = proto.Field(proto.INT32, number=403212361, optional=True,) http2_health_check = proto.Field( - proto.MESSAGE, number=11360986, message="HTTP2HealthCheck", + proto.MESSAGE, number=11360986, optional=True, message="HTTP2HealthCheck", ) - http_health_check = proto.Field( - proto.MESSAGE, number=144151484, message="HTTPHealthCheck", + proto.MESSAGE, number=412586940, optional=True, message="HTTPHealthCheck", ) - https_health_check = proto.Field( - proto.MESSAGE, number=167611449, message="HTTPSHealthCheck", + proto.MESSAGE, number=436046905, optional=True, message="HTTPSHealthCheck", ) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - + id = proto.Field(proto.STRING, number=3355, optional=True,) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) log_config = proto.Field( - proto.MESSAGE, number=82864285, message="HealthCheckLogConfig", + proto.MESSAGE, number=351299741, optional=True, message="HealthCheckLogConfig", ) - - name = proto.Field(proto.STRING, number=3373707) - - region = proto.Field(proto.STRING, number=138946292) - - self_link = proto.Field(proto.STRING, number=187779341) - + name = proto.Field(proto.STRING, number=3373707, optional=True,) + region = proto.Field(proto.STRING, number=138946292, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) ssl_health_check = proto.Field( - proto.MESSAGE, number=11596984, message="SSLHealthCheck", + proto.MESSAGE, number=280032440, optional=True, message="SSLHealthCheck", ) - tcp_health_check = proto.Field( - proto.MESSAGE, number=201544963, message="TCPHealthCheck", + proto.MESSAGE, number=469980419, optional=True, message="TCPHealthCheck", ) - - timeout_sec = proto.Field(proto.INT32, number=79994995) - - type_ = proto.Field(proto.ENUM, number=3575610, enum=Type,) - - unhealthy_threshold = proto.Field(proto.INT32, number=227958480) + timeout_sec = proto.Field(proto.INT32, number=79994995, optional=True,) + type_ = proto.Field(proto.ENUM, number=3575610, optional=True, enum=Type,) + unhealthy_threshold = proto.Field(proto.INT32, number=227958480, optional=True,) class HealthCheckList(proto.Message): r"""Contains a list of HealthCheck resources. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -8521,17 +8083,14 @@ class HealthCheckList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="HealthCheck",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 HealthCheckReference(proto.Message): @@ -8547,7 +8106,7 @@ class HealthCheckReference(proto.Message): """ - health_check = proto.Field(proto.STRING, number=40441189) + health_check = proto.Field(proto.STRING, number=308876645, optional=True,) class HealthCheckService(proto.Message): @@ -8647,33 +8206,22 @@ class HealthStatusAggregationPolicy(proto.Enum): """ UNDEFINED_HEALTH_STATUS_AGGREGATION_POLICY = 0 AND = 64951 - NO_AGGREGATION = 158009668 - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - fingerprint = proto.Field(proto.STRING, number=234678500) - - health_checks = proto.RepeatedField(proto.STRING, number=179935150) + NO_AGGREGATION = 426445124 + 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,) + health_checks = proto.RepeatedField(proto.STRING, number=448370606,) health_status_aggregation_policy = proto.Field( - proto.ENUM, number=253163129, enum=HealthStatusAggregationPolicy, + proto.ENUM, number=253163129, optional=True, enum=HealthStatusAggregationPolicy, ) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - - network_endpoint_groups = proto.RepeatedField(proto.STRING, number=29346733) - - notification_endpoints = proto.RepeatedField(proto.STRING, number=138293034) - - region = proto.Field(proto.STRING, number=138946292) - - self_link = proto.Field(proto.STRING, number=187779341) + 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,) + network_endpoint_groups = proto.RepeatedField(proto.STRING, number=29346733,) + notification_endpoints = proto.RepeatedField(proto.STRING, number=406728490,) + region = proto.Field(proto.STRING, number=138946292, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) class HealthCheckServiceReference(proto.Message): @@ -8690,12 +8238,11 @@ class HealthCheckServiceReference(proto.Message): """ - health_check_service = proto.Field(proto.STRING, number=139939291) + health_check_service = proto.Field(proto.STRING, number=408374747, optional=True,) class HealthCheckServicesList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -8723,24 +8270,20 @@ class HealthCheckServicesList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="HealthCheckService", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 HealthChecksScopedList(proto.Message): r""" - Attributes: health_checks (Sequence[google.cloud.compute_v1.types.HealthCheck]): A list of HealthChecks contained in this @@ -8751,15 +8294,15 @@ class HealthChecksScopedList(proto.Message): """ health_checks = proto.RepeatedField( - proto.MESSAGE, number=179935150, message="HealthCheck", + proto.MESSAGE, number=448370606, message="HealthCheck", + ) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", ) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) class HealthChecksAggregatedList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -8787,26 +8330,21 @@ class HealthChecksAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="HealthChecksScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 HealthStatusForNetworkEndpoint(proto.Message): r""" - Attributes: backend_service (google.cloud.compute_v1.types.BackendServiceReference): URL of the backend service associated with @@ -8831,28 +8369,35 @@ class HealthState(proto.Enum): health checks configured. """ UNDEFINED_HEALTH_STATE = 0 - DRAINING = 212019946 - HEALTHY = 171365757 - UNHEALTHY = 193682628 - UNKNOWN = 164706346 + DRAINING = 480455402 + HEALTHY = 439801213 + UNHEALTHY = 462118084 + UNKNOWN = 433141802 backend_service = proto.Field( - proto.MESSAGE, number=38510602, message="BackendServiceReference", + proto.MESSAGE, + number=306946058, + optional=True, + message="BackendServiceReference", ) - forwarding_rule = proto.Field( - proto.MESSAGE, number=1528574, message="ForwardingRuleReference", + proto.MESSAGE, + number=269964030, + optional=True, + message="ForwardingRuleReference", ) - health_check = proto.Field( - proto.MESSAGE, number=40441189, message="HealthCheckReference", + proto.MESSAGE, number=308876645, optional=True, message="HealthCheckReference", ) - health_check_service = proto.Field( - proto.MESSAGE, number=139939291, message="HealthCheckServiceReference", + proto.MESSAGE, + number=408374747, + optional=True, + message="HealthCheckServiceReference", + ) + health_state = proto.Field( + proto.ENUM, number=324007150, optional=True, enum=HealthState, ) - - health_state = proto.Field(proto.ENUM, number=55571694, enum=HealthState,) class HostRule(proto.Message): @@ -8880,11 +8425,9 @@ class HostRule(proto.Message): matches the URL's host portion. """ - description = proto.Field(proto.STRING, number=154502140) - - hosts = proto.RepeatedField(proto.STRING, number=99467211) - - path_matcher = proto.Field(proto.STRING, number=69377816) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + hosts = proto.RepeatedField(proto.STRING, number=99467211,) + path_matcher = proto.Field(proto.STRING, number=337813272, optional=True,) class HttpFaultAbort(proto.Message): @@ -8903,9 +8446,8 @@ class HttpFaultAbort(proto.Message): must be between 0.0 and 100.0 inclusive. """ - http_status = proto.Field(proto.UINT32, number=200514441) - - percentage = proto.Field(proto.DOUBLE, number=151909018) + http_status = proto.Field(proto.UINT32, number=468949897, optional=True,) + percentage = proto.Field(proto.DOUBLE, number=151909018, optional=True,) class HttpFaultDelay(proto.Message): @@ -8925,9 +8467,10 @@ class HttpFaultDelay(proto.Message): inclusive. """ - fixed_delay = proto.Field(proto.MESSAGE, number=48602360, message="Duration",) - - percentage = proto.Field(proto.DOUBLE, number=151909018) + fixed_delay = proto.Field( + proto.MESSAGE, number=317037816, optional=True, message="Duration", + ) + percentage = proto.Field(proto.DOUBLE, number=151909018, optional=True,) class HttpFaultInjection(proto.Message): @@ -8949,9 +8492,12 @@ class HttpFaultInjection(proto.Message): sent to a backend service. """ - abort = proto.Field(proto.MESSAGE, number=92611376, message="HttpFaultAbort",) - - delay = proto.Field(proto.MESSAGE, number=95467907, message="HttpFaultDelay",) + abort = proto.Field( + proto.MESSAGE, number=92611376, optional=True, message="HttpFaultAbort", + ) + delay = proto.Field( + proto.MESSAGE, number=95467907, optional=True, message="HttpFaultDelay", + ) class HttpHeaderOption(proto.Message): @@ -8971,11 +8517,9 @@ class HttpHeaderOption(proto.Message): header. The default value is false. """ - header_name = proto.Field(proto.STRING, number=110223613) - - header_value = proto.Field(proto.STRING, number=203094335) - - replace = proto.Field(proto.BOOL, number=20755124) + header_name = proto.Field(proto.STRING, number=110223613, optional=True,) + header_value = proto.Field(proto.STRING, number=203094335, optional=True,) + replace = proto.Field(proto.BOOL, number=20755124, optional=True,) class HttpHeaderAction(proto.Message): @@ -9003,14 +8547,11 @@ class HttpHeaderAction(proto.Message): request_headers_to_add = proto.RepeatedField( proto.MESSAGE, number=72111974, message="HttpHeaderOption", ) - - request_headers_to_remove = proto.RepeatedField(proto.STRING, number=218425247) - + request_headers_to_remove = proto.RepeatedField(proto.STRING, number=218425247,) response_headers_to_add = proto.RepeatedField( proto.MESSAGE, number=32136052, message="HttpHeaderOption", ) - - response_headers_to_remove = proto.RepeatedField(proto.STRING, number=75415761) + response_headers_to_remove = proto.RepeatedField(proto.STRING, number=75415761,) class Int64RangeMatch(proto.Message): @@ -9026,14 +8567,12 @@ class Int64RangeMatch(proto.Message): long integer format. """ - range_end = proto.Field(proto.STRING, number=54004441) - - range_start = proto.Field(proto.STRING, number=103333600) + range_end = proto.Field(proto.STRING, number=322439897, optional=True,) + range_start = proto.Field(proto.STRING, number=103333600, optional=True,) class HttpHeaderMatch(proto.Message): r"""matchRule criteria for request header matches. - Attributes: exact_match (str): The value should exactly match contents of @@ -9104,28 +8643,20 @@ class HttpHeaderMatch(proto.Message): presentMatch or rangeMatch must be set. """ - exact_match = proto.Field(proto.STRING, number=189205637) - - header_name = proto.Field(proto.STRING, number=110223613) - - invert_match = proto.Field(proto.BOOL, number=232694812) - - prefix_match = proto.Field(proto.STRING, number=257898968) - - present_match = proto.Field(proto.BOOL, number=67435841) - + exact_match = proto.Field(proto.STRING, number=457641093, optional=True,) + header_name = proto.Field(proto.STRING, number=110223613, optional=True,) + invert_match = proto.Field(proto.BOOL, number=501130268, optional=True,) + prefix_match = proto.Field(proto.STRING, number=257898968, optional=True,) + present_match = proto.Field(proto.BOOL, number=67435841, optional=True,) range_match = proto.Field( - proto.MESSAGE, number=97244227, message="Int64RangeMatch", + proto.MESSAGE, number=97244227, optional=True, message="Int64RangeMatch", ) - - regex_match = proto.Field(proto.STRING, number=107387853) - - suffix_match = proto.Field(proto.STRING, number=158053207) + regex_match = proto.Field(proto.STRING, number=107387853, optional=True,) + suffix_match = proto.Field(proto.STRING, number=426488663, optional=True,) class HttpQueryParameterMatch(proto.Message): r"""HttpRouteRuleMatch criteria for a request's query parameter. - Attributes: exact_match (str): The queryParameterMatch matches if the value @@ -9152,18 +8683,14 @@ class HttpQueryParameterMatch(proto.Message): set to INTERNAL_SELF_MANAGED. """ - exact_match = proto.Field(proto.STRING, number=189205637) - - name = proto.Field(proto.STRING, number=3373707) - - present_match = proto.Field(proto.BOOL, number=67435841) - - regex_match = proto.Field(proto.STRING, number=107387853) + exact_match = proto.Field(proto.STRING, number=457641093, optional=True,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + present_match = proto.Field(proto.BOOL, number=67435841, optional=True,) + regex_match = proto.Field(proto.STRING, number=107387853, optional=True,) class HttpRedirectAction(proto.Message): r"""Specifies settings for an HTTP redirect. - Attributes: host_redirect (str): The host that will be used in the redirect @@ -9233,29 +8760,23 @@ class RedirectResponseCode(proto.Enum): """ UNDEFINED_REDIRECT_RESPONSE_CODE = 0 FOUND = 67084130 - MOVED_PERMANENTLY_DEFAULT = 118262993 - PERMANENT_REDIRECT = 113570925 - SEE_OTHER = 176945124 - TEMPORARY_REDIRECT = 221114922 - - host_redirect = proto.Field(proto.STRING, number=107417747) - - https_redirect = proto.Field(proto.BOOL, number=170260656) - - path_redirect = proto.Field(proto.STRING, number=3907254) - - prefix_redirect = proto.Field(proto.STRING, number=177748713) - + MOVED_PERMANENTLY_DEFAULT = 386698449 + PERMANENT_REDIRECT = 382006381 + SEE_OTHER = 445380580 + TEMPORARY_REDIRECT = 489550378 + + host_redirect = proto.Field(proto.STRING, number=107417747, optional=True,) + https_redirect = proto.Field(proto.BOOL, number=170260656, optional=True,) + path_redirect = proto.Field(proto.STRING, number=272342710, optional=True,) + prefix_redirect = proto.Field(proto.STRING, number=446184169, optional=True,) redirect_response_code = proto.Field( - proto.ENUM, number=168274952, enum=RedirectResponseCode, + proto.ENUM, number=436710408, optional=True, enum=RedirectResponseCode, ) - - strip_query = proto.Field(proto.BOOL, number=52284641) + strip_query = proto.Field(proto.BOOL, number=52284641, optional=True,) class HttpRetryPolicy(proto.Message): r"""The retry policy associates with HttpRouteRule - Attributes: num_retries (int): Specifies the allowed number retries. This @@ -9301,11 +8822,11 @@ class HttpRetryPolicy(proto.Message): code in the response header is set to unavailable """ - num_retries = proto.Field(proto.UINT32, number=251680141) - - per_try_timeout = proto.Field(proto.MESSAGE, number=11605691, message="Duration",) - - retry_conditions = proto.RepeatedField(proto.STRING, number=28815535) + num_retries = proto.Field(proto.UINT32, number=251680141, optional=True,) + per_try_timeout = proto.Field( + proto.MESSAGE, number=280041147, optional=True, message="Duration", + ) + retry_conditions = proto.RepeatedField(proto.STRING, number=28815535,) class RequestMirrorPolicy(proto.Message): @@ -9321,7 +8842,7 @@ class RequestMirrorPolicy(proto.Message): resource being mirrored to. """ - backend_service = proto.Field(proto.STRING, number=38510602) + backend_service = proto.Field(proto.STRING, number=306946058, optional=True,) class UrlRewrite(proto.Message): @@ -9342,9 +8863,8 @@ class UrlRewrite(proto.Message): and 1024 characters. """ - host_rewrite = proto.Field(proto.STRING, number=159819253) - - path_prefix_rewrite = proto.Field(proto.STRING, number=41186361) + host_rewrite = proto.Field(proto.STRING, number=159819253, optional=True,) + path_prefix_rewrite = proto.Field(proto.STRING, number=41186361, optional=True,) class WeightedBackendService(proto.Message): @@ -9387,18 +8907,15 @@ class WeightedBackendService(proto.Message): 1000 """ - backend_service = proto.Field(proto.STRING, number=38510602) - + backend_service = proto.Field(proto.STRING, number=306946058, optional=True,) header_action = proto.Field( - proto.MESSAGE, number=59641896, message="HttpHeaderAction", + proto.MESSAGE, number=328077352, optional=True, message="HttpHeaderAction", ) - - weight = proto.Field(proto.UINT32, number=13714040) + weight = proto.Field(proto.UINT32, number=282149496, optional=True,) class HttpRouteAction(proto.Message): r""" - Attributes: cors_policy (google.cloud.compute_v1.types.CorsPolicy): The specification for allowing client side @@ -9469,26 +8986,26 @@ class HttpRouteAction(proto.Message): this HttpRouteAction. """ - cors_policy = proto.Field(proto.MESSAGE, number=130508292, message="CorsPolicy",) - + cors_policy = proto.Field( + proto.MESSAGE, number=398943748, optional=True, message="CorsPolicy", + ) fault_injection_policy = proto.Field( - proto.MESSAGE, number=144345623, message="HttpFaultInjection", + proto.MESSAGE, number=412781079, optional=True, message="HttpFaultInjection", ) - request_mirror_policy = proto.Field( - proto.MESSAGE, number=220196866, message="RequestMirrorPolicy", + proto.MESSAGE, number=220196866, optional=True, message="RequestMirrorPolicy", ) - retry_policy = proto.Field( - proto.MESSAGE, number=56799913, message="HttpRetryPolicy", + proto.MESSAGE, number=56799913, optional=True, message="HttpRetryPolicy", + ) + timeout = proto.Field( + proto.MESSAGE, number=296701281, optional=True, message="Duration", + ) + url_rewrite = proto.Field( + proto.MESSAGE, number=273333948, optional=True, message="UrlRewrite", ) - - timeout = proto.Field(proto.MESSAGE, number=28265825, message="Duration",) - - url_rewrite = proto.Field(proto.MESSAGE, number=4898492, message="UrlRewrite",) - weighted_backend_services = proto.RepeatedField( - proto.MESSAGE, number=68592593, message="WeightedBackendService", + proto.MESSAGE, number=337028049, message="WeightedBackendService", ) @@ -9562,25 +9079,19 @@ class HttpRouteRuleMatch(proto.Message): their loadBalancingScheme set to INTERNAL_SELF_MANAGED. """ - full_path_match = proto.Field(proto.STRING, number=214598875) - + full_path_match = proto.Field(proto.STRING, number=214598875, optional=True,) header_matches = proto.RepeatedField( - proto.MESSAGE, number=93468033, message="HttpHeaderMatch", + proto.MESSAGE, number=361903489, message="HttpHeaderMatch", ) - - ignore_case = proto.Field(proto.BOOL, number=195889533) - + ignore_case = proto.Field(proto.BOOL, number=464324989, optional=True,) metadata_filters = proto.RepeatedField( - proto.MESSAGE, number=196290283, message="MetadataFilter", + proto.MESSAGE, number=464725739, message="MetadataFilter", ) - - prefix_match = proto.Field(proto.STRING, number=257898968) - + prefix_match = proto.Field(proto.STRING, number=257898968, optional=True,) query_parameter_matches = proto.RepeatedField( - proto.MESSAGE, number=17795814, message="HttpQueryParameterMatch", + proto.MESSAGE, number=286231270, message="HttpQueryParameterMatch", ) - - regex_match = proto.Field(proto.STRING, number=107387853) + regex_match = proto.Field(proto.STRING, number=107387853, optional=True,) class HttpRouteRule(proto.Message): @@ -9665,32 +9176,25 @@ class HttpRouteRule(proto.Message): is bound to target gRPC proxy. """ - description = proto.Field(proto.STRING, number=154502140) - + description = proto.Field(proto.STRING, number=422937596, optional=True,) header_action = proto.Field( - proto.MESSAGE, number=59641896, message="HttpHeaderAction", + proto.MESSAGE, number=328077352, optional=True, message="HttpHeaderAction", ) - match_rules = proto.RepeatedField( - proto.MESSAGE, number=107765245, message="HttpRouteRuleMatch", + proto.MESSAGE, number=376200701, message="HttpRouteRuleMatch", ) - - priority = proto.Field(proto.INT32, number=176716196) - + priority = proto.Field(proto.INT32, number=445151652, optional=True,) route_action = proto.Field( - proto.MESSAGE, number=156128492, message="HttpRouteAction", + proto.MESSAGE, number=424563948, optional=True, message="HttpRouteAction", ) - - service = proto.Field(proto.STRING, number=105105077) - + service = proto.Field(proto.STRING, number=373540533, optional=True,) url_redirect = proto.Field( - proto.MESSAGE, number=136712364, message="HttpRedirectAction", + proto.MESSAGE, number=405147820, optional=True, message="HttpRedirectAction", ) class RawDisk(proto.Message): r"""The parameters of the raw disk image. - Attributes: container_type (google.cloud.compute_v1.types.RawDisk.ContainerType): The format used to encode and transmit the @@ -9718,11 +9222,11 @@ class ContainerType(proto.Enum): UNDEFINED_CONTAINER_TYPE = 0 TAR = 82821 - container_type = proto.Field(proto.ENUM, number=50373688, enum=ContainerType,) - - sha1_checksum = proto.Field(proto.STRING, number=46008893) - - source = proto.Field(proto.STRING, number=177235995) + container_type = proto.Field( + proto.ENUM, number=318809144, optional=True, enum=ContainerType, + ) + sha1_checksum = proto.Field(proto.STRING, number=314444349, optional=True,) + source = proto.Field(proto.STRING, number=177235995, optional=True,) class Image(proto.Message): @@ -9900,89 +9404,63 @@ class Status(proto.Enum): values are FAILED, PENDING, or READY. """ UNDEFINED_STATUS = 0 - DELETING = 260166568 - FAILED = 187271229 + DELETING = 528602024 + FAILED = 455706685 PENDING = 35394935 READY = 77848963 - archive_size_bytes = proto.Field(proto.STRING, number=112657994) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - + archive_size_bytes = proto.Field(proto.STRING, number=381093450, optional=True,) + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) deprecated = proto.Field( - proto.MESSAGE, number=246703539, message="DeprecationStatus", + proto.MESSAGE, number=515138995, optional=True, message="DeprecationStatus", ) - - description = proto.Field(proto.STRING, number=154502140) - - disk_size_gb = proto.Field(proto.STRING, number=47828279) - - family = proto.Field(proto.STRING, number=60316516) - + description = proto.Field(proto.STRING, number=422937596, optional=True,) + disk_size_gb = proto.Field(proto.STRING, number=316263735, optional=True,) + family = proto.Field(proto.STRING, number=328751972, optional=True,) guest_os_features = proto.RepeatedField( proto.MESSAGE, number=79294545, message="GuestOsFeature", ) - - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) image_encryption_key = proto.Field( - proto.MESSAGE, number=111077127, message="CustomerEncryptionKey", - ) - - kind = proto.Field(proto.STRING, number=3292052) - - label_fingerprint = proto.Field(proto.STRING, number=178124825) - - labels = proto.MapField(proto.STRING, proto.STRING, number=231759871) - - license_codes = proto.RepeatedField(proto.STRING, number=45482664) - - licenses = proto.RepeatedField(proto.STRING, number=69207122) - - name = proto.Field(proto.STRING, number=3373707) - - raw_disk = proto.Field(proto.MESSAGE, number=234678100, message="RawDisk",) - - self_link = proto.Field(proto.STRING, number=187779341) - + proto.MESSAGE, number=379512583, optional=True, message="CustomerEncryptionKey", + ) + 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,) + license_codes = proto.RepeatedField(proto.STRING, number=45482664,) + licenses = proto.RepeatedField(proto.STRING, number=337642578,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + raw_disk = proto.Field( + proto.MESSAGE, number=503113556, optional=True, message="RawDisk", + ) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) shielded_instance_initial_state = proto.Field( - proto.MESSAGE, number=192356867, message="InitialStateConfig", + proto.MESSAGE, number=192356867, optional=True, message="InitialStateConfig", ) - - source_disk = proto.Field(proto.STRING, number=183318337) - + source_disk = proto.Field(proto.STRING, number=451753793, optional=True,) source_disk_encryption_key = proto.Field( - proto.MESSAGE, number=263065697, message="CustomerEncryptionKey", + proto.MESSAGE, number=531501153, optional=True, message="CustomerEncryptionKey", ) - - source_disk_id = proto.Field(proto.STRING, number=185755353) - - source_image = proto.Field(proto.STRING, number=50443319) - + source_disk_id = proto.Field(proto.STRING, number=454190809, optional=True,) + source_image = proto.Field(proto.STRING, number=50443319, optional=True,) source_image_encryption_key = proto.Field( - proto.MESSAGE, number=113068203, message="CustomerEncryptionKey", + proto.MESSAGE, number=381503659, optional=True, message="CustomerEncryptionKey", ) - - source_image_id = proto.Field(proto.STRING, number=55328291) - - source_snapshot = proto.Field(proto.STRING, number=126061928) - + source_image_id = proto.Field(proto.STRING, number=55328291, optional=True,) + source_snapshot = proto.Field(proto.STRING, number=126061928, optional=True,) source_snapshot_encryption_key = proto.Field( - proto.MESSAGE, number=35243866, message="CustomerEncryptionKey", + proto.MESSAGE, number=303679322, optional=True, message="CustomerEncryptionKey", ) - - source_snapshot_id = proto.Field(proto.STRING, number=98962258) - - source_type = proto.Field(proto.ENUM, number=183810270, enum=SourceType,) - - status = proto.Field(proto.ENUM, number=181260274, enum=Status,) - - storage_locations = proto.RepeatedField(proto.STRING, number=59569818) + source_snapshot_id = proto.Field(proto.STRING, number=98962258, optional=True,) + source_type = proto.Field( + proto.ENUM, number=452245726, optional=True, enum=SourceType, + ) + status = proto.Field(proto.ENUM, number=181260274, optional=True, enum=Status,) + storage_locations = proto.RepeatedField(proto.STRING, number=328005274,) class ImageList(proto.Message): r"""Contains a list of images. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -10008,22 +9486,18 @@ class ImageList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="Image",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 Metadata(proto.Message): r"""A metadata key/value entry. - Attributes: fingerprint (str): Specifies a fingerprint for this request, @@ -10045,16 +9519,13 @@ class Metadata(proto.Message): for metadata. """ - fingerprint = proto.Field(proto.STRING, number=234678500) - + fingerprint = proto.Field(proto.STRING, number=234678500, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="Items",) - - kind = proto.Field(proto.STRING, number=3292052) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) class NetworkInterface(proto.Message): r"""A network interface resource attached to an instance. - Attributes: access_configs (Sequence[google.cloud.compute_v1.types.AccessConfig]): An array of configurations for this interface. Currently, @@ -10125,31 +9596,22 @@ class NicType(proto.Enum): UNDEFINED_NIC_TYPE = 0 GVNIC = 68209305 UNSPECIFIED_NIC_TYPE = 67411801 - VIRTIO_NET = 183688025 + VIRTIO_NET = 452123481 access_configs = proto.RepeatedField( proto.MESSAGE, number=111058326, message="AccessConfig", ) - alias_ip_ranges = proto.RepeatedField( proto.MESSAGE, number=165085631, message="AliasIpRange", ) - - fingerprint = proto.Field(proto.STRING, number=234678500) - - ipv6_address = proto.Field(proto.STRING, number=73128348) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - - network = proto.Field(proto.STRING, number=232872494) - - network_i_p = proto.Field(proto.STRING, number=207181961) - - nic_type = proto.Field(proto.ENUM, number=59810577, enum=NicType,) - - subnetwork = proto.Field(proto.STRING, number=39392238) + fingerprint = proto.Field(proto.STRING, number=234678500, optional=True,) + ipv6_address = proto.Field(proto.STRING, number=341563804, optional=True,) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + network = proto.Field(proto.STRING, number=232872494, optional=True,) + network_i_p = proto.Field(proto.STRING, number=207181961, optional=True,) + nic_type = proto.Field(proto.ENUM, number=59810577, optional=True, enum=NicType,) + subnetwork = proto.Field(proto.STRING, number=307827694, optional=True,) class ReservationAffinity(proto.Message): @@ -10181,20 +9643,17 @@ class ConsumeReservationType(proto.Enum): ANY_RESERVATION = 200008121 NO_RESERVATION = 169322030 SPECIFIC_RESERVATION = 229889055 - UNSPECIFIED = 258350871 + UNSPECIFIED = 526786327 consume_reservation_type = proto.Field( - proto.ENUM, number=32301488, enum=ConsumeReservationType, + proto.ENUM, number=300736944, optional=True, enum=ConsumeReservationType, ) - - key = proto.Field(proto.STRING, number=106079) - - values = proto.RepeatedField(proto.STRING, number=249928994) + key = proto.Field(proto.STRING, number=106079, optional=True,) + values = proto.RepeatedField(proto.STRING, number=249928994,) class Scheduling(proto.Message): r"""Sets the scheduling options for an Instance. NextID: 13 - Attributes: automatic_restart (bool): Specifies whether the instance should be @@ -10243,28 +9702,22 @@ class OnHostMaintenance(proto.Enum): """ UNDEFINED_ON_HOST_MAINTENANCE = 0 MIGRATE = 165699979 - TERMINATE = 259182145 - - automatic_restart = proto.Field(proto.BOOL, number=82385915) - - location_hint = proto.Field(proto.STRING, number=82084049) - - min_node_cpus = proto.Field(proto.INT32, number=48796219) + TERMINATE = 527617601 + automatic_restart = proto.Field(proto.BOOL, number=350821371, optional=True,) + location_hint = proto.Field(proto.STRING, number=350519505, optional=True,) + min_node_cpus = proto.Field(proto.INT32, number=317231675, optional=True,) node_affinities = proto.RepeatedField( - proto.MESSAGE, number=193364515, message="SchedulingNodeAffinity", + proto.MESSAGE, number=461799971, message="SchedulingNodeAffinity", ) - on_host_maintenance = proto.Field( - proto.ENUM, number=64616796, enum=OnHostMaintenance, + proto.ENUM, number=64616796, optional=True, enum=OnHostMaintenance, ) - - preemptible = proto.Field(proto.BOOL, number=55767713) + preemptible = proto.Field(proto.BOOL, number=324203169, optional=True,) class ServiceAccount(proto.Message): r"""A service account. - Attributes: email (str): Email address of the service account. @@ -10273,14 +9726,12 @@ class ServiceAccount(proto.Message): this service account. """ - email = proto.Field(proto.STRING, number=96619420) - - scopes = proto.RepeatedField(proto.STRING, number=165973151) + email = proto.Field(proto.STRING, number=96619420, optional=True,) + scopes = proto.RepeatedField(proto.STRING, number=165973151,) class ShieldedInstanceConfig(proto.Message): r"""A set of Shielded Instance options. - Attributes: enable_integrity_monitoring (bool): Defines whether the instance has integrity @@ -10293,11 +9744,11 @@ class ShieldedInstanceConfig(proto.Message): enabled. Enabled by default. """ - enable_integrity_monitoring = proto.Field(proto.BOOL, number=140635574) - - enable_secure_boot = proto.Field(proto.BOOL, number=123568638) - - enable_vtpm = proto.Field(proto.BOOL, number=181858935) + enable_integrity_monitoring = proto.Field( + proto.BOOL, number=409071030, optional=True, + ) + enable_secure_boot = proto.Field(proto.BOOL, number=123568638, optional=True,) + enable_vtpm = proto.Field(proto.BOOL, number=181858935, optional=True,) class ShieldedInstanceIntegrityPolicy(proto.Message): @@ -10311,12 +9762,11 @@ class ShieldedInstanceIntegrityPolicy(proto.Message): recent boot. """ - update_auto_learn_policy = proto.Field(proto.BOOL, number=245490215) + update_auto_learn_policy = proto.Field(proto.BOOL, number=245490215, optional=True,) class Tags(proto.Message): r"""A set of instance tags. - Attributes: fingerprint (str): Specifies a fingerprint for this request, @@ -10333,9 +9783,8 @@ class Tags(proto.Message): characters long, and comply with RFC1035. """ - fingerprint = proto.Field(proto.STRING, number=234678500) - - items = proto.RepeatedField(proto.STRING, number=100526016) + fingerprint = proto.Field(proto.STRING, number=234678500, optional=True,) + items = proto.RepeatedField(proto.STRING, number=100526016,) class Instance(proto.Message): @@ -10522,9 +9971,9 @@ class PrivateIpv6GoogleAccess(proto.Enum): use INHERIT_FROM_SUBNETWORK as default. """ UNDEFINED_PRIVATE_IPV6_GOOGLE_ACCESS = 0 - ENABLE_BIDIRECTIONAL_ACCESS_TO_GOOGLE = 159540538 - ENABLE_OUTBOUND_VM_ACCESS_TO_GOOGLE = 19774807 - INHERIT_FROM_SUBNETWORK = 261821503 + ENABLE_BIDIRECTIONAL_ACCESS_TO_GOOGLE = 427975994 + ENABLE_OUTBOUND_VM_ACCESS_TO_GOOGLE = 288210263 + INHERIT_FROM_SUBNETWORK = 530256959 class Status(proto.Enum): r"""[Output Only] The status of the instance. One of the following @@ -10533,111 +9982,87 @@ class Status(proto.Enum): status of the instance, see Instance life cycle. """ UNDEFINED_STATUS = 0 - DEPROVISIONING = 160500206 - PROVISIONING = 22461165 - REPAIRING = 145047829 + DEPROVISIONING = 428935662 + PROVISIONING = 290896621 + REPAIRING = 413483285 RUNNING = 121282975 - STAGING = 162636827 - STOPPED = 175840685 - STOPPING = 82356340 + STAGING = 431072283 + STOPPED = 444276141 + STOPPING = 350791796 SUSPENDED = 51223995 - SUSPENDING = 245770790 + SUSPENDING = 514206246 TERMINATED = 250018339 - can_ip_forward = proto.Field(proto.BOOL, number=199295868) - + can_ip_forward = proto.Field(proto.BOOL, number=467731324, optional=True,) confidential_instance_config = proto.Field( - proto.MESSAGE, number=222202229, message="ConfidentialInstanceConfig", - ) - - cpu_platform = proto.Field(proto.STRING, number=141849898) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - deletion_protection = proto.Field(proto.BOOL, number=189579242) - - description = proto.Field(proto.STRING, number=154502140) - + proto.MESSAGE, + number=490637685, + optional=True, + message="ConfidentialInstanceConfig", + ) + cpu_platform = proto.Field(proto.STRING, number=410285354, optional=True,) + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + deletion_protection = proto.Field(proto.BOOL, number=458014698, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) disks = proto.RepeatedField(proto.MESSAGE, number=95594102, message="AttachedDisk",) - display_device = proto.Field( - proto.MESSAGE, number=258933875, message="DisplayDevice", + proto.MESSAGE, number=258933875, optional=True, message="DisplayDevice", ) - - fingerprint = proto.Field(proto.STRING, number=234678500) - + fingerprint = proto.Field(proto.STRING, number=234678500, optional=True,) guest_accelerators = proto.RepeatedField( - proto.MESSAGE, number=195159663, message="AcceleratorConfig", - ) - - hostname = proto.Field(proto.STRING, number=237067315) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - label_fingerprint = proto.Field(proto.STRING, number=178124825) - - labels = proto.MapField(proto.STRING, proto.STRING, number=231759871) - - last_start_timestamp = proto.Field(proto.STRING, number=175395280) - - last_stop_timestamp = proto.Field(proto.STRING, number=144387554) - - last_suspended_timestamp = proto.Field(proto.STRING, number=87839881) - - machine_type = proto.Field(proto.STRING, number=227711026) - - metadata = proto.Field(proto.MESSAGE, number=86866735, message="Metadata",) - - min_cpu_platform = proto.Field(proto.STRING, number=242912759) - - name = proto.Field(proto.STRING, number=3373707) - + proto.MESSAGE, number=463595119, message="AcceleratorConfig", + ) + hostname = proto.Field(proto.STRING, number=237067315, optional=True,) + id = proto.Field(proto.STRING, number=3355, 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,) + last_start_timestamp = proto.Field(proto.STRING, number=443830736, optional=True,) + last_stop_timestamp = proto.Field(proto.STRING, number=412823010, optional=True,) + last_suspended_timestamp = proto.Field( + proto.STRING, number=356275337, optional=True, + ) + 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,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) network_interfaces = proto.RepeatedField( proto.MESSAGE, number=52735243, message="NetworkInterface", ) - private_ipv6_google_access = proto.Field( - proto.ENUM, number=48277006, enum=PrivateIpv6GoogleAccess, + proto.ENUM, number=48277006, optional=True, enum=PrivateIpv6GoogleAccess, ) - reservation_affinity = proto.Field( - proto.MESSAGE, number=157850683, message="ReservationAffinity", + proto.MESSAGE, number=157850683, optional=True, message="ReservationAffinity", ) - - resource_policies = proto.RepeatedField(proto.STRING, number=22220385) - - scheduling = proto.Field(proto.MESSAGE, number=118252948, message="Scheduling",) - - self_link = proto.Field(proto.STRING, number=187779341) - + resource_policies = proto.RepeatedField(proto.STRING, number=22220385,) + scheduling = proto.Field( + proto.MESSAGE, number=386688404, optional=True, message="Scheduling", + ) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) service_accounts = proto.RepeatedField( - proto.MESSAGE, number=9101872, message="ServiceAccount", + proto.MESSAGE, number=277537328, message="ServiceAccount", ) - shielded_instance_config = proto.Field( - proto.MESSAGE, number=12862901, message="ShieldedInstanceConfig", + proto.MESSAGE, number=12862901, optional=True, message="ShieldedInstanceConfig", ) - shielded_instance_integrity_policy = proto.Field( - proto.MESSAGE, number=163696919, message="ShieldedInstanceIntegrityPolicy", + proto.MESSAGE, + number=163696919, + optional=True, + message="ShieldedInstanceIntegrityPolicy", ) - - start_restricted = proto.Field(proto.BOOL, number=123693144) - - status = proto.Field(proto.ENUM, number=181260274, enum=Status,) - - status_message = proto.Field(proto.STRING, number=28992698) - - tags = proto.Field(proto.MESSAGE, number=3552281, message="Tags",) - - zone = proto.Field(proto.STRING, number=3744684) + start_restricted = proto.Field(proto.BOOL, number=123693144, optional=True,) + status = proto.Field(proto.ENUM, number=181260274, optional=True, enum=Status,) + status_message = proto.Field(proto.STRING, number=297428154, optional=True,) + tags = proto.Field(proto.MESSAGE, number=3552281, optional=True, message="Tags",) + zone = proto.Field(proto.STRING, number=3744684, optional=True,) class InstancesScopedList(proto.Message): r""" - Attributes: instances (Sequence[google.cloud.compute_v1.types.Instance]): [Output Only] A list of instances contained in this scope. @@ -10647,13 +10072,13 @@ class InstancesScopedList(proto.Message): """ instances = proto.RepeatedField(proto.MESSAGE, number=29097598, message="Instance",) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", + ) class InstanceAggregatedList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -10684,26 +10109,21 @@ class InstanceAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="InstancesScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 NamedPort(proto.Message): r"""The named port. For example: . - Attributes: name (str): The name for this named port. The name must @@ -10714,9 +10134,8 @@ class NamedPort(proto.Message): 1 and 65535. """ - name = proto.Field(proto.STRING, number=3373707) - - port = proto.Field(proto.INT32, number=3446913) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + port = proto.Field(proto.INT32, number=3446913, optional=True,) class InstanceGroup(proto.Message): @@ -10798,38 +10217,25 @@ class InstanceGroup(proto.Message): is located (for zonal resources). """ - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - fingerprint = proto.Field(proto.STRING, number=234678500) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - + 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,) named_ports = proto.RepeatedField( - proto.MESSAGE, number=159163276, message="NamedPort", + proto.MESSAGE, number=427598732, message="NamedPort", ) - - network = proto.Field(proto.STRING, number=232872494) - - region = proto.Field(proto.STRING, number=138946292) - - self_link = proto.Field(proto.STRING, number=187779341) - - size = proto.Field(proto.INT32, number=3530753) - - subnetwork = proto.Field(proto.STRING, number=39392238) - - zone = proto.Field(proto.STRING, number=3744684) + network = proto.Field(proto.STRING, number=232872494, optional=True,) + region = proto.Field(proto.STRING, number=138946292, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + size = proto.Field(proto.INT32, number=3530753, optional=True,) + subnetwork = proto.Field(proto.STRING, number=307827694, optional=True,) + zone = proto.Field(proto.STRING, number=3744684, optional=True,) class InstanceGroupsScopedList(proto.Message): r""" - Attributes: instance_groups (Sequence[google.cloud.compute_v1.types.InstanceGroup]): [Output Only] The list of instance groups that are contained @@ -10840,15 +10246,15 @@ class InstanceGroupsScopedList(proto.Message): """ instance_groups = proto.RepeatedField( - proto.MESSAGE, number=98033854, message="InstanceGroup", + proto.MESSAGE, number=366469310, message="InstanceGroup", + ) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", ) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) class InstanceGroupAggregatedList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -10878,29 +10284,24 @@ class InstanceGroupAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="InstanceGroupsScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 InstanceGroupList(proto.Message): r"""A list of InstanceGroup resources. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -10927,24 +10328,20 @@ class InstanceGroupList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="InstanceGroup", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 InstanceGroupManagerAutoHealingPolicy(proto.Message): r""" - Attributes: health_check (str): The URL for the health check that signals @@ -10960,14 +10357,12 @@ class InstanceGroupManagerAutoHealingPolicy(proto.Message): 3600]. """ - health_check = proto.Field(proto.STRING, number=40441189) - - initial_delay_sec = proto.Field(proto.INT32, number=263207002) + health_check = proto.Field(proto.STRING, number=308876645, optional=True,) + initial_delay_sec = proto.Field(proto.INT32, number=263207002, optional=True,) class InstanceGroupManagerActionsSummary(proto.Message): r""" - Attributes: abandoning (int): [Output Only] The total number of instances in the managed @@ -11021,41 +10416,36 @@ class InstanceGroupManagerActionsSummary(proto.Message): listManagedInstances method documentation. """ - abandoning = proto.Field(proto.INT32, number=171587917) - - creating = proto.Field(proto.INT32, number=209809081) - - creating_without_retries = proto.Field(proto.INT32, number=101481289) - - deleting = proto.Field(proto.INT32, number=14410664) - - none = proto.Field(proto.INT32, number=3387192) - - recreating = proto.Field(proto.INT32, number=70621676) - - refreshing = proto.Field(proto.INT32, number=215044903) - - restarting = proto.Field(proto.INT32, number=103877491) - - verifying = proto.Field(proto.INT32, number=183177417) + abandoning = proto.Field(proto.INT32, number=440023373, optional=True,) + creating = proto.Field(proto.INT32, number=209809081, optional=True,) + creating_without_retries = proto.Field( + proto.INT32, number=369916745, optional=True, + ) + deleting = proto.Field(proto.INT32, number=282846120, optional=True,) + none = proto.Field(proto.INT32, number=3387192, optional=True,) + recreating = proto.Field(proto.INT32, number=339057132, optional=True,) + refreshing = proto.Field(proto.INT32, number=215044903, optional=True,) + restarting = proto.Field(proto.INT32, number=372312947, optional=True,) + verifying = proto.Field(proto.INT32, number=451612873, optional=True,) class StatefulPolicy(proto.Message): r""" - Attributes: preserved_state (google.cloud.compute_v1.types.StatefulPolicyPreservedState): """ preserved_state = proto.Field( - proto.MESSAGE, number=2634026, message="StatefulPolicyPreservedState", + proto.MESSAGE, + number=2634026, + optional=True, + message="StatefulPolicyPreservedState", ) class InstanceGroupManagerStatus(proto.Message): r""" - Attributes: autoscaler (str): [Output Only] The URL of the Autoscaler that targets this @@ -11077,24 +10467,24 @@ class InstanceGroupManagerStatus(proto.Message): Instance Group Manager. """ - autoscaler = proto.Field(proto.STRING, number=248823511) - - is_stable = proto.Field(proto.BOOL, number=108410864) - + autoscaler = proto.Field(proto.STRING, number=517258967, optional=True,) + is_stable = proto.Field(proto.BOOL, number=108410864, optional=True,) stateful = proto.Field( - proto.MESSAGE, number=244462412, message="InstanceGroupManagerStatusStateful", + proto.MESSAGE, + number=244462412, + optional=True, + message="InstanceGroupManagerStatusStateful", ) - version_target = proto.Field( proto.MESSAGE, - number=20950744, + number=289386200, + optional=True, message="InstanceGroupManagerStatusVersionTarget", ) class InstanceGroupManagerUpdatePolicy(proto.Message): r""" - Attributes: instance_redistribution_type (str): The instance redistribution policy for @@ -11159,24 +10549,22 @@ class InstanceGroupManagerUpdatePolicy(proto.Message): recreateInstances calls). """ - instance_redistribution_type = proto.Field(proto.STRING, number=24194968) - - max_surge = proto.Field(proto.MESSAGE, number=34137235, message="FixedOrPercent",) - + instance_redistribution_type = proto.Field( + proto.STRING, number=292630424, optional=True, + ) + max_surge = proto.Field( + proto.MESSAGE, number=302572691, optional=True, message="FixedOrPercent", + ) max_unavailable = proto.Field( - proto.MESSAGE, number=136504821, message="FixedOrPercent", + proto.MESSAGE, number=404940277, optional=True, message="FixedOrPercent", ) - - minimal_action = proto.Field(proto.STRING, number=2131604) - - replacement_method = proto.Field(proto.STRING, number=237496238) - - type_ = proto.Field(proto.STRING, number=3575610) + minimal_action = proto.Field(proto.STRING, number=270567060, optional=True,) + replacement_method = proto.Field(proto.STRING, number=505931694, optional=True,) + type_ = proto.Field(proto.STRING, number=3575610, optional=True,) class InstanceGroupManagerVersion(proto.Message): r""" - Attributes: instance_template (str): The URL of the instance template that is specified for this @@ -11209,11 +10597,11 @@ class InstanceGroupManagerVersion(proto.Message): information. """ - instance_template = proto.Field(proto.STRING, number=40812772) - - name = proto.Field(proto.STRING, number=3373707) - - target_size = proto.Field(proto.MESSAGE, number=62880239, message="FixedOrPercent",) + instance_template = proto.Field(proto.STRING, number=309248228, optional=True,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + target_size = proto.Field( + proto.MESSAGE, number=62880239, optional=True, message="FixedOrPercent", + ) class InstanceGroupManager(proto.Message): @@ -11337,70 +10725,57 @@ class InstanceGroupManager(proto.Message): auto_healing_policies = proto.RepeatedField( proto.MESSAGE, - number=188363653, + number=456799109, message="InstanceGroupManagerAutoHealingPolicy", ) - - base_instance_name = proto.Field(proto.STRING, number=120670983) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - + base_instance_name = proto.Field(proto.STRING, number=389106439, optional=True,) + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) current_actions = proto.Field( - proto.MESSAGE, number=164045879, message="InstanceGroupManagerActionsSummary", + proto.MESSAGE, + number=164045879, + optional=True, + message="InstanceGroupManagerActionsSummary", ) - - description = proto.Field(proto.STRING, number=154502140) - + description = proto.Field(proto.STRING, number=422937596, optional=True,) distribution_policy = proto.Field( - proto.MESSAGE, number=266123085, message="DistributionPolicy", - ) - - fingerprint = proto.Field(proto.STRING, number=234678500) - - id = proto.Field(proto.STRING, number=3355) - - instance_group = proto.Field(proto.STRING, number=81095253) - - instance_template = proto.Field(proto.STRING, number=40812772) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - + proto.MESSAGE, number=534558541, optional=True, message="DistributionPolicy", + ) + fingerprint = proto.Field(proto.STRING, number=234678500, optional=True,) + id = proto.Field(proto.STRING, number=3355, optional=True,) + instance_group = proto.Field(proto.STRING, number=81095253, optional=True,) + instance_template = proto.Field(proto.STRING, number=309248228, optional=True,) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) named_ports = proto.RepeatedField( - proto.MESSAGE, number=159163276, message="NamedPort", + proto.MESSAGE, number=427598732, message="NamedPort", ) - - region = proto.Field(proto.STRING, number=138946292) - - self_link = proto.Field(proto.STRING, number=187779341) - + region = proto.Field(proto.STRING, number=138946292, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) stateful_policy = proto.Field( - proto.MESSAGE, number=47538565, message="StatefulPolicy", + proto.MESSAGE, number=47538565, optional=True, message="StatefulPolicy", ) - status = proto.Field( - proto.MESSAGE, number=181260274, message="InstanceGroupManagerStatus", + proto.MESSAGE, + number=181260274, + optional=True, + message="InstanceGroupManagerStatus", ) - - target_pools = proto.RepeatedField(proto.STRING, number=67637161) - - target_size = proto.Field(proto.INT32, number=62880239) - + target_pools = proto.RepeatedField(proto.STRING, number=336072617,) + target_size = proto.Field(proto.INT32, number=62880239, optional=True,) update_policy = proto.Field( - proto.MESSAGE, number=175809896, message="InstanceGroupManagerUpdatePolicy", + proto.MESSAGE, + number=175809896, + optional=True, + message="InstanceGroupManagerUpdatePolicy", ) - versions = proto.RepeatedField( proto.MESSAGE, number=162430619, message="InstanceGroupManagerVersion", ) - - zone = proto.Field(proto.STRING, number=3744684) + zone = proto.Field(proto.STRING, number=3744684, optional=True,) class InstanceGroupManagersScopedList(proto.Message): r""" - Attributes: instance_group_managers (Sequence[google.cloud.compute_v1.types.InstanceGroupManager]): [Output Only] The list of managed instance groups that are @@ -11413,13 +10788,13 @@ class InstanceGroupManagersScopedList(proto.Message): instance_group_managers = proto.RepeatedField( proto.MESSAGE, number=214072592, message="InstanceGroupManager", ) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", + ) class InstanceGroupManagerAggregatedList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -11450,29 +10825,24 @@ class InstanceGroupManagerAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="InstanceGroupManagersScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 InstanceGroupManagerList(proto.Message): r"""[Output Only] A list of managed instance groups. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -11500,24 +10870,20 @@ class InstanceGroupManagerList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="InstanceGroupManager", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 InstanceGroupManagerStatusStateful(proto.Message): r""" - Attributes: has_stateful_config (bool): [Output Only] A bit indicating whether the managed instance @@ -11532,18 +10898,17 @@ class InstanceGroupManagerStatusStateful(proto.Message): instance. """ - has_stateful_config = proto.Field(proto.BOOL, number=110474224) - + has_stateful_config = proto.Field(proto.BOOL, number=110474224, optional=True,) per_instance_configs = proto.Field( proto.MESSAGE, - number=257829545, + number=526265001, + optional=True, message="InstanceGroupManagerStatusStatefulPerInstanceConfigs", ) class InstanceGroupManagerStatusVersionTarget(proto.Message): r""" - Attributes: is_reached (bool): [Output Only] A bit indicating whether version target has @@ -11553,12 +10918,11 @@ class InstanceGroupManagerStatusVersionTarget(proto.Message): Manager. """ - is_reached = proto.Field(proto.BOOL, number=164773693) + is_reached = proto.Field(proto.BOOL, number=433209149, optional=True,) class InstanceGroupManagerStatusStatefulPerInstanceConfigs(proto.Message): r""" - Attributes: all_effective (bool): A bit indicating if all of the group's per- @@ -11567,12 +10931,11 @@ class InstanceGroupManagerStatusStatefulPerInstanceConfigs(proto.Message): EFFECTIVE or there are no per-instance-configs. """ - all_effective = proto.Field(proto.BOOL, number=248105097) + all_effective = proto.Field(proto.BOOL, number=516540553, optional=True,) class InstanceGroupManagersAbandonInstancesRequest(proto.Message): r""" - Attributes: instances (Sequence[str]): The URLs of one or more instances to abandon. This can be a @@ -11580,12 +10943,11 @@ class InstanceGroupManagersAbandonInstancesRequest(proto.Message): zones/[ZONE]/instances/[INSTANCE_NAME]. """ - instances = proto.RepeatedField(proto.STRING, number=29097598) + instances = proto.RepeatedField(proto.STRING, number=29097598,) class InstanceGroupManagersApplyUpdatesRequest(proto.Message): r"""InstanceGroupManagers.applyUpdatesToInstances - Attributes: all_instances (bool): Flag to update all instances instead of @@ -11620,18 +10982,16 @@ class InstanceGroupManagersApplyUpdatesRequest(proto.Message): the update request will fail. """ - all_instances = proto.Field(proto.BOOL, number=135241056) - - instances = proto.RepeatedField(proto.STRING, number=29097598) - - minimal_action = proto.Field(proto.STRING, number=2131604) - - most_disruptive_allowed_action = proto.Field(proto.STRING, number=66103053) + all_instances = proto.Field(proto.BOOL, number=403676512, optional=True,) + instances = proto.RepeatedField(proto.STRING, number=29097598,) + minimal_action = proto.Field(proto.STRING, number=270567060, optional=True,) + most_disruptive_allowed_action = proto.Field( + proto.STRING, number=66103053, optional=True, + ) class PerInstanceConfig(proto.Message): r""" - Attributes: fingerprint (str): Fingerprint of this per-instance config. This @@ -11665,27 +11025,23 @@ class Status(proto.Enum): corresponding managed instance. """ UNDEFINED_STATUS = 0 - APPLYING = 83568052 - DELETING = 260166568 + APPLYING = 352003508 + DELETING = 528602024 EFFECTIVE = 244201863 NONE = 2402104 - UNAPPLIED = 215499684 - UNAPPLIED_DELETION = 45521417 - - fingerprint = proto.Field(proto.STRING, number=234678500) - - name = proto.Field(proto.STRING, number=3373707) + UNAPPLIED = 483935140 + UNAPPLIED_DELETION = 313956873 + fingerprint = proto.Field(proto.STRING, number=234678500, optional=True,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) preserved_state = proto.Field( - proto.MESSAGE, number=2634026, message="PreservedState", + proto.MESSAGE, number=2634026, optional=True, message="PreservedState", ) - - status = proto.Field(proto.ENUM, number=181260274, enum=Status,) + status = proto.Field(proto.ENUM, number=181260274, optional=True, enum=Status,) class InstanceGroupManagersCreateInstancesRequest(proto.Message): r"""InstanceGroupManagers.createInstances - Attributes: instances (Sequence[google.cloud.compute_v1.types.PerInstanceConfig]): [Required] List of specifications of per-instance configs. @@ -11698,7 +11054,6 @@ class InstanceGroupManagersCreateInstancesRequest(proto.Message): class InstanceGroupManagersDeleteInstancesRequest(proto.Message): r""" - Attributes: instances (Sequence[str]): The URLs of one or more instances to delete. This can be a @@ -11706,12 +11061,11 @@ class InstanceGroupManagersDeleteInstancesRequest(proto.Message): zones/[ZONE]/instances/[INSTANCE_NAME]. """ - instances = proto.RepeatedField(proto.STRING, number=29097598) + instances = proto.RepeatedField(proto.STRING, number=29097598,) class InstanceGroupManagersDeletePerInstanceConfigsReq(proto.Message): r"""InstanceGroupManagers.deletePerInstanceConfigs - Attributes: names (Sequence[str]): The list of instance names for which we want @@ -11719,12 +11073,11 @@ class InstanceGroupManagersDeletePerInstanceConfigsReq(proto.Message): instance group. """ - names = proto.RepeatedField(proto.STRING, number=104585032) + names = proto.RepeatedField(proto.STRING, number=104585032,) class InstanceManagedByIgmError(proto.Message): r""" - Attributes: error (google.cloud.compute_v1.types.InstanceManagedByIgmErrorManagedInstanceError): [Output Only] Contents of the error. @@ -11740,21 +11093,20 @@ class InstanceManagedByIgmError(proto.Message): error = proto.Field( proto.MESSAGE, number=96784904, + optional=True, message="InstanceManagedByIgmErrorManagedInstanceError", ) - instance_action_details = proto.Field( proto.MESSAGE, - number=23789091, + number=292224547, + optional=True, message="InstanceManagedByIgmErrorInstanceActionDetails", ) - - timestamp = proto.Field(proto.STRING, number=55126294) + timestamp = proto.Field(proto.STRING, number=55126294, optional=True,) class InstanceGroupManagersListErrorsResponse(proto.Message): r""" - Attributes: items (Sequence[google.cloud.compute_v1.types.InstanceManagedByIgmError]): [Output Only] The list of errors of the managed instance @@ -11775,13 +11127,11 @@ def raw_page(self): items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="InstanceManagedByIgmError", ) - - next_page_token = proto.Field(proto.STRING, number=79797525) + next_page_token = proto.Field(proto.STRING, number=79797525, optional=True,) class ManagedInstance(proto.Message): r"""A Managed Instance resource. - Attributes: current_action (google.cloud.compute_v1.types.ManagedInstance.CurrentAction): [Output Only] The current action that the managed instance @@ -11867,14 +11217,14 @@ class CurrentAction(proto.Enum): it is in the process of being verified. """ UNDEFINED_CURRENT_ACTION = 0 - ABANDONING = 119809357 - CREATING = 187129529 - CREATING_WITHOUT_RETRIES = 160408329 - DELETING = 260166568 + ABANDONING = 388244813 + CREATING = 455564985 + CREATING_WITHOUT_RETRIES = 428843785 + DELETING = 528602024 NONE = 2402104 - RECREATING = 18843116 + RECREATING = 287278572 REFRESHING = 163266343 - RESTARTING = 52098931 + RESTARTING = 320534387 VERIFYING = 16982185 class InstanceStatus(proto.Enum): @@ -11882,49 +11232,50 @@ class InstanceStatus(proto.Enum): the instance does not exist. """ UNDEFINED_INSTANCE_STATUS = 0 - DEPROVISIONING = 160500206 - PROVISIONING = 22461165 - REPAIRING = 145047829 + DEPROVISIONING = 428935662 + PROVISIONING = 290896621 + REPAIRING = 413483285 RUNNING = 121282975 - STAGING = 162636827 - STOPPED = 175840685 - STOPPING = 82356340 + STAGING = 431072283 + STOPPED = 444276141 + STOPPING = 350791796 SUSPENDED = 51223995 - SUSPENDING = 245770790 + SUSPENDING = 514206246 TERMINATED = 250018339 - current_action = proto.Field(proto.ENUM, number=178475964, enum=CurrentAction,) - - id = proto.Field(proto.STRING, number=3355) - - instance = proto.Field(proto.STRING, number=18257045) - + current_action = proto.Field( + proto.ENUM, number=178475964, optional=True, enum=CurrentAction, + ) + id = proto.Field(proto.STRING, number=3355, optional=True,) + instance = proto.Field(proto.STRING, number=18257045, optional=True,) instance_health = proto.RepeatedField( - proto.MESSAGE, number=114231622, message="ManagedInstanceInstanceHealth", + proto.MESSAGE, number=382667078, message="ManagedInstanceInstanceHealth", + ) + instance_status = proto.Field( + proto.ENUM, number=174577372, optional=True, enum=InstanceStatus, ) - - instance_status = proto.Field(proto.ENUM, number=174577372, enum=InstanceStatus,) - last_attempt = proto.Field( - proto.MESSAGE, number=166336036, message="ManagedInstanceLastAttempt", + proto.MESSAGE, + number=434771492, + optional=True, + message="ManagedInstanceLastAttempt", ) - preserved_state_from_config = proto.Field( - proto.MESSAGE, number=98661858, message="PreservedState", + proto.MESSAGE, number=98661858, optional=True, message="PreservedState", ) - preserved_state_from_policy = proto.Field( - proto.MESSAGE, number=202348498, message="PreservedState", + proto.MESSAGE, number=470783954, optional=True, message="PreservedState", ) - version = proto.Field( - proto.MESSAGE, number=83172568, message="ManagedInstanceVersion", + proto.MESSAGE, + number=351608024, + optional=True, + message="ManagedInstanceVersion", ) class InstanceGroupManagersListManagedInstancesResponse(proto.Message): r""" - Attributes: managed_instances (Sequence[google.cloud.compute_v1.types.ManagedInstance]): [Output Only] The list of instances in the managed instance @@ -11943,15 +11294,13 @@ def raw_page(self): return self managed_instances = proto.RepeatedField( - proto.MESSAGE, number=67784158, message="ManagedInstance", + proto.MESSAGE, number=336219614, message="ManagedInstance", ) - - next_page_token = proto.Field(proto.STRING, number=79797525) + next_page_token = proto.Field(proto.STRING, number=79797525, optional=True,) class InstanceGroupManagersListPerInstanceConfigsResp(proto.Message): r""" - Attributes: items (Sequence[google.cloud.compute_v1.types.PerInstanceConfig]): [Output Only] The list of PerInstanceConfig. @@ -11973,15 +11322,14 @@ def raw_page(self): items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="PerInstanceConfig", ) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + next_page_token = proto.Field(proto.STRING, number=79797525, optional=True,) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", + ) class InstanceGroupManagersPatchPerInstanceConfigsReq(proto.Message): r"""InstanceGroupManagers.patchPerInstanceConfigs - Attributes: per_instance_configs (Sequence[google.cloud.compute_v1.types.PerInstanceConfig]): The list of per-instance configs to insert or @@ -11989,13 +11337,12 @@ class InstanceGroupManagersPatchPerInstanceConfigsReq(proto.Message): """ per_instance_configs = proto.RepeatedField( - proto.MESSAGE, number=257829545, message="PerInstanceConfig", + proto.MESSAGE, number=526265001, message="PerInstanceConfig", ) class InstanceGroupManagersRecreateInstancesRequest(proto.Message): r""" - Attributes: instances (Sequence[str]): The URLs of one or more instances to recreate. This can be a @@ -12003,12 +11350,11 @@ class InstanceGroupManagersRecreateInstancesRequest(proto.Message): zones/[ZONE]/instances/[INSTANCE_NAME]. """ - instances = proto.RepeatedField(proto.STRING, number=29097598) + instances = proto.RepeatedField(proto.STRING, number=29097598,) class InstanceGroupManagersSetInstanceTemplateRequest(proto.Message): r""" - Attributes: instance_template (str): The URL of the instance template that is @@ -12021,12 +11367,11 @@ class InstanceGroupManagersSetInstanceTemplateRequest(proto.Message): updatePolicy.type to PROACTIVE. """ - instance_template = proto.Field(proto.STRING, number=40812772) + instance_template = proto.Field(proto.STRING, number=309248228, optional=True,) class InstanceGroupManagersSetTargetPoolsRequest(proto.Message): r""" - Attributes: fingerprint (str): The fingerprint of the target pools @@ -12047,14 +11392,12 @@ class InstanceGroupManagersSetTargetPoolsRequest(proto.Message): group all receive these target pool settings. """ - fingerprint = proto.Field(proto.STRING, number=234678500) - - target_pools = proto.RepeatedField(proto.STRING, number=67637161) + fingerprint = proto.Field(proto.STRING, number=234678500, optional=True,) + target_pools = proto.RepeatedField(proto.STRING, number=336072617,) class InstanceGroupManagersUpdatePerInstanceConfigsReq(proto.Message): r"""InstanceGroupManagers.updatePerInstanceConfigs - Attributes: per_instance_configs (Sequence[google.cloud.compute_v1.types.PerInstanceConfig]): The list of per-instance configs to insert or @@ -12062,24 +11405,22 @@ class InstanceGroupManagersUpdatePerInstanceConfigsReq(proto.Message): """ per_instance_configs = proto.RepeatedField( - proto.MESSAGE, number=257829545, message="PerInstanceConfig", + proto.MESSAGE, number=526265001, message="PerInstanceConfig", ) class InstanceReference(proto.Message): r""" - Attributes: instance (str): The URL for a specific instance. """ - instance = proto.Field(proto.STRING, number=18257045) + instance = proto.Field(proto.STRING, number=18257045, optional=True,) class InstanceGroupsAddInstancesRequest(proto.Message): r""" - Attributes: instances (Sequence[google.cloud.compute_v1.types.InstanceReference]): The list of instances to add to the instance @@ -12093,7 +11434,6 @@ class InstanceGroupsAddInstancesRequest(proto.Message): class InstanceWithNamedPorts(proto.Message): r""" - Attributes: instance (str): [Output Only] The URL of the instance. @@ -12107,29 +11447,26 @@ class InstanceWithNamedPorts(proto.Message): class Status(proto.Enum): r"""[Output Only] The status of the instance.""" UNDEFINED_STATUS = 0 - DEPROVISIONING = 160500206 - PROVISIONING = 22461165 - REPAIRING = 145047829 + DEPROVISIONING = 428935662 + PROVISIONING = 290896621 + REPAIRING = 413483285 RUNNING = 121282975 - STAGING = 162636827 - STOPPED = 175840685 - STOPPING = 82356340 + STAGING = 431072283 + STOPPED = 444276141 + STOPPING = 350791796 SUSPENDED = 51223995 - SUSPENDING = 245770790 + SUSPENDING = 514206246 TERMINATED = 250018339 - instance = proto.Field(proto.STRING, number=18257045) - + instance = proto.Field(proto.STRING, number=18257045, optional=True,) named_ports = proto.RepeatedField( - proto.MESSAGE, number=159163276, message="NamedPort", + proto.MESSAGE, number=427598732, message="NamedPort", ) - - status = proto.Field(proto.ENUM, number=181260274, enum=Status,) + status = proto.Field(proto.ENUM, number=181260274, optional=True, enum=Status,) class InstanceGroupsListInstances(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -12157,24 +11494,20 @@ class InstanceGroupsListInstances(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="InstanceWithNamedPorts", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 InstanceGroupsListInstancesRequest(proto.Message): r""" - Attributes: instance_state (google.cloud.compute_v1.types.InstanceGroupsListInstancesRequest.InstanceState): A filter for the state of the instances in @@ -12194,12 +11527,13 @@ class InstanceState(proto.Enum): ALL = 64897 RUNNING = 121282975 - instance_state = proto.Field(proto.ENUM, number=92223591, enum=InstanceState,) + instance_state = proto.Field( + proto.ENUM, number=92223591, optional=True, enum=InstanceState, + ) class InstanceGroupsRemoveInstancesRequest(proto.Message): r""" - Attributes: instances (Sequence[google.cloud.compute_v1.types.InstanceReference]): The list of instances to remove from the @@ -12213,7 +11547,6 @@ class InstanceGroupsRemoveInstancesRequest(proto.Message): class InstanceGroupsSetNamedPortsRequest(proto.Message): r""" - Attributes: fingerprint (str): The fingerprint of the named ports @@ -12232,16 +11565,14 @@ class InstanceGroupsSetNamedPortsRequest(proto.Message): instance group. """ - fingerprint = proto.Field(proto.STRING, number=234678500) - + fingerprint = proto.Field(proto.STRING, number=234678500, optional=True,) named_ports = proto.RepeatedField( - proto.MESSAGE, number=159163276, message="NamedPort", + proto.MESSAGE, number=427598732, message="NamedPort", ) class InstanceList(proto.Message): r"""Contains a list of instances. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -12268,22 +11599,18 @@ class InstanceList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="Instance",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 Reference(proto.Message): r"""Represents a reference to a resource. - Attributes: kind (str): [Output Only] Type of the resource. Always compute#reference @@ -12301,18 +11628,14 @@ class Reference(proto.Message): points. """ - kind = proto.Field(proto.STRING, number=3292052) - - reference_type = proto.Field(proto.STRING, number=247521198) - - referrer = proto.Field(proto.STRING, number=82738207) - - target = proto.Field(proto.STRING, number=192835985) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) + reference_type = proto.Field(proto.STRING, number=247521198, optional=True,) + referrer = proto.Field(proto.STRING, number=351173663, optional=True,) + target = proto.Field(proto.STRING, number=192835985, optional=True,) class InstanceListReferrers(proto.Message): r"""Contains a list of instance referrers. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -12340,22 +11663,18 @@ class InstanceListReferrers(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="Reference",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 InstanceManagedByIgmErrorManagedInstanceError(proto.Message): r""" - Attributes: code (str): [Output Only] Error code. @@ -12363,14 +11682,12 @@ class InstanceManagedByIgmErrorManagedInstanceError(proto.Message): [Output Only] Error message. """ - code = proto.Field(proto.STRING, number=3059181) - - message = proto.Field(proto.STRING, number=149618695) + code = proto.Field(proto.STRING, number=3059181, optional=True,) + message = proto.Field(proto.STRING, number=418054151, optional=True,) class InstanceManagedByIgmErrorInstanceActionDetails(proto.Message): r""" - Attributes: action (google.cloud.compute_v1.types.InstanceManagedByIgmErrorInstanceActionDetails.Action): [Output Only] Action that managed instance group was @@ -12392,28 +11709,28 @@ class Action(proto.Enum): the instance when the error occurred. Possible values: """ UNDEFINED_ACTION = 0 - ABANDONING = 119809357 - CREATING = 187129529 - CREATING_WITHOUT_RETRIES = 160408329 - DELETING = 260166568 + ABANDONING = 388244813 + CREATING = 455564985 + CREATING_WITHOUT_RETRIES = 428843785 + DELETING = 528602024 NONE = 2402104 - RECREATING = 18843116 + RECREATING = 287278572 REFRESHING = 163266343 - RESTARTING = 52098931 + RESTARTING = 320534387 VERIFYING = 16982185 - action = proto.Field(proto.ENUM, number=187661878, enum=Action,) - - instance = proto.Field(proto.STRING, number=18257045) - + action = proto.Field(proto.ENUM, number=187661878, optional=True, enum=Action,) + instance = proto.Field(proto.STRING, number=18257045, optional=True,) version = proto.Field( - proto.MESSAGE, number=83172568, message="ManagedInstanceVersion", + proto.MESSAGE, + number=351608024, + optional=True, + message="ManagedInstanceVersion", ) class ManagedInstanceVersion(proto.Message): r""" - Attributes: instance_template (str): [Output Only] The intended template of the instance. This @@ -12423,14 +11740,12 @@ class ManagedInstanceVersion(proto.Message): [Output Only] Name of the version. """ - instance_template = proto.Field(proto.STRING, number=40812772) - - name = proto.Field(proto.STRING, number=3373707) + instance_template = proto.Field(proto.STRING, number=309248228, optional=True,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) class InstanceMoveRequest(proto.Message): r""" - Attributes: destination_zone (str): The URL of the destination zone to move the @@ -12449,14 +11764,12 @@ class InstanceMoveRequest(proto.Message): - zones/zone/instances/instance """ - destination_zone = proto.Field(proto.STRING, number=131854653) - - target_instance = proto.Field(proto.STRING, number=21333891) + destination_zone = proto.Field(proto.STRING, number=131854653, optional=True,) + 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 @@ -12541,57 +11854,48 @@ class PrivateIpv6GoogleAccess(proto.Enum): INHERIT_FROM_SUBNETWORK as default. """ UNDEFINED_PRIVATE_IPV6_GOOGLE_ACCESS = 0 - ENABLE_BIDIRECTIONAL_ACCESS_TO_GOOGLE = 159540538 - ENABLE_OUTBOUND_VM_ACCESS_TO_GOOGLE = 19774807 - INHERIT_FROM_SUBNETWORK = 261821503 - - can_ip_forward = proto.Field(proto.BOOL, number=199295868) + 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=222202229, message="ConfidentialInstanceConfig", + proto.MESSAGE, + number=490637685, + optional=True, + message="ConfidentialInstanceConfig", ) - - description = proto.Field(proto.STRING, number=154502140) - + 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=195159663, message="AcceleratorConfig", + proto.MESSAGE, number=463595119, message="AcceleratorConfig", ) - - labels = proto.MapField(proto.STRING, proto.STRING, number=231759871) - - machine_type = proto.Field(proto.STRING, number=227711026) - - metadata = proto.Field(proto.MESSAGE, number=86866735, message="Metadata",) - - min_cpu_platform = proto.Field(proto.STRING, number=242912759) - + 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, enum=PrivateIpv6GoogleAccess, + proto.ENUM, number=48277006, optional=True, enum=PrivateIpv6GoogleAccess, ) - reservation_affinity = proto.Field( - proto.MESSAGE, number=157850683, message="ReservationAffinity", + 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", ) - - resource_policies = proto.RepeatedField(proto.STRING, number=22220385) - - scheduling = proto.Field(proto.MESSAGE, number=118252948, message="Scheduling",) - service_accounts = proto.RepeatedField( - proto.MESSAGE, number=9101872, message="ServiceAccount", + proto.MESSAGE, number=277537328, message="ServiceAccount", ) - shielded_instance_config = proto.Field( - proto.MESSAGE, number=12862901, message="ShieldedInstanceConfig", + proto.MESSAGE, number=12862901, optional=True, message="ShieldedInstanceConfig", ) - - tags = proto.Field(proto.MESSAGE, number=3552281, message="Tags",) + tags = proto.Field(proto.MESSAGE, number=3552281, optional=True, message="Tags",) class SourceInstanceParams(proto.Message): @@ -12661,32 +11965,23 @@ class InstanceTemplate(proto.Message): this instance template. """ - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, 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,) properties = proto.Field( - proto.MESSAGE, number=147688755, message="InstanceProperties", + proto.MESSAGE, number=147688755, optional=True, message="InstanceProperties", ) - - self_link = proto.Field(proto.STRING, number=187779341) - - source_instance = proto.Field(proto.STRING, number=127880249) - + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + source_instance = proto.Field(proto.STRING, number=396315705, optional=True,) source_instance_params = proto.Field( - proto.MESSAGE, number=135342156, message="SourceInstanceParams", + proto.MESSAGE, number=135342156, optional=True, message="SourceInstanceParams", ) class InstanceTemplateList(proto.Message): r"""A list of instance templates. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -12714,48 +12009,42 @@ class InstanceTemplateList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="InstanceTemplate", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 InstancesAddResourcePoliciesRequest(proto.Message): r""" - Attributes: resource_policies (Sequence[str]): Resource policies to be added to this instance. """ - resource_policies = proto.RepeatedField(proto.STRING, number=22220385) + resource_policies = proto.RepeatedField(proto.STRING, number=22220385,) class InstancesRemoveResourcePoliciesRequest(proto.Message): r""" - Attributes: resource_policies (Sequence[str]): Resource policies to be removed from this instance. """ - resource_policies = proto.RepeatedField(proto.STRING, number=22220385) + resource_policies = proto.RepeatedField(proto.STRING, number=22220385,) class InstancesSetLabelsRequest(proto.Message): r""" - Attributes: label_fingerprint (str): Fingerprint of the previous set of labels for @@ -12766,14 +12055,12 @@ class InstancesSetLabelsRequest(proto.Message): """ - label_fingerprint = proto.Field(proto.STRING, number=178124825) - - labels = proto.MapField(proto.STRING, proto.STRING, number=231759871) + label_fingerprint = proto.Field(proto.STRING, number=178124825, optional=True,) + labels = proto.MapField(proto.STRING, proto.STRING, number=500195327,) class InstancesSetMachineResourcesRequest(proto.Message): r""" - Attributes: guest_accelerators (Sequence[google.cloud.compute_v1.types.AcceleratorConfig]): A list of the type and count of accelerator @@ -12781,13 +12068,12 @@ class InstancesSetMachineResourcesRequest(proto.Message): """ guest_accelerators = proto.RepeatedField( - proto.MESSAGE, number=195159663, message="AcceleratorConfig", + proto.MESSAGE, number=463595119, message="AcceleratorConfig", ) class InstancesSetMachineTypeRequest(proto.Message): r""" - Attributes: machine_type (str): Full or partial URL of the machine type @@ -12796,24 +12082,22 @@ class InstancesSetMachineTypeRequest(proto.Message): central1-f/machineTypes/n1-standard-1 """ - machine_type = proto.Field(proto.STRING, number=227711026) + machine_type = proto.Field(proto.STRING, number=227711026, optional=True,) class InstancesSetMinCpuPlatformRequest(proto.Message): r""" - Attributes: min_cpu_platform (str): Minimum cpu/platform this instance should be started at. """ - min_cpu_platform = proto.Field(proto.STRING, number=242912759) + min_cpu_platform = proto.Field(proto.STRING, number=242912759, optional=True,) class InstancesSetServiceAccountRequest(proto.Message): r""" - Attributes: email (str): Email address of the service account. @@ -12822,14 +12106,12 @@ class InstancesSetServiceAccountRequest(proto.Message): this service account. """ - email = proto.Field(proto.STRING, number=96619420) - - scopes = proto.RepeatedField(proto.STRING, number=165973151) + email = proto.Field(proto.STRING, number=96619420, optional=True,) + scopes = proto.RepeatedField(proto.STRING, number=165973151,) class InstancesStartWithEncryptionKeyRequest(proto.Message): r""" - Attributes: disks (Sequence[google.cloud.compute_v1.types.CustomerEncryptionKeyProtectedDisk]): Array of disks associated with this instance @@ -12864,16 +12146,13 @@ class InterconnectCircuitInfo(proto.Message): Google to the customer in the LOA. """ - customer_demarc_id = proto.Field(proto.STRING, number=28771859) - - google_circuit_id = proto.Field(proto.STRING, number=262014711) - - google_demarc_id = proto.Field(proto.STRING, number=179760814) + customer_demarc_id = proto.Field(proto.STRING, number=28771859, optional=True,) + google_circuit_id = proto.Field(proto.STRING, number=262014711, optional=True,) + google_demarc_id = proto.Field(proto.STRING, number=448196270, optional=True,) class InterconnectOutageNotification(proto.Message): r"""Description of a planned outage on this Interconnect. - Attributes: affected_circuits (Sequence[str]): If issue_type is IT_PARTIAL_OUTAGE, a list of the @@ -12945,8 +12224,8 @@ class Source(proto.Enum): value of NSRC_GOOGLE has been deprecated in favor of GOOGLE. """ UNDEFINED_SOURCE = 0 - GOOGLE = 229003833 - NSRC_GOOGLE = 242139106 + GOOGLE = 497439289 + NSRC_GOOGLE = 510574562 class State(proto.Enum): r"""State of this notification, which can take one of the following @@ -12961,27 +12240,22 @@ class State(proto.Enum): favor of the unprefixed values. """ UNDEFINED_STATE = 0 - ACTIVE = 46297862 + ACTIVE = 314733318 CANCELLED = 41957681 - COMPLETED = 41485867 + COMPLETED = 309921323 NS_ACTIVE = 252563136 - NS_CANCELED = 238143955 - - affected_circuits = proto.RepeatedField(proto.STRING, number=177717013) - - description = proto.Field(proto.STRING, number=154502140) - - end_time = proto.Field(proto.STRING, number=114938801) - - issue_type = proto.Field(proto.ENUM, number=101203680, enum=IssueType,) - - name = proto.Field(proto.STRING, number=3373707) - - source = proto.Field(proto.ENUM, number=177235995, enum=Source,) + NS_CANCELED = 506579411 - start_time = proto.Field(proto.STRING, number=37467274) - - state = proto.Field(proto.ENUM, number=109757585, enum=State,) + affected_circuits = proto.RepeatedField(proto.STRING, number=177717013,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + end_time = proto.Field(proto.STRING, number=114938801, optional=True,) + issue_type = proto.Field( + proto.ENUM, number=369639136, optional=True, enum=IssueType, + ) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + source = proto.Field(proto.ENUM, number=177235995, optional=True, enum=Source,) + start_time = proto.Field(proto.STRING, number=37467274, optional=True,) + state = proto.Field(proto.ENUM, number=109757585, optional=True, enum=State,) class Interconnect(proto.Message): @@ -13120,8 +12394,8 @@ class InterconnectType(proto.Enum): """ UNDEFINED_INTERCONNECT_TYPE = 0 DEDICATED = 258411983 - IT_PRIVATE = 67241551 - PARTNER = 193489064 + IT_PRIVATE = 335677007 + PARTNER = 461924520 class LinkType(proto.Enum): r"""Type of link requested, which can take one of the following values: @@ -13132,7 +12406,7 @@ class LinkType(proto.Enum): bundle, not the speed of the entire bundle. """ UNDEFINED_LINK_TYPE = 0 - LINK_TYPE_ETHERNET_100G_LR = 69237095 + LINK_TYPE_ETHERNET_100G_LR = 337672551 LINK_TYPE_ETHERNET_10G_LR = 236739749 class OperationalStatus(proto.Enum): @@ -13164,60 +12438,39 @@ class State(proto.Enum): Interconnect. """ UNDEFINED_STATE = 0 - ACTIVE = 46297862 - UNPROVISIONED = 248898523 - - admin_enabled = proto.Field(proto.BOOL, number=177239633) + ACTIVE = 314733318 + UNPROVISIONED = 517333979 + admin_enabled = proto.Field(proto.BOOL, number=445675089, optional=True,) circuit_infos = proto.RepeatedField( proto.MESSAGE, number=164839855, message="InterconnectCircuitInfo", ) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - customer_name = proto.Field(proto.STRING, number=3665484) - - description = proto.Field(proto.STRING, number=154502140) - + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + customer_name = proto.Field(proto.STRING, number=3665484, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) expected_outages = proto.RepeatedField( proto.MESSAGE, number=264484123, message="InterconnectOutageNotification", ) - - google_ip_address = proto.Field(proto.STRING, number=174670498) - - google_reference_id = proto.Field(proto.STRING, number=266509013) - - id = proto.Field(proto.STRING, number=3355) - - interconnect_attachments = proto.RepeatedField(proto.STRING, number=156952959) - + google_ip_address = proto.Field(proto.STRING, number=443105954, optional=True,) + google_reference_id = proto.Field(proto.STRING, number=534944469, optional=True,) + id = proto.Field(proto.STRING, number=3355, optional=True,) + interconnect_attachments = proto.RepeatedField(proto.STRING, number=425388415,) interconnect_type = proto.Field( - proto.ENUM, number=246729803, enum=InterconnectType, + proto.ENUM, number=515165259, optional=True, enum=InterconnectType, ) - - kind = proto.Field(proto.STRING, number=3292052) - - link_type = proto.Field(proto.ENUM, number=254772319, enum=LinkType,) - - location = proto.Field(proto.STRING, number=21995445) - - name = proto.Field(proto.STRING, number=3373707) - - noc_contact_email = proto.Field(proto.STRING, number=14072832) - + kind = proto.Field(proto.STRING, number=3292052, optional=True,) + link_type = proto.Field(proto.ENUM, number=523207775, optional=True, enum=LinkType,) + location = proto.Field(proto.STRING, number=290430901, optional=True,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + noc_contact_email = proto.Field(proto.STRING, number=14072832, optional=True,) operational_status = proto.Field( - proto.ENUM, number=201070847, enum=OperationalStatus, + proto.ENUM, number=201070847, optional=True, enum=OperationalStatus, ) - - peer_ip_address = proto.Field(proto.STRING, number=207735769) - - provisioned_link_count = proto.Field(proto.INT32, number=142453109) - - requested_link_count = proto.Field(proto.INT32, number=45051387) - - self_link = proto.Field(proto.STRING, number=187779341) - - state = proto.Field(proto.ENUM, number=109757585, enum=State,) + peer_ip_address = proto.Field(proto.STRING, number=207735769, optional=True,) + provisioned_link_count = proto.Field(proto.INT32, number=410888565, optional=True,) + requested_link_count = proto.Field(proto.INT32, number=45051387, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + state = proto.Field(proto.ENUM, number=109757585, optional=True, enum=State,) class InterconnectAttachmentPartnerMetadata(proto.Message): @@ -13245,11 +12498,9 @@ class InterconnectAttachmentPartnerMetadata(proto.Message): match approved Partner values. """ - interconnect_name = proto.Field(proto.STRING, number=246527900) - - partner_name = proto.Field(proto.STRING, number=161747874) - - portal_url = proto.Field(proto.STRING, number=747292) + interconnect_name = proto.Field(proto.STRING, number=514963356, optional=True,) + partner_name = proto.Field(proto.STRING, number=161747874, optional=True,) + portal_url = proto.Field(proto.STRING, number=269182748, optional=True,) class InterconnectAttachmentPrivateInfo(proto.Message): @@ -13263,7 +12514,7 @@ class InterconnectAttachmentPrivateInfo(proto.Message): this network and region. """ - tag8021q = proto.Field(proto.UINT32, number=3385536) + tag8021q = proto.Field(proto.UINT32, number=271820992, optional=True,) class InterconnectAttachment(proto.Message): @@ -13473,17 +12724,17 @@ class Bandwidth(proto.Enum): """ UNDEFINED_BANDWIDTH = 0 BPS_100M = 49547958 - BPS_10G = 10257550 - BPS_1G = 86922992 + BPS_10G = 278693006 + BPS_1G = 355358448 BPS_200M = 49577749 - BPS_20G = 10258511 - BPS_2G = 86923023 + BPS_20G = 278693967 + BPS_2G = 355358479 BPS_300M = 49607540 BPS_400M = 49637331 BPS_500M = 49667122 - BPS_50G = 10261394 - BPS_50M = 10261400 - BPS_5G = 86923116 + BPS_50G = 278696850 + BPS_50M = 278696856 + BPS_5G = 355358572 class EdgeAvailabilityDomain(proto.Enum): r"""Desired availability domain for the attachment. Only available for @@ -13500,9 +12751,9 @@ class EdgeAvailabilityDomain(proto.Enum): AVAILABILITY_DOMAIN_ANY. """ UNDEFINED_EDGE_AVAILABILITY_DOMAIN = 0 - AVAILABILITY_DOMAIN_1 = 81116634 - AVAILABILITY_DOMAIN_2 = 81116635 - AVAILABILITY_DOMAIN_ANY = 106820917 + AVAILABILITY_DOMAIN_1 = 349552090 + AVAILABILITY_DOMAIN_2 = 349552091 + AVAILABILITY_DOMAIN_ANY = 375256373 class OperationalStatus(proto.Enum): r"""[Output Only] The current status of whether or not this interconnect @@ -13542,13 +12793,13 @@ class State(proto.Enum): deleted. """ UNDEFINED_STATE = 0 - ACTIVE = 46297862 + ACTIVE = 314733318 DEFUNCT = 115891759 - PARTNER_REQUEST_RECEIVED = 245151848 + PARTNER_REQUEST_RECEIVED = 513587304 PENDING_CUSTOMER = 167494054 - PENDING_PARTNER = 119455200 - STATE_UNSPECIFIED = 202319945 - UNPROVISIONED = 248898523 + PENDING_PARTNER = 387890656 + STATE_UNSPECIFIED = 470755401 + UNPROVISIONED = 517333979 class Type(proto.Enum): r"""The type of interconnect attachment this is, which can take one of @@ -13562,73 +12813,59 @@ class Type(proto.Enum): """ UNDEFINED_TYPE = 0 DEDICATED = 258411983 - PARTNER = 193489064 - PARTNER_PROVIDER = 214825896 - - admin_enabled = proto.Field(proto.BOOL, number=177239633) - - bandwidth = proto.Field(proto.ENUM, number=181715121, enum=Bandwidth,) - - candidate_subnets = proto.RepeatedField(proto.STRING, number=237842938) - - cloud_router_ip_address = proto.Field(proto.STRING, number=18957320) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - customer_router_ip_address = proto.Field(proto.STRING, number=64040305) - - dataplane_version = proto.Field(proto.INT32, number=34920075) - - description = proto.Field(proto.STRING, number=154502140) + PARTNER = 461924520 + PARTNER_PROVIDER = 483261352 - edge_availability_domain = proto.Field( - proto.ENUM, number=71289510, enum=EdgeAvailabilityDomain, + admin_enabled = proto.Field(proto.BOOL, number=445675089, optional=True,) + bandwidth = proto.Field( + proto.ENUM, number=181715121, optional=True, enum=Bandwidth, ) - - google_reference_id = proto.Field(proto.STRING, number=266509013) - - id = proto.Field(proto.STRING, number=3355) - - interconnect = proto.Field(proto.STRING, number=224601230) - - kind = proto.Field(proto.STRING, number=3292052) - - mtu = proto.Field(proto.INT32, number=108462) - - name = proto.Field(proto.STRING, number=3373707) - + candidate_subnets = proto.RepeatedField(proto.STRING, number=237842938,) + cloud_router_ip_address = proto.Field( + proto.STRING, number=287392776, optional=True, + ) + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + customer_router_ip_address = proto.Field( + proto.STRING, number=332475761, optional=True, + ) + dataplane_version = proto.Field(proto.INT32, number=34920075, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + edge_availability_domain = proto.Field( + proto.ENUM, number=71289510, optional=True, enum=EdgeAvailabilityDomain, + ) + 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,) + 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,) operational_status = proto.Field( - proto.ENUM, number=201070847, enum=OperationalStatus, + proto.ENUM, number=201070847, optional=True, enum=OperationalStatus, ) - - pairing_key = proto.Field(proto.STRING, number=171260008) - - partner_asn = proto.Field(proto.STRING, number=169730693) - + pairing_key = proto.Field(proto.STRING, number=439695464, optional=True,) + partner_asn = proto.Field(proto.STRING, number=438166149, optional=True,) partner_metadata = proto.Field( - proto.MESSAGE, number=65908934, message="InterconnectAttachmentPartnerMetadata", + proto.MESSAGE, + number=65908934, + optional=True, + message="InterconnectAttachmentPartnerMetadata", ) - private_interconnect_info = proto.Field( - proto.MESSAGE, number=237270531, message="InterconnectAttachmentPrivateInfo", + proto.MESSAGE, + number=237270531, + optional=True, + message="InterconnectAttachmentPrivateInfo", ) - - region = proto.Field(proto.STRING, number=138946292) - - router = proto.Field(proto.STRING, number=148608841) - - self_link = proto.Field(proto.STRING, number=187779341) - - state = proto.Field(proto.ENUM, number=109757585, enum=State,) - - type_ = proto.Field(proto.ENUM, number=3575610, enum=Type,) - - vlan_tag8021q = proto.Field(proto.INT32, number=119927836) + region = proto.Field(proto.STRING, number=138946292, optional=True,) + router = proto.Field(proto.STRING, number=148608841, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + state = proto.Field(proto.ENUM, number=109757585, optional=True, enum=State,) + type_ = proto.Field(proto.ENUM, number=3575610, optional=True, enum=Type,) + vlan_tag8021q = proto.Field(proto.INT32, number=119927836, optional=True,) class InterconnectAttachmentsScopedList(proto.Message): r""" - Attributes: interconnect_attachments (Sequence[google.cloud.compute_v1.types.InterconnectAttachment]): A list of interconnect attachments contained @@ -13639,15 +12876,15 @@ class InterconnectAttachmentsScopedList(proto.Message): """ interconnect_attachments = proto.RepeatedField( - proto.MESSAGE, number=156952959, message="InterconnectAttachment", + proto.MESSAGE, number=425388415, message="InterconnectAttachment", + ) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", ) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) class InterconnectAttachmentAggregatedList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -13678,24 +12915,20 @@ class InterconnectAttachmentAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="InterconnectAttachmentsScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 InterconnectAttachmentList(proto.Message): @@ -13729,24 +12962,20 @@ class InterconnectAttachmentList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="InterconnectAttachment", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 InterconnectDiagnosticsARPEntry(proto.Message): r"""Describing the ARP neighbor entries seen on this link - Attributes: ip_address (str): The IP address of this ARP neighbor. @@ -13754,14 +12983,12 @@ class InterconnectDiagnosticsARPEntry(proto.Message): The MAC address of this ARP neighbor. """ - ip_address = proto.Field(proto.STRING, number=137836764) - - mac_address = proto.Field(proto.STRING, number=64104708) + ip_address = proto.Field(proto.STRING, number=406272220, optional=True,) + mac_address = proto.Field(proto.STRING, number=332540164, optional=True,) class InterconnectDiagnosticsLinkStatus(proto.Message): r""" - Attributes: arp_caches (Sequence[google.cloud.compute_v1.types.InterconnectDiagnosticsARPEntry]): A list of InterconnectDiagnostics.ARPEntry @@ -13787,26 +13014,26 @@ class InterconnectDiagnosticsLinkStatus(proto.Message): """ arp_caches = proto.RepeatedField( - proto.MESSAGE, number=146156305, message="InterconnectDiagnosticsARPEntry", + proto.MESSAGE, number=414591761, message="InterconnectDiagnosticsARPEntry", ) - - circuit_id = proto.Field(proto.STRING, number=225180977) - - google_demarc = proto.Field(proto.STRING, number=51084) - + circuit_id = proto.Field(proto.STRING, number=225180977, optional=True,) + google_demarc = proto.Field(proto.STRING, number=51084, optional=True,) lacp_status = proto.Field( - proto.MESSAGE, number=92774959, message="InterconnectDiagnosticsLinkLACPStatus", + proto.MESSAGE, + number=361210415, + optional=True, + message="InterconnectDiagnosticsLinkLACPStatus", ) - receiving_optical_power = proto.Field( proto.MESSAGE, number=244717279, + optional=True, message="InterconnectDiagnosticsLinkOpticalPower", ) - transmitting_optical_power = proto.Field( proto.MESSAGE, - number=190995741, + number=459431197, + optional=True, message="InterconnectDiagnosticsLinkOpticalPower", ) @@ -13833,19 +13060,16 @@ class InterconnectDiagnostics(proto.Message): """ arp_caches = proto.RepeatedField( - proto.MESSAGE, number=146156305, message="InterconnectDiagnosticsARPEntry", + proto.MESSAGE, number=414591761, message="InterconnectDiagnosticsARPEntry", ) - links = proto.RepeatedField( proto.MESSAGE, number=102977465, message="InterconnectDiagnosticsLinkStatus", ) - - mac_address = proto.Field(proto.STRING, number=64104708) + mac_address = proto.Field(proto.STRING, number=332540164, optional=True,) class InterconnectDiagnosticsLinkLACPStatus(proto.Message): r""" - Attributes: google_system_id (str): System ID of the port on Google's side of the @@ -13869,19 +13093,16 @@ class State(proto.Enum): bundle. This means that the rest of the object should be empty. """ UNDEFINED_STATE = 0 - ACTIVE = 46297862 + ACTIVE = 314733318 DETACHED = 216562546 - google_system_id = proto.Field(proto.STRING, number=91210405) - - neighbor_system_id = proto.Field(proto.STRING, number=75385886) - - state = proto.Field(proto.ENUM, number=109757585, enum=State,) + google_system_id = proto.Field(proto.STRING, number=91210405, optional=True,) + neighbor_system_id = proto.Field(proto.STRING, number=343821342, optional=True,) + state = proto.Field(proto.ENUM, number=109757585, optional=True, enum=State,) class InterconnectDiagnosticsLinkOpticalPower(proto.Message): r""" - Attributes: state (google.cloud.compute_v1.types.InterconnectDiagnosticsLinkOpticalPower.State): The status of the current value when compared to the warning @@ -13920,15 +13141,14 @@ class State(proto.Enum): - HIGH_ALARM: The value has crossed above the high alarm threshold. """ UNDEFINED_STATE = 0 - HIGH_ALARM = 36927828 + HIGH_ALARM = 305363284 HIGH_WARNING = 220984799 - LOW_ALARM = 48223590 - LOW_WARNING = 70358385 + LOW_ALARM = 316659046 + LOW_WARNING = 338793841 OK = 2524 - state = proto.Field(proto.ENUM, number=109757585, enum=State,) - - value = proto.Field(proto.FLOAT, number=111972721) + state = proto.Field(proto.ENUM, number=109757585, optional=True, enum=State,) + value = proto.Field(proto.FLOAT, number=111972721, optional=True,) class InterconnectList(proto.Message): @@ -13961,19 +13181,16 @@ class InterconnectList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="Interconnect", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 InterconnectLocationRegionInfo(proto.Message): @@ -13996,18 +13213,16 @@ class InterconnectLocationRegionInfo(proto.Message): class LocationPresence(proto.Enum): r"""Identifies the network presence of this location.""" UNDEFINED_LOCATION_PRESENCE = 0 - GLOBAL = 226228131 - LOCAL_REGION = 135100008 - LP_GLOBAL = 161148606 - LP_LOCAL_REGION = 220163395 - - expected_rtt_ms = proto.Field(proto.STRING, number=154108410) + GLOBAL = 494663587 + LOCAL_REGION = 403535464 + LP_GLOBAL = 429584062 + LP_LOCAL_REGION = 488598851 + expected_rtt_ms = proto.Field(proto.STRING, number=422543866, optional=True,) location_presence = proto.Field( - proto.ENUM, number=101517893, enum=LocationPresence, + proto.ENUM, number=101517893, optional=True, enum=LocationPresence, ) - - region = proto.Field(proto.STRING, number=138946292) + region = proto.Field(proto.STRING, number=138946292, optional=True,) class InterconnectLocation(proto.Message): @@ -14089,15 +13304,15 @@ class Continent(proto.Enum): - SOUTH_AMERICA """ UNDEFINED_CONTINENT = 0 - AFRICA = 49008250 + AFRICA = 317443706 ASIA_PAC = 119782269 C_AFRICA = 71993846 - C_ASIA_PAC = 197232633 + C_ASIA_PAC = 465668089 C_EUROPE = 200369438 - C_NORTH_AMERICA = 7261592 - C_SOUTH_AMERICA = 128714336 - EUROPE = 177383842 - NORTH_AMERICA = 179580052 + C_NORTH_AMERICA = 275697048 + C_SOUTH_AMERICA = 397149792 + EUROPE = 445819298 + NORTH_AMERICA = 448015508 SOUTH_AMERICA = 32597340 class Status(proto.Enum): @@ -14110,40 +13325,30 @@ class Status(proto.Enum): new Interconnects. """ UNDEFINED_STATUS = 0 - AVAILABLE = 173644457 - CLOSED = 111727980 - - address = proto.Field(proto.STRING, number=194485236) - - availability_zone = proto.Field(proto.STRING, number=158459920) - - city = proto.Field(proto.STRING, number=3053931) - - continent = proto.Field(proto.ENUM, number=133442996, enum=Continent,) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - facility_provider = proto.Field(proto.STRING, number=264867853) - - facility_provider_facility_id = proto.Field(proto.STRING, number=87269125) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - - peeringdb_facility_id = proto.Field(proto.STRING, number=268131638) - + AVAILABLE = 442079913 + CLOSED = 380163436 + + address = proto.Field(proto.STRING, number=462920692, optional=True,) + availability_zone = proto.Field(proto.STRING, number=158459920, optional=True,) + city = proto.Field(proto.STRING, number=3053931, optional=True,) + continent = proto.Field( + proto.ENUM, number=133442996, optional=True, enum=Continent, + ) + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + facility_provider = proto.Field(proto.STRING, number=533303309, optional=True,) + facility_provider_facility_id = proto.Field( + proto.STRING, number=87269125, 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,) + peeringdb_facility_id = proto.Field(proto.STRING, number=536567094, optional=True,) region_infos = proto.RepeatedField( - proto.MESSAGE, number=43758714, message="InterconnectLocationRegionInfo", + proto.MESSAGE, number=312194170, message="InterconnectLocationRegionInfo", ) - - self_link = proto.Field(proto.STRING, number=187779341) - - status = proto.Field(proto.ENUM, number=181260274, enum=Status,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + status = proto.Field(proto.ENUM, number=181260274, optional=True, enum=Status,) class InterconnectLocationList(proto.Message): @@ -14177,37 +13382,35 @@ class InterconnectLocationList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="InterconnectLocation", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 InterconnectsGetDiagnosticsResponse(proto.Message): r"""Response for the InterconnectsGetDiagnosticsRequest. - Attributes: result (google.cloud.compute_v1.types.InterconnectDiagnostics): """ result = proto.Field( - proto.MESSAGE, number=139315229, message="InterconnectDiagnostics", + proto.MESSAGE, + number=139315229, + optional=True, + message="InterconnectDiagnostics", ) class LicenseResourceRequirements(proto.Message): r""" - Attributes: min_guest_cpu_count (int): Minimum number of guest cpus required to use @@ -14219,9 +13422,8 @@ class LicenseResourceRequirements(proto.Message): start. """ - min_guest_cpu_count = proto.Field(proto.INT32, number=209529380) - - min_memory_mb = proto.Field(proto.INT32, number=236350438) + min_guest_cpu_count = proto.Field(proto.INT32, number=477964836, optional=True,) + min_memory_mb = proto.Field(proto.INT32, number=504785894, optional=True,) class License(proto.Message): @@ -14265,32 +13467,25 @@ class License(proto.Message): disk. """ - charges_use_fee = proto.Field(proto.BOOL, number=103977166) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - license_code = proto.Field(proto.STRING, number=1467179) - - name = proto.Field(proto.STRING, number=3373707) - + charges_use_fee = proto.Field(proto.BOOL, number=372412622, optional=True,) + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + id = proto.Field(proto.STRING, number=3355, optional=True,) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) + license_code = proto.Field(proto.STRING, number=1467179, optional=True,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) resource_requirements = proto.Field( - proto.MESSAGE, number=214292769, message="LicenseResourceRequirements", + proto.MESSAGE, + number=214292769, + optional=True, + message="LicenseResourceRequirements", ) - - self_link = proto.Field(proto.STRING, number=187779341) - - transferable = proto.Field(proto.BOOL, number=4349893) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + transferable = proto.Field(proto.BOOL, number=4349893, optional=True,) class LicenseCodeLicenseAlias(proto.Message): r""" - Attributes: description (str): [Output Only] Description of this License Code. @@ -14299,9 +13494,8 @@ class LicenseCodeLicenseAlias(proto.Message): Code. """ - description = proto.Field(proto.STRING, number=154502140) - - self_link = proto.Field(proto.STRING, number=187779341) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) class LicenseCode(proto.Message): @@ -14342,36 +13536,27 @@ class LicenseCode(proto.Message): class State(proto.Enum): r"""[Output Only] Current state of this License Code.""" UNDEFINED_STATE = 0 - DISABLED = 248261244 + DISABLED = 516696700 ENABLED = 182130465 RESTRICTED = 261551195 - STATE_UNSPECIFIED = 202319945 + STATE_UNSPECIFIED = 470755401 TERMINATED = 250018339 - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + id = proto.Field(proto.STRING, number=3355, optional=True,) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) license_alias = proto.RepeatedField( proto.MESSAGE, number=43550930, message="LicenseCodeLicenseAlias", ) - - name = proto.Field(proto.STRING, number=3373707) - - self_link = proto.Field(proto.STRING, number=187779341) - - state = proto.Field(proto.ENUM, number=109757585, enum=State,) - - transferable = proto.Field(proto.BOOL, number=4349893) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + state = proto.Field(proto.ENUM, number=109757585, optional=True, enum=State,) + transferable = proto.Field(proto.BOOL, number=4349893, optional=True,) class LicensesListResponse(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -14395,20 +13580,17 @@ class LicensesListResponse(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="License",) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 LocalDisk(proto.Message): r""" - Attributes: disk_count (int): Specifies the number of such disks. @@ -14422,16 +13604,13 @@ class LocalDisk(proto.Message): its URL. """ - disk_count = proto.Field(proto.INT32, number=182933485) - - disk_size_gb = proto.Field(proto.INT32, number=47828279) - - disk_type = proto.Field(proto.STRING, number=93009052) + disk_count = proto.Field(proto.INT32, number=182933485, optional=True,) + disk_size_gb = proto.Field(proto.INT32, number=316263735, optional=True,) + disk_type = proto.Field(proto.STRING, number=93009052, optional=True,) class LogConfigCloudAuditOptions(proto.Message): r"""Write a Cloud Audit log - Attributes: authorization_logging_options (google.cloud.compute_v1.types.AuthorizationLoggingOptions): Information used by the Cloud Audit Logging @@ -14443,15 +13622,17 @@ class LogConfigCloudAuditOptions(proto.Message): class LogName(proto.Enum): r"""The log_name to populate in the Cloud Audit Record.""" UNDEFINED_LOG_NAME = 0 - ADMIN_ACTIVITY = 159067679 + ADMIN_ACTIVITY = 427503135 DATA_ACCESS = 238070681 - UNSPECIFIED_LOG_NAME = 142079726 + UNSPECIFIED_LOG_NAME = 410515182 authorization_logging_options = proto.Field( - proto.MESSAGE, number=217861624, message="AuthorizationLoggingOptions", + proto.MESSAGE, + number=217861624, + optional=True, + message="AuthorizationLoggingOptions", ) - - log_name = proto.Field(proto.ENUM, number=134478502, enum=LogName,) + log_name = proto.Field(proto.ENUM, number=402913958, optional=True, enum=LogName,) class LogConfigCounterOptions(proto.Message): @@ -14491,15 +13672,12 @@ class LogConfigCounterOptions(proto.Message): custom_fields = proto.RepeatedField( proto.MESSAGE, number=249651015, message="LogConfigCounterOptionsCustomField", ) - - field = proto.Field(proto.STRING, number=97427706) - - metric = proto.Field(proto.STRING, number=264631728) + field = proto.Field(proto.STRING, number=97427706, optional=True,) + metric = proto.Field(proto.STRING, number=533067184, optional=True,) class LogConfigDataAccessOptions(proto.Message): r"""Write a Data Access (Gin) log - Attributes: log_mode (google.cloud.compute_v1.types.LogConfigDataAccessOptions.LogMode): @@ -14508,15 +13686,14 @@ class LogConfigDataAccessOptions(proto.Message): class LogMode(proto.Enum): r"""""" UNDEFINED_LOG_MODE = 0 - LOG_FAIL_CLOSED = 92034322 + LOG_FAIL_CLOSED = 360469778 LOG_MODE_UNSPECIFIED = 88160822 - log_mode = proto.Field(proto.ENUM, number=134461886, enum=LogMode,) + log_mode = proto.Field(proto.ENUM, number=402897342, optional=True, enum=LogMode,) class LogConfig(proto.Message): r"""Specifies what kind of log the caller must write - Attributes: cloud_audit (google.cloud.compute_v1.types.LogConfigCloudAuditOptions): Cloud audit options. @@ -14527,15 +13704,22 @@ class LogConfig(proto.Message): """ cloud_audit = proto.Field( - proto.MESSAGE, number=144417105, message="LogConfigCloudAuditOptions", + proto.MESSAGE, + number=412852561, + optional=True, + message="LogConfigCloudAuditOptions", ) - counter = proto.Field( - proto.MESSAGE, number=152524284, message="LogConfigCounterOptions", + proto.MESSAGE, + number=420959740, + optional=True, + message="LogConfigCounterOptions", ) - data_access = proto.Field( - proto.MESSAGE, number=18198425, message="LogConfigDataAccessOptions", + proto.MESSAGE, + number=286633881, + optional=True, + message="LogConfigDataAccessOptions", ) @@ -14553,14 +13737,12 @@ class LogConfigCounterOptionsCustomField(proto.Message): from the IAMContext. """ - name = proto.Field(proto.STRING, number=3373707) - - value = proto.Field(proto.STRING, number=111972721) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + value = proto.Field(proto.STRING, number=111972721, optional=True,) class Accelerators(proto.Message): r""" - Attributes: guest_accelerator_count (int): Number of accelerator cards exposed to the @@ -14570,20 +13752,18 @@ class Accelerators(proto.Message): full URL, e.g. 'nvidia-tesla-k80'. """ - guest_accelerator_count = proto.Field(proto.INT32, number=210643860) - - guest_accelerator_type = proto.Field(proto.STRING, number=24629269) + guest_accelerator_count = proto.Field(proto.INT32, number=479079316, optional=True,) + guest_accelerator_type = proto.Field(proto.STRING, number=293064725, optional=True,) class ScratchDisks(proto.Message): r""" - Attributes: disk_gb (int): Size of the scratch disk, defined in GB. """ - disk_gb = proto.Field(proto.INT32, number=60990141) + disk_gb = proto.Field(proto.INT32, number=60990141, optional=True,) class MachineType(proto.Message): @@ -14642,47 +13822,35 @@ class MachineType(proto.Message): """ accelerators = proto.RepeatedField( - proto.MESSAGE, number=1141608, message="Accelerators", + proto.MESSAGE, number=269577064, message="Accelerators", ) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) deprecated = proto.Field( - proto.MESSAGE, number=246703539, message="DeprecationStatus", - ) - - description = proto.Field(proto.STRING, number=154502140) - - guest_cpus = proto.Field(proto.INT32, number=124921298) - - id = proto.Field(proto.STRING, number=3355) - - image_space_gb = proto.Field(proto.INT32, number=75331864) - - is_shared_cpu = proto.Field(proto.BOOL, number=252964099) - - kind = proto.Field(proto.STRING, number=3292052) - - maximum_persistent_disks = proto.Field(proto.INT32, number=227785485) - - maximum_persistent_disks_size_gb = proto.Field(proto.STRING, number=154274471) - - memory_mb = proto.Field(proto.INT32, number=116001171) - - name = proto.Field(proto.STRING, number=3373707) - + proto.MESSAGE, number=515138995, optional=True, message="DeprecationStatus", + ) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + guest_cpus = proto.Field(proto.INT32, number=393356754, optional=True,) + id = proto.Field(proto.STRING, number=3355, optional=True,) + image_space_gb = proto.Field(proto.INT32, number=75331864, optional=True,) + is_shared_cpu = proto.Field(proto.BOOL, number=521399555, optional=True,) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) + maximum_persistent_disks = proto.Field( + proto.INT32, number=496220941, optional=True, + ) + maximum_persistent_disks_size_gb = proto.Field( + proto.STRING, number=154274471, optional=True, + ) + memory_mb = proto.Field(proto.INT32, number=116001171, optional=True,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) scratch_disks = proto.RepeatedField( - proto.MESSAGE, number=212343025, message="ScratchDisks", + proto.MESSAGE, number=480778481, message="ScratchDisks", ) - - self_link = proto.Field(proto.STRING, number=187779341) - - zone = proto.Field(proto.STRING, number=3744684) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + zone = proto.Field(proto.STRING, number=3744684, optional=True,) class MachineTypesScopedList(proto.Message): r""" - Attributes: machine_types (Sequence[google.cloud.compute_v1.types.MachineType]): [Output Only] A list of machine types contained in this @@ -14695,13 +13863,13 @@ class MachineTypesScopedList(proto.Message): machine_types = proto.RepeatedField( proto.MESSAGE, number=79720065, message="MachineType", ) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", + ) class MachineTypeAggregatedList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -14731,26 +13899,21 @@ class MachineTypeAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="MachineTypesScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 MachineTypeList(proto.Message): r"""Contains a list of machine types. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -14777,22 +13940,18 @@ class MachineTypeList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="MachineType",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 ManagedInstanceInstanceHealth(proto.Message): r""" - Attributes: detailed_health_state (google.cloud.compute_v1.types.ManagedInstanceInstanceHealth.DetailedHealthState): [Output Only] The current detailed instance health state. @@ -14804,34 +13963,33 @@ class ManagedInstanceInstanceHealth(proto.Message): class DetailedHealthState(proto.Enum): r"""[Output Only] The current detailed instance health state.""" UNDEFINED_DETAILED_HEALTH_STATE = 0 - DRAINING = 212019946 - HEALTHY = 171365757 - TIMEOUT = 209377601 - UNHEALTHY = 193682628 - UNKNOWN = 164706346 + DRAINING = 480455402 + HEALTHY = 439801213 + TIMEOUT = 477813057 + UNHEALTHY = 462118084 + UNKNOWN = 433141802 detailed_health_state = proto.Field( - proto.ENUM, number=242034717, enum=DetailedHealthState, + proto.ENUM, number=510470173, optional=True, enum=DetailedHealthState, ) - - health_check = proto.Field(proto.STRING, number=40441189) + health_check = proto.Field(proto.STRING, number=308876645, optional=True,) class ManagedInstanceLastAttempt(proto.Message): r""" - Attributes: errors (google.cloud.compute_v1.types.Errors): [Output Only] Encountered errors during the last attempt to create or delete the instance. """ - errors = proto.Field(proto.MESSAGE, number=47542123, message="Errors",) + errors = proto.Field( + proto.MESSAGE, number=315977579, optional=True, message="Errors", + ) class PreservedState(proto.Message): r"""Preserved state for a given instance. - Attributes: disks (Sequence[google.cloud.compute_v1.types.PreservedState.DisksEntry]): Preserved disks defined for this instance. @@ -14847,13 +14005,11 @@ class PreservedState(proto.Message): number=95594102, message="PreservedStatePreservedDisk", ) - - metadata = proto.MapField(proto.STRING, proto.STRING, number=86866735) + metadata = proto.MapField(proto.STRING, proto.STRING, number=86866735,) class Errors(proto.Message): r""" - Attributes: code (str): [Output Only] The error type identifier for this error. @@ -14864,16 +14020,13 @@ class Errors(proto.Message): [Output Only] An optional, human-readable error message. """ - code = proto.Field(proto.STRING, number=3059181) - - location = proto.Field(proto.STRING, number=21995445) - - message = proto.Field(proto.STRING, number=149618695) + code = proto.Field(proto.STRING, number=3059181, optional=True,) + location = proto.Field(proto.STRING, number=290430901, optional=True,) + message = proto.Field(proto.STRING, number=418054151, optional=True,) class Items(proto.Message): r""" - Attributes: key (str): Key for the metadata entry. Keys must conform to the @@ -14890,9 +14043,8 @@ class Items(proto.Message): 262144 bytes (256 KiB). """ - key = proto.Field(proto.STRING, number=106079) - - value = proto.Field(proto.STRING, number=111972721) + key = proto.Field(proto.STRING, number=106079, optional=True,) + value = proto.Field(proto.STRING, number=111972721, optional=True,) class MetadataFilterLabelMatch(proto.Message): @@ -14912,9 +14064,8 @@ class MetadataFilterLabelMatch(proto.Message): of 1024 characters. """ - name = proto.Field(proto.STRING, number=3373707) - - value = proto.Field(proto.STRING, number=111972721) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + value = proto.Field(proto.STRING, number=111972721, optional=True,) class NetworkPeering(proto.Message): @@ -14991,30 +14142,24 @@ class State(proto.Enum): configuration in the peer network. """ UNDEFINED_STATE = 0 - ACTIVE = 46297862 - INACTIVE = 1985643 - - auto_create_routes = proto.Field(proto.BOOL, number=57454941) - - exchange_subnet_routes = proto.Field(proto.BOOL, number=26322256) - - export_custom_routes = proto.Field(proto.BOOL, number=60281485) - - export_subnet_routes_with_public_ip = proto.Field(proto.BOOL, number=97940834) - - import_custom_routes = proto.Field(proto.BOOL, number=197982398) - - import_subnet_routes_with_public_ip = proto.Field(proto.BOOL, number=14419729) - - name = proto.Field(proto.STRING, number=3373707) - - network = proto.Field(proto.STRING, number=232872494) - - peer_mtu = proto.Field(proto.INT32, number=69584721) + ACTIVE = 314733318 + INACTIVE = 270421099 - state = proto.Field(proto.ENUM, number=109757585, enum=State,) - - state_details = proto.Field(proto.STRING, number=95566996) + auto_create_routes = proto.Field(proto.BOOL, number=57454941, optional=True,) + exchange_subnet_routes = proto.Field(proto.BOOL, number=26322256, optional=True,) + export_custom_routes = proto.Field(proto.BOOL, number=60281485, optional=True,) + export_subnet_routes_with_public_ip = proto.Field( + proto.BOOL, number=97940834, optional=True, + ) + import_custom_routes = proto.Field(proto.BOOL, number=197982398, optional=True,) + import_subnet_routes_with_public_ip = proto.Field( + proto.BOOL, number=14419729, optional=True, + ) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + network = proto.Field(proto.STRING, number=232872494, optional=True,) + peer_mtu = proto.Field(proto.INT32, number=69584721, optional=True,) + state = proto.Field(proto.ENUM, number=109757585, optional=True, enum=State,) + state_details = proto.Field(proto.STRING, number=95566996, optional=True,) class NetworkRoutingConfig(proto.Message): @@ -15042,10 +14187,12 @@ class RoutingMode(proto.Enum): with all subnets of this network, across regions. """ UNDEFINED_ROUTING_MODE = 0 - GLOBAL = 226228131 + GLOBAL = 494663587 REGIONAL = 92288543 - routing_mode = proto.Field(proto.ENUM, number=206708092, enum=RoutingMode,) + routing_mode = proto.Field( + proto.ENUM, number=475143548, optional=True, enum=RoutingMode, + ) class Network(proto.Message): @@ -15117,35 +14264,23 @@ class Network(proto.Message): subnetworks in this VPC network. """ - auto_create_subnetworks = proto.Field(proto.BOOL, number=256156690) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - gateway_i_pv4 = proto.Field(proto.STRING, number=178678877) - - i_pv4_range = proto.Field(proto.STRING, number=1978454) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - mtu = proto.Field(proto.INT32, number=108462) - - name = proto.Field(proto.STRING, number=3373707) - + 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,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) peerings = proto.RepeatedField( proto.MESSAGE, number=69883187, message="NetworkPeering", ) - routing_config = proto.Field( - proto.MESSAGE, number=255120603, message="NetworkRoutingConfig", + proto.MESSAGE, number=523556059, optional=True, message="NetworkRoutingConfig", ) - - self_link = proto.Field(proto.STRING, number=187779341) - - subnetworks = proto.RepeatedField(proto.STRING, number=147417669) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + subnetworks = proto.RepeatedField(proto.STRING, number=415853125,) class NetworkEndpointGroupAppEngine(proto.Message): @@ -15182,11 +14317,9 @@ class NetworkEndpointGroupAppEngine(proto.Message): Example value: "v1", "v2". """ - service = proto.Field(proto.STRING, number=105105077) - - url_mask = proto.Field(proto.STRING, number=103352252) - - version = proto.Field(proto.STRING, number=83172568) + service = proto.Field(proto.STRING, number=373540533, optional=True,) + url_mask = proto.Field(proto.STRING, number=103352252, optional=True,) + version = proto.Field(proto.STRING, number=351608024, optional=True,) class NetworkEndpointGroupCloudFunction(proto.Message): @@ -15214,9 +14347,8 @@ class NetworkEndpointGroupCloudFunction(proto.Message): } and { function = "function2" } respectively. """ - function = proto.Field(proto.STRING, number=38761432) - - url_mask = proto.Field(proto.STRING, number=103352252) + function = proto.Field(proto.STRING, number=307196888, optional=True,) + url_mask = proto.Field(proto.STRING, number=103352252, optional=True,) class NetworkEndpointGroupCloudRun(proto.Message): @@ -15253,11 +14385,9 @@ class NetworkEndpointGroupCloudRun(proto.Message): service="bar2", tag="foo2" } respectively. """ - service = proto.Field(proto.STRING, number=105105077) - - tag = proto.Field(proto.STRING, number=114586) - - url_mask = proto.Field(proto.STRING, number=103352252) + service = proto.Field(proto.STRING, number=373540533, optional=True,) + tag = proto.Field(proto.STRING, number=114586, optional=True,) + url_mask = proto.Field(proto.STRING, number=103352252, optional=True,) class NetworkEndpointGroup(proto.Message): @@ -15342,58 +14472,50 @@ class NetworkEndpointType(proto.Enum): INTERNET_IP_PORT, or SERVERLESS. """ UNDEFINED_NETWORK_ENDPOINT_TYPE = 0 - GCE_VM_IP_PORT = 233402919 - INTERNET_FQDN_PORT = 135719021 - INTERNET_IP_PORT = 209284507 - NON_GCP_PRIVATE_IP_PORT = 68012512 - SERVERLESS = 2057052 - - annotations = proto.MapField(proto.STRING, proto.STRING, number=112032548) + GCE_VM_IP_PORT = 501838375 + INTERNET_FQDN_PORT = 404154477 + INTERNET_IP_PORT = 477719963 + NON_GCP_PRIVATE_IP_PORT = 336447968 + SERVERLESS = 270492508 + annotations = proto.MapField(proto.STRING, proto.STRING, number=112032548,) app_engine = proto.Field( - proto.MESSAGE, number=72353312, message="NetworkEndpointGroupAppEngine", + proto.MESSAGE, + number=340788768, + optional=True, + message="NetworkEndpointGroupAppEngine", ) - cloud_function = proto.Field( - proto.MESSAGE, number=251458210, message="NetworkEndpointGroupCloudFunction", + proto.MESSAGE, + number=519893666, + optional=True, + message="NetworkEndpointGroupCloudFunction", ) - cloud_run = proto.Field( - proto.MESSAGE, number=111060353, message="NetworkEndpointGroupCloudRun", - ) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - default_port = proto.Field(proto.INT32, number=154942399) - - description = proto.Field(proto.STRING, number=154502140) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - - network = proto.Field(proto.STRING, number=232872494) - + proto.MESSAGE, + number=111060353, + optional=True, + message="NetworkEndpointGroupCloudRun", + ) + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + default_port = proto.Field(proto.INT32, number=423377855, optional=True,) + description = proto.Field(proto.STRING, number=422937596, 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,) + network = proto.Field(proto.STRING, number=232872494, optional=True,) network_endpoint_type = proto.Field( - proto.ENUM, number=118301523, enum=NetworkEndpointType, + proto.ENUM, number=118301523, optional=True, enum=NetworkEndpointType, ) - - region = proto.Field(proto.STRING, number=138946292) - - self_link = proto.Field(proto.STRING, number=187779341) - - size = proto.Field(proto.INT32, number=3530753) - - subnetwork = proto.Field(proto.STRING, number=39392238) - - zone = proto.Field(proto.STRING, number=3744684) + region = proto.Field(proto.STRING, number=138946292, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + size = proto.Field(proto.INT32, number=3530753, optional=True,) + subnetwork = proto.Field(proto.STRING, number=307827694, optional=True,) + zone = proto.Field(proto.STRING, number=3744684, optional=True,) class NetworkEndpointGroupsScopedList(proto.Message): r""" - Attributes: network_endpoint_groups (Sequence[google.cloud.compute_v1.types.NetworkEndpointGroup]): [Output Only] The list of network endpoint groups that are @@ -15406,13 +14528,13 @@ class NetworkEndpointGroupsScopedList(proto.Message): network_endpoint_groups = proto.RepeatedField( proto.MESSAGE, number=29346733, message="NetworkEndpointGroup", ) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", + ) class NetworkEndpointGroupAggregatedList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -15443,29 +14565,24 @@ class NetworkEndpointGroupAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="NetworkEndpointGroupsScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 NetworkEndpointGroupList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -15493,24 +14610,20 @@ class NetworkEndpointGroupList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="NetworkEndpointGroup", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 NetworkEndpointGroupsAttachEndpointsRequest(proto.Message): r""" - Attributes: network_endpoints (Sequence[google.cloud.compute_v1.types.NetworkEndpoint]): The list of network endpoints to be attached. @@ -15523,7 +14636,6 @@ class NetworkEndpointGroupsAttachEndpointsRequest(proto.Message): class NetworkEndpointGroupsDetachEndpointsRequest(proto.Message): r""" - Attributes: network_endpoints (Sequence[google.cloud.compute_v1.types.NetworkEndpoint]): The list of network endpoints to be detached. @@ -15536,7 +14648,6 @@ class NetworkEndpointGroupsDetachEndpointsRequest(proto.Message): class NetworkEndpointGroupsListEndpointsRequest(proto.Message): r""" - Attributes: health_status (google.cloud.compute_v1.types.NetworkEndpointGroupsListEndpointsRequest.HealthStatus): Optional query parameter for showing the @@ -15556,12 +14667,13 @@ class HealthStatus(proto.Enum): SHOW = 2544381 SKIP = 2547071 - health_status = proto.Field(proto.ENUM, number=112110389, enum=HealthStatus,) + health_status = proto.Field( + proto.ENUM, number=380545845, optional=True, enum=HealthStatus, + ) class NetworkEndpointWithHealthStatus(proto.Message): r""" - Attributes: healths (Sequence[google.cloud.compute_v1.types.HealthStatusForNetworkEndpoint]): [Output only] The health status of network endpoint; @@ -15572,15 +14684,13 @@ class NetworkEndpointWithHealthStatus(proto.Message): healths = proto.RepeatedField( proto.MESSAGE, number=258689431, message="HealthStatusForNetworkEndpoint", ) - network_endpoint = proto.Field( - proto.MESSAGE, number=56789126, message="NetworkEndpoint", + proto.MESSAGE, number=56789126, optional=True, message="NetworkEndpoint", ) class NetworkEndpointGroupsListNetworkEndpoints(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -15608,22 +14718,19 @@ class NetworkEndpointGroupsListNetworkEndpoints(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="NetworkEndpointWithHealthStatus", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 NetworkList(proto.Message): r"""Contains a list of networks. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -15650,22 +14757,18 @@ class NetworkList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="Network",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 NetworksAddPeeringRequest(proto.Message): r""" - Attributes: auto_create_routes (bool): This field will be deprecated soon. Use @@ -15694,45 +14797,39 @@ class NetworksAddPeeringRequest(proto.Message): current network. """ - auto_create_routes = proto.Field(proto.BOOL, number=57454941) - - name = proto.Field(proto.STRING, number=3373707) - + auto_create_routes = proto.Field(proto.BOOL, number=57454941, optional=True,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) network_peering = proto.Field( - proto.MESSAGE, number=60491311, message="NetworkPeering", + proto.MESSAGE, number=328926767, optional=True, message="NetworkPeering", ) - - peer_network = proto.Field(proto.STRING, number=232190033) + peer_network = proto.Field(proto.STRING, number=500625489, optional=True,) class NetworksRemovePeeringRequest(proto.Message): r""" - Attributes: name (str): Name of the peering, which should conform to RFC1035. """ - name = proto.Field(proto.STRING, number=3373707) + name = proto.Field(proto.STRING, number=3373707, optional=True,) class NetworksUpdatePeeringRequest(proto.Message): r""" - Attributes: network_peering (google.cloud.compute_v1.types.NetworkPeering): """ network_peering = proto.Field( - proto.MESSAGE, number=60491311, message="NetworkPeering", + proto.MESSAGE, number=328926767, optional=True, message="NetworkPeering", ) class NodeGroupAutoscalingPolicy(proto.Message): r""" - Attributes: max_nodes (int): The maximum number of nodes that the group @@ -15751,16 +14848,14 @@ class Mode(proto.Enum): more information, see Autoscaler modes. """ UNDEFINED_MODE = 0 - MODE_UNSPECIFIED = 102912635 + MODE_UNSPECIFIED = 371348091 OFF = 78159 ON = 2527 ONLY_SCALE_OUT = 152713670 - max_nodes = proto.Field(proto.INT32, number=29327382) - - min_nodes = proto.Field(proto.INT32, number=264935044) - - mode = proto.Field(proto.ENUM, number=3357091, enum=Mode,) + max_nodes = proto.Field(proto.INT32, number=297762838, optional=True,) + min_nodes = proto.Field(proto.INT32, number=533370500, optional=True,) + mode = proto.Field(proto.ENUM, number=3357091, optional=True, enum=Mode,) class NodeGroupMaintenanceWindow(proto.Message): @@ -15780,10 +14875,9 @@ class NodeGroupMaintenanceWindow(proto.Message): """ maintenance_duration = proto.Field( - proto.MESSAGE, number=256856384, message="Duration", + proto.MESSAGE, number=525291840, optional=True, message="Duration", ) - - start_time = proto.Field(proto.STRING, number=37467274) + start_time = proto.Field(proto.STRING, number=37467274, optional=True,) class NodeGroup(proto.Message): @@ -15859,49 +14953,41 @@ class MaintenancePolicy(proto.Enum): class Status(proto.Enum): r"""""" UNDEFINED_STATUS = 0 - CREATING = 187129529 - DELETING = 260166568 - INVALID = 261848535 + CREATING = 455564985 + DELETING = 528602024 + INVALID = 530283991 READY = 77848963 autoscaling_policy = proto.Field( - proto.MESSAGE, number=221950041, message="NodeGroupAutoscalingPolicy", - ) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - fingerprint = proto.Field(proto.STRING, number=234678500) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - + proto.MESSAGE, + number=221950041, + optional=True, + message="NodeGroupAutoscalingPolicy", + ) + 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,) maintenance_policy = proto.Field( - proto.ENUM, number=259892190, enum=MaintenancePolicy, + proto.ENUM, number=528327646, optional=True, enum=MaintenancePolicy, ) - maintenance_window = proto.Field( - proto.MESSAGE, number=186374812, message="NodeGroupMaintenanceWindow", + proto.MESSAGE, + number=186374812, + optional=True, + message="NodeGroupMaintenanceWindow", ) - - name = proto.Field(proto.STRING, number=3373707) - - node_template = proto.Field(proto.STRING, number=54718999) - - self_link = proto.Field(proto.STRING, number=187779341) - - size = proto.Field(proto.INT32, number=3530753) - - status = proto.Field(proto.ENUM, number=181260274, enum=Status,) - - zone = proto.Field(proto.STRING, number=3744684) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + node_template = proto.Field(proto.STRING, number=323154455, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + size = proto.Field(proto.INT32, number=3530753, optional=True,) + status = proto.Field(proto.ENUM, number=181260274, optional=True, enum=Status,) + zone = proto.Field(proto.STRING, number=3744684, optional=True,) class NodeGroupsScopedList(proto.Message): r""" - Attributes: node_groups (Sequence[google.cloud.compute_v1.types.NodeGroup]): [Output Only] A list of node groups contained in this scope. @@ -15913,13 +14999,13 @@ class NodeGroupsScopedList(proto.Message): node_groups = proto.RepeatedField( proto.MESSAGE, number=73188017, message="NodeGroup", ) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", + ) class NodeGroupAggregatedList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -15949,26 +15035,21 @@ class NodeGroupAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="NodeGroupsScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 NodeGroupList(proto.Message): r"""Contains a list of nodeGroups. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -15995,22 +15076,18 @@ class NodeGroupList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="NodeGroup",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 ServerBinding(proto.Message): r""" - Attributes: type_ (google.cloud.compute_v1.types.ServerBinding.Type): @@ -16019,16 +15096,15 @@ class ServerBinding(proto.Message): class Type(proto.Enum): r"""""" UNDEFINED_TYPE = 0 - RESTART_NODE_ON_ANY_SERVER = 234515529 + RESTART_NODE_ON_ANY_SERVER = 502950985 RESTART_NODE_ON_MINIMAL_SERVERS = 204166495 SERVER_BINDING_TYPE_UNSPECIFIED = 180825512 - type_ = proto.Field(proto.ENUM, number=3575610, enum=Type,) + type_ = proto.Field(proto.ENUM, number=3575610, optional=True, enum=Type,) class NodeGroupNode(proto.Message): r""" - Attributes: accelerators (Sequence[google.cloud.compute_v1.types.AcceleratorConfig]): Accelerators for this node. @@ -16053,70 +15129,59 @@ class NodeGroupNode(proto.Message): class CpuOvercommitType(proto.Enum): r"""CPU overcommit.""" UNDEFINED_CPU_OVERCOMMIT_TYPE = 0 - CPU_OVERCOMMIT_TYPE_UNSPECIFIED = 252230159 + CPU_OVERCOMMIT_TYPE_UNSPECIFIED = 520665615 ENABLED = 182130465 NONE = 2402104 class Status(proto.Enum): r"""""" UNDEFINED_STATUS = 0 - CREATING = 187129529 - DELETING = 260166568 - INVALID = 261848535 + CREATING = 455564985 + DELETING = 528602024 + INVALID = 530283991 READY = 77848963 - REPAIRING = 145047829 + REPAIRING = 413483285 accelerators = proto.RepeatedField( - proto.MESSAGE, number=1141608, message="AcceleratorConfig", + proto.MESSAGE, number=269577064, message="AcceleratorConfig", ) - cpu_overcommit_type = proto.Field( - proto.ENUM, number=247727959, enum=CpuOvercommitType, + proto.ENUM, number=247727959, optional=True, enum=CpuOvercommitType, ) - disks = proto.RepeatedField(proto.MESSAGE, number=95594102, message="LocalDisk",) - - instances = proto.RepeatedField(proto.STRING, number=29097598) - - name = proto.Field(proto.STRING, number=3373707) - - node_type = proto.Field(proto.STRING, number=197397335) - + 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,) server_binding = proto.Field( - proto.MESSAGE, number=208179593, message="ServerBinding", + proto.MESSAGE, number=208179593, optional=True, message="ServerBinding", ) - - server_id = proto.Field(proto.STRING, number=70997911) - - status = proto.Field(proto.ENUM, number=181260274, enum=Status,) + server_id = proto.Field(proto.STRING, number=339433367, optional=True,) + status = proto.Field(proto.ENUM, number=181260274, optional=True, enum=Status,) class NodeGroupsAddNodesRequest(proto.Message): r""" - Attributes: additional_node_count (int): Count of additional nodes to be added to the node group. """ - additional_node_count = proto.Field(proto.INT32, number=134997930) + additional_node_count = proto.Field(proto.INT32, number=134997930, optional=True,) class NodeGroupsDeleteNodesRequest(proto.Message): r""" - Attributes: nodes (Sequence[str]): Names of the nodes to delete. """ - nodes = proto.RepeatedField(proto.STRING, number=104993457) + nodes = proto.RepeatedField(proto.STRING, number=104993457,) class NodeGroupsListNodes(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -16144,36 +15209,31 @@ class NodeGroupsListNodes(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="NodeGroupNode", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 NodeGroupsSetNodeTemplateRequest(proto.Message): r""" - Attributes: node_template (str): Full or partial URL of the node template resource to be updated for this node group. """ - node_template = proto.Field(proto.STRING, number=54718999) + node_template = proto.Field(proto.STRING, number=323154455, optional=True,) class NodeTemplateNodeTypeFlexibility(proto.Message): r""" - Attributes: cpus (str): @@ -16183,11 +15243,9 @@ class NodeTemplateNodeTypeFlexibility(proto.Message): """ - cpus = proto.Field(proto.STRING, number=3060683) - - local_ssd = proto.Field(proto.STRING, number=137305904) - - memory = proto.Field(proto.STRING, number=264420609) + cpus = proto.Field(proto.STRING, number=3060683, optional=True,) + local_ssd = proto.Field(proto.STRING, number=405741360, optional=True,) + memory = proto.Field(proto.STRING, number=532856065, optional=True,) class NodeTemplate(proto.Message): @@ -16265,7 +15323,7 @@ class NodeTemplate(proto.Message): class CpuOvercommitType(proto.Enum): r"""CPU overcommit.""" UNDEFINED_CPU_OVERCOMMIT_TYPE = 0 - CPU_OVERCOMMIT_TYPE_UNSPECIFIED = 252230159 + CPU_OVERCOMMIT_TYPE_UNSPECIFIED = 520665615 ENABLED = 182130465 NONE = 2402104 @@ -16274,55 +15332,42 @@ class Status(proto.Enum): values: CREATING, READY, and DELETING. """ UNDEFINED_STATUS = 0 - CREATING = 187129529 - DELETING = 260166568 - INVALID = 261848535 + CREATING = 455564985 + DELETING = 528602024 + INVALID = 530283991 READY = 77848963 accelerators = proto.RepeatedField( - proto.MESSAGE, number=1141608, message="AcceleratorConfig", + proto.MESSAGE, number=269577064, message="AcceleratorConfig", ) - cpu_overcommit_type = proto.Field( - proto.ENUM, number=247727959, enum=CpuOvercommitType, + proto.ENUM, number=247727959, optional=True, enum=CpuOvercommitType, ) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) disks = proto.RepeatedField(proto.MESSAGE, number=95594102, message="LocalDisk",) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - - node_affinity_labels = proto.MapField(proto.STRING, proto.STRING, number=70571705) - - node_type = proto.Field(proto.STRING, number=197397335) - + 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,) + node_affinity_labels = proto.MapField(proto.STRING, proto.STRING, number=339007161,) + node_type = proto.Field(proto.STRING, number=465832791, optional=True,) node_type_flexibility = proto.Field( - proto.MESSAGE, number=46822449, message="NodeTemplateNodeTypeFlexibility", + proto.MESSAGE, + number=315257905, + optional=True, + message="NodeTemplateNodeTypeFlexibility", ) - - region = proto.Field(proto.STRING, number=138946292) - - self_link = proto.Field(proto.STRING, number=187779341) - + region = proto.Field(proto.STRING, number=138946292, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) server_binding = proto.Field( - proto.MESSAGE, number=208179593, message="ServerBinding", + proto.MESSAGE, number=208179593, optional=True, message="ServerBinding", ) - - status = proto.Field(proto.ENUM, number=181260274, enum=Status,) - - status_message = proto.Field(proto.STRING, number=28992698) + status = proto.Field(proto.ENUM, number=181260274, optional=True, enum=Status,) + status_message = proto.Field(proto.STRING, number=297428154, optional=True,) class NodeTemplatesScopedList(proto.Message): r""" - Attributes: node_templates (Sequence[google.cloud.compute_v1.types.NodeTemplate]): [Output Only] A list of node templates contained in this @@ -16333,15 +15378,15 @@ class NodeTemplatesScopedList(proto.Message): """ node_templates = proto.RepeatedField( - proto.MESSAGE, number=85676348, message="NodeTemplate", + proto.MESSAGE, number=354111804, message="NodeTemplate", + ) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", ) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) class NodeTemplateAggregatedList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -16371,29 +15416,24 @@ class NodeTemplateAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="NodeTemplatesScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 NodeTemplateList(proto.Message): r"""Contains a list of node templates. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -16420,19 +15460,16 @@ class NodeTemplateList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="NodeTemplate", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 NodeType(proto.Message): @@ -16480,36 +15517,24 @@ class NodeType(proto.Message): resides, such as us-central1-a. """ - cpu_platform = proto.Field(proto.STRING, number=141849898) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - + cpu_platform = proto.Field(proto.STRING, number=410285354, optional=True,) + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) deprecated = proto.Field( - proto.MESSAGE, number=246703539, message="DeprecationStatus", + proto.MESSAGE, number=515138995, optional=True, message="DeprecationStatus", ) - - description = proto.Field(proto.STRING, number=154502140) - - guest_cpus = proto.Field(proto.INT32, number=124921298) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - local_ssd_gb = proto.Field(proto.INT32, number=60802122) - - memory_mb = proto.Field(proto.INT32, number=116001171) - - name = proto.Field(proto.STRING, number=3373707) - - self_link = proto.Field(proto.STRING, number=187779341) - - zone = proto.Field(proto.STRING, number=3744684) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + guest_cpus = proto.Field(proto.INT32, number=393356754, optional=True,) + id = proto.Field(proto.STRING, number=3355, optional=True,) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) + local_ssd_gb = proto.Field(proto.INT32, number=329237578, optional=True,) + memory_mb = proto.Field(proto.INT32, number=116001171, optional=True,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + zone = proto.Field(proto.STRING, number=3744684, optional=True,) class NodeTypesScopedList(proto.Message): r""" - Attributes: node_types (Sequence[google.cloud.compute_v1.types.NodeType]): [Output Only] A list of node types contained in this scope. @@ -16519,15 +15544,15 @@ class NodeTypesScopedList(proto.Message): """ node_types = proto.RepeatedField( - proto.MESSAGE, number=213737468, message="NodeType", + proto.MESSAGE, number=482172924, message="NodeType", + ) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", ) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) class NodeTypeAggregatedList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -16557,26 +15582,21 @@ class NodeTypeAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="NodeTypesScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 NodeTypeList(proto.Message): r"""Contains a list of node types. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -16603,17 +15623,14 @@ class NodeTypeList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="NodeType",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 NotificationEndpointGrpcSettings(proto.Message): @@ -16647,15 +15664,13 @@ class NotificationEndpointGrpcSettings(proto.Message): Limit is 20m (1200s). Must be a positive number. """ - authority = proto.Field(proto.STRING, number=133433155) - - endpoint = proto.Field(proto.STRING, number=130489749) - - payload_name = proto.Field(proto.STRING, number=31922844) - - resend_interval = proto.Field(proto.MESSAGE, number=209853513, message="Duration",) - - retry_duration_sec = proto.Field(proto.UINT32, number=115681117) + authority = proto.Field(proto.STRING, number=401868611, optional=True,) + endpoint = proto.Field(proto.STRING, number=130489749, optional=True,) + payload_name = proto.Field(proto.STRING, number=300358300, optional=True,) + resend_interval = proto.Field( + proto.MESSAGE, number=478288969, optional=True, message="Duration", + ) + retry_duration_sec = proto.Field(proto.UINT32, number=115681117, optional=True,) class NotificationEndpoint(proto.Message): @@ -16705,28 +15720,23 @@ class NotificationEndpoint(proto.Message): [Output Only] Server-defined URL for the resource. """ - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) grpc_settings = proto.Field( - proto.MESSAGE, number=187704100, message="NotificationEndpointGrpcSettings", + proto.MESSAGE, + number=456139556, + optional=True, + message="NotificationEndpointGrpcSettings", ) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - - region = proto.Field(proto.STRING, number=138946292) - - self_link = proto.Field(proto.STRING, number=187779341) + 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,) + region = proto.Field(proto.STRING, number=138946292, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) class NotificationEndpointList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -16753,19 +15763,16 @@ class NotificationEndpointList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="NotificationEndpoint", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 Error(proto.Message): @@ -16778,12 +15785,11 @@ class Error(proto.Message): processing this operation. """ - errors = proto.RepeatedField(proto.MESSAGE, number=47542123, message="Errors",) + errors = proto.RepeatedField(proto.MESSAGE, number=315977579, message="Errors",) class Warnings(proto.Message): r""" - Attributes: code (google.cloud.compute_v1.types.Warnings.Code): [Output Only] A warning code, if applicable. For example, @@ -16805,36 +15811,34 @@ class Code(proto.Enum): """ UNDEFINED_CODE = 0 CLEANUP_FAILED = 150308440 - DEPRECATED_RESOURCE_USED = 123400130 - DEPRECATED_TYPE_USED = 78090774 - DISK_SIZE_LARGER_THAN_IMAGE_SIZE = 101007511 - EXPERIMENTAL_TYPE_USED = 183518987 + DEPRECATED_RESOURCE_USED = 391835586 + DEPRECATED_TYPE_USED = 346526230 + DISK_SIZE_LARGER_THAN_IMAGE_SIZE = 369442967 + EXPERIMENTAL_TYPE_USED = 451954443 EXTERNAL_API_WARNING = 175546307 - FIELD_VALUE_OVERRIDEN = 61233967 - INJECTED_KERNELS_DEPRECATED = 148941963 - LARGE_DEPLOYMENT_WARNING = 213005222 - MISSING_TYPE_DEPENDENCY = 76070007 - NEXT_HOP_ADDRESS_NOT_ASSIGNED = 56529543 - NEXT_HOP_CANNOT_IP_FORWARD = 114947431 - NEXT_HOP_INSTANCE_NOT_FOUND = 195814990 + FIELD_VALUE_OVERRIDEN = 329669423 + INJECTED_KERNELS_DEPRECATED = 417377419 + LARGE_DEPLOYMENT_WARNING = 481440678 + MISSING_TYPE_DEPENDENCY = 344505463 + NEXT_HOP_ADDRESS_NOT_ASSIGNED = 324964999 + NEXT_HOP_CANNOT_IP_FORWARD = 383382887 + NEXT_HOP_INSTANCE_NOT_FOUND = 464250446 NEXT_HOP_INSTANCE_NOT_ON_NETWORK = 243758146 - NEXT_HOP_NOT_RUNNING = 148645809 + NEXT_HOP_NOT_RUNNING = 417081265 NOT_CRITICAL_ERROR = 105763924 NO_RESULTS_ON_PAGE = 30036744 PARTIAL_SUCCESS = 39966469 REQUIRED_TOS_AGREEMENT = 3745539 - RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING = 228293185 + RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING = 496728641 RESOURCE_NOT_DELETED = 168598460 - SCHEMA_VALIDATION_IGNORED = 6810186 + SCHEMA_VALIDATION_IGNORED = 275245642 SINGLE_INSTANCE_PROPERTY_TEMPLATE = 268305617 - UNDECLARED_PROPERTIES = 122077983 + UNDECLARED_PROPERTIES = 390513439 UNREACHABLE = 13328052 - code = proto.Field(proto.ENUM, number=3059181, enum=Code,) - + code = proto.Field(proto.ENUM, number=3059181, optional=True, enum=Code,) data = proto.RepeatedField(proto.MESSAGE, number=3076010, message="Data",) - - message = proto.Field(proto.STRING, number=149618695) + message = proto.Field(proto.STRING, number=418054151, optional=True,) class Operation(proto.Message): @@ -16950,56 +15954,33 @@ class Status(proto.Enum): PENDING = 35394935 RUNNING = 121282975 - client_operation_id = proto.Field(proto.STRING, number=28804839) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - end_time = proto.Field(proto.STRING, number=114938801) - - error = proto.Field(proto.MESSAGE, number=96784904, message="Error",) - - http_error_message = proto.Field(proto.STRING, number=202521945) - - http_error_status_code = proto.Field(proto.INT32, number=43909740) - - id = proto.Field(proto.STRING, number=3355) - - insert_time = proto.Field(proto.STRING, number=165287059) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - - operation_type = proto.Field(proto.STRING, number=177650450) - - progress = proto.Field(proto.INT32, number=72663597) - - region = proto.Field(proto.STRING, number=138946292) - - self_link = proto.Field(proto.STRING, number=187779341) - - start_time = proto.Field(proto.STRING, number=37467274) - - status = proto.Field(proto.ENUM, number=181260274, enum=Status,) - - status_message = proto.Field(proto.STRING, number=28992698) - - target_id = proto.Field(proto.STRING, number=258165385) - - target_link = proto.Field(proto.STRING, number=62671336) - - user = proto.Field(proto.STRING, number=3599307) - - warnings = proto.RepeatedField(proto.MESSAGE, number=229655639, message="Warnings",) - - zone = proto.Field(proto.STRING, number=3744684) + client_operation_id = proto.Field(proto.STRING, number=297240295, optional=True,) + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + end_time = proto.Field(proto.STRING, number=114938801, optional=True,) + error = proto.Field(proto.MESSAGE, number=96784904, optional=True, message="Error",) + http_error_message = proto.Field(proto.STRING, number=202521945, optional=True,) + http_error_status_code = proto.Field(proto.INT32, number=312345196, optional=True,) + id = proto.Field(proto.STRING, number=3355, optional=True,) + 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_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,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + start_time = proto.Field(proto.STRING, number=37467274, optional=True,) + status = proto.Field(proto.ENUM, number=181260274, optional=True, enum=Status,) + status_message = proto.Field(proto.STRING, number=297428154, optional=True,) + target_id = proto.Field(proto.STRING, number=258165385, optional=True,) + target_link = proto.Field(proto.STRING, number=62671336, optional=True,) + user = proto.Field(proto.STRING, number=3599307, optional=True,) + warnings = proto.RepeatedField(proto.MESSAGE, number=498091095, message="Warnings",) + zone = proto.Field(proto.STRING, number=3744684, optional=True,) class OperationsScopedList(proto.Message): r""" - Attributes: operations (Sequence[google.cloud.compute_v1.types.Operation]): [Output Only] A list of operations contained in this scope. @@ -17011,13 +15992,13 @@ class OperationsScopedList(proto.Message): operations = proto.RepeatedField( proto.MESSAGE, number=4184044, message="Operation", ) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", + ) class OperationAggregatedList(proto.Message): r""" - Attributes: id (str): [Output Only] The unique identifier for the resource. This @@ -17047,26 +16028,21 @@ class OperationAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="OperationsScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 OperationList(proto.Message): r"""Contains a list of Operation resources. - Attributes: id (str): [Output Only] The unique identifier for the resource. This @@ -17093,22 +16069,18 @@ class OperationList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="Operation",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 PacketMirroringForwardingRuleInfo(proto.Message): r""" - Attributes: canonical_url (str): [Output Only] Unique identifier for the forwarding rule; @@ -17119,14 +16091,12 @@ class PacketMirroringForwardingRuleInfo(proto.Message): of the mirrored traffic. """ - canonical_url = proto.Field(proto.STRING, number=243859364) - - url = proto.Field(proto.STRING, number=116079) + canonical_url = proto.Field(proto.STRING, number=512294820, optional=True,) + url = proto.Field(proto.STRING, number=116079, optional=True,) class PacketMirroringFilter(proto.Message): r""" - Attributes: cidr_ranges (Sequence[str]): IP CIDR ranges that apply as filter on the @@ -17154,19 +16124,18 @@ class Direction(proto.Enum): """ UNDEFINED_DIRECTION = 0 BOTH = 2044801 - EGRESS = 164445045 - INGRESS = 248495765 - - cidr_ranges = proto.RepeatedField(proto.STRING, number=219466241) + EGRESS = 432880501 + INGRESS = 516931221 - direction = proto.Field(proto.ENUM, number=111150975, enum=Direction,) - - i_p_protocols = proto.RepeatedField(proto.STRING, number=104889590) + 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): r""" - Attributes: instances (Sequence[google.cloud.compute_v1.types.PacketMirroringMirroredResourceInfoInstanceInfo]): A set of virtual machine instances that are @@ -17194,19 +16163,16 @@ class PacketMirroringMirroredResourceInfo(proto.Message): number=29097598, message="PacketMirroringMirroredResourceInfoInstanceInfo", ) - subnetworks = proto.RepeatedField( proto.MESSAGE, - number=147417669, + number=415853125, message="PacketMirroringMirroredResourceInfoSubnetInfo", ) - - tags = proto.RepeatedField(proto.STRING, number=3552281) + tags = proto.RepeatedField(proto.STRING, number=3552281,) class PacketMirroringNetworkInfo(proto.Message): r""" - Attributes: canonical_url (str): [Output Only] Unique identifier for the network; defined by @@ -17215,9 +16181,8 @@ class PacketMirroringNetworkInfo(proto.Message): URL of the network resource. """ - canonical_url = proto.Field(proto.STRING, number=243859364) - - url = proto.Field(proto.STRING, number=116079) + canonical_url = proto.Field(proto.STRING, number=512294820, optional=True,) + url = proto.Field(proto.STRING, number=116079, optional=True,) class PacketMirroring(proto.Message): @@ -17303,43 +16268,39 @@ class Enable(proto.Enum): TRUE = 2583950 collector_ilb = proto.Field( - proto.MESSAGE, number=158172397, message="PacketMirroringForwardingRuleInfo", + proto.MESSAGE, + number=426607853, + optional=True, + message="PacketMirroringForwardingRuleInfo", ) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - enable = proto.Field(proto.ENUM, number=43328899, enum=Enable,) - + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + enable = proto.Field(proto.ENUM, number=311764355, optional=True, enum=Enable,) filter = proto.Field( - proto.MESSAGE, number=67685240, message="PacketMirroringFilter", + proto.MESSAGE, number=336120696, optional=True, message="PacketMirroringFilter", ) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - + id = proto.Field(proto.STRING, number=3355, optional=True,) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) mirrored_resources = proto.Field( - proto.MESSAGE, number=124817348, message="PacketMirroringMirroredResourceInfo", + proto.MESSAGE, + number=124817348, + optional=True, + message="PacketMirroringMirroredResourceInfo", ) - - name = proto.Field(proto.STRING, number=3373707) - + name = proto.Field(proto.STRING, number=3373707, optional=True,) network = proto.Field( - proto.MESSAGE, number=232872494, message="PacketMirroringNetworkInfo", + proto.MESSAGE, + number=232872494, + optional=True, + message="PacketMirroringNetworkInfo", ) - - priority = proto.Field(proto.UINT32, number=176716196) - - region = proto.Field(proto.STRING, number=138946292) - - self_link = proto.Field(proto.STRING, number=187779341) + priority = proto.Field(proto.UINT32, number=445151652, optional=True,) + region = proto.Field(proto.STRING, number=138946292, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) class PacketMirroringsScopedList(proto.Message): r""" - Attributes: packet_mirrorings (Sequence[google.cloud.compute_v1.types.PacketMirroring]): A list of packetMirrorings contained in this @@ -17352,13 +16313,13 @@ class PacketMirroringsScopedList(proto.Message): packet_mirrorings = proto.RepeatedField( proto.MESSAGE, number=154615079, message="PacketMirroring", ) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", + ) class PacketMirroringAggregatedList(proto.Message): r"""Contains a list of packetMirrorings. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -17386,29 +16347,24 @@ class PacketMirroringAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="PacketMirroringsScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 PacketMirroringList(proto.Message): r"""Contains a list of PacketMirroring resources. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -17435,24 +16391,20 @@ class PacketMirroringList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="PacketMirroring", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 PacketMirroringMirroredResourceInfoInstanceInfo(proto.Message): r""" - Attributes: canonical_url (str): [Output Only] Unique identifier for the instance; defined by @@ -17462,14 +16414,12 @@ class PacketMirroringMirroredResourceInfoInstanceInfo(proto.Message): which is being mirrored. """ - canonical_url = proto.Field(proto.STRING, number=243859364) - - url = proto.Field(proto.STRING, number=116079) + canonical_url = proto.Field(proto.STRING, number=512294820, optional=True,) + url = proto.Field(proto.STRING, number=116079, optional=True,) class PacketMirroringMirroredResourceInfoSubnetInfo(proto.Message): r""" - Attributes: canonical_url (str): [Output Only] Unique identifier for the subnetwork; defined @@ -17480,9 +16430,8 @@ class PacketMirroringMirroredResourceInfoSubnetInfo(proto.Message): mirrored. """ - canonical_url = proto.Field(proto.STRING, number=243859364) - - url = proto.Field(proto.STRING, number=116079) + canonical_url = proto.Field(proto.STRING, number=512294820, optional=True,) + url = proto.Field(proto.STRING, number=116079, optional=True,) class PathRule(proto.Message): @@ -17531,16 +16480,13 @@ class PathRule(proto.Message): the URL map is bound to target gRPC proxy. """ - paths = proto.RepeatedField(proto.STRING, number=106438894) - + paths = proto.RepeatedField(proto.STRING, number=106438894,) route_action = proto.Field( - proto.MESSAGE, number=156128492, message="HttpRouteAction", + proto.MESSAGE, number=424563948, optional=True, message="HttpRouteAction", ) - - service = proto.Field(proto.STRING, number=105105077) - + service = proto.Field(proto.STRING, number=373540533, optional=True,) url_redirect = proto.Field( - proto.MESSAGE, number=136712364, message="HttpRedirectAction", + proto.MESSAGE, number=405147820, optional=True, message="HttpRedirectAction", ) @@ -17636,35 +16582,27 @@ class PathMatcher(proto.Message): """ default_route_action = proto.Field( - proto.MESSAGE, number=110484010, message="HttpRouteAction", + proto.MESSAGE, number=378919466, optional=True, message="HttpRouteAction", ) - - default_service = proto.Field(proto.STRING, number=101806775) - + default_service = proto.Field(proto.STRING, number=370242231, optional=True,) default_url_redirect = proto.Field( - proto.MESSAGE, number=91067882, message="HttpRedirectAction", + proto.MESSAGE, number=359503338, optional=True, message="HttpRedirectAction", ) - - description = proto.Field(proto.STRING, number=154502140) - + description = proto.Field(proto.STRING, number=422937596, optional=True,) header_action = proto.Field( - proto.MESSAGE, number=59641896, message="HttpHeaderAction", + proto.MESSAGE, number=328077352, optional=True, message="HttpHeaderAction", ) - - name = proto.Field(proto.STRING, number=3373707) - + name = proto.Field(proto.STRING, number=3373707, optional=True,) path_rules = proto.RepeatedField( proto.MESSAGE, number=104439901, message="PathRule", ) - route_rules = proto.RepeatedField( - proto.MESSAGE, number=107856769, message="HttpRouteRule", + proto.MESSAGE, number=376292225, message="HttpRouteRule", ) class Rule(proto.Message): r"""A rule to be applied in a Policy. - Attributes: action (google.cloud.compute_v1.types.Rule.Action): Required @@ -17698,32 +16636,25 @@ class Action(proto.Enum): ALLOW = 62368553 ALLOW_WITH_LOG = 76034177 DENY = 2094604 - DENY_WITH_LOG = 82998526 + DENY_WITH_LOG = 351433982 LOG = 75556 NO_ACTION = 260643444 - action = proto.Field(proto.ENUM, number=187661878, enum=Action,) - + action = proto.Field(proto.ENUM, number=187661878, optional=True, enum=Action,) conditions = proto.RepeatedField( proto.MESSAGE, number=142882488, message="Condition", ) - - description = proto.Field(proto.STRING, number=154502140) - - ins = proto.RepeatedField(proto.STRING, number=104430) - + description = proto.Field(proto.STRING, number=422937596, optional=True,) + ins = proto.RepeatedField(proto.STRING, number=104430,) log_configs = proto.RepeatedField( proto.MESSAGE, number=152873846, message="LogConfig", ) - - not_ins = proto.RepeatedField(proto.STRING, number=250007682) - - permissions = proto.RepeatedField(proto.STRING, number=59962500) + not_ins = proto.RepeatedField(proto.STRING, number=518443138,) + permissions = proto.RepeatedField(proto.STRING, number=59962500,) class WafExpressionSet(proto.Message): r""" - Attributes: aliases (Sequence[str]): A list of alternate IDs. The format should @@ -17739,18 +16670,15 @@ class WafExpressionSet(proto.Message): format should be: - E.g. XSS-20170329 """ - aliases = proto.RepeatedField(proto.STRING, number=159207166) - + aliases = proto.RepeatedField(proto.STRING, number=159207166,) expressions = proto.RepeatedField( proto.MESSAGE, number=175554779, message="WafExpressionSetExpression", ) - - id = proto.Field(proto.STRING, number=3355) + id = proto.Field(proto.STRING, number=3355, optional=True,) class PreconfiguredWafSet(proto.Message): r""" - Attributes: expression_sets (Sequence[google.cloud.compute_v1.types.WafExpressionSet]): List of entities that are currently supported @@ -17758,13 +16686,12 @@ class PreconfiguredWafSet(proto.Message): """ expression_sets = proto.RepeatedField( - proto.MESSAGE, number=205575576, message="WafExpressionSet", + proto.MESSAGE, number=474011032, message="WafExpressionSet", ) class PreservedStatePreservedDisk(proto.Message): r""" - Attributes: auto_delete (google.cloud.compute_v1.types.PreservedStatePreservedDisk.AutoDelete): These stateful disks will never be deleted during @@ -17802,16 +16729,15 @@ class Mode(proto.Enum): READ_ONLY = 91950261 READ_WRITE = 173607894 - auto_delete = proto.Field(proto.ENUM, number=196325947, enum=AutoDelete,) - - mode = proto.Field(proto.ENUM, number=3357091, enum=Mode,) - - source = proto.Field(proto.STRING, number=177235995) + auto_delete = proto.Field( + proto.ENUM, number=464761403, optional=True, enum=AutoDelete, + ) + mode = proto.Field(proto.ENUM, number=3357091, optional=True, enum=Mode,) + source = proto.Field(proto.STRING, number=177235995, optional=True,) class Quota(proto.Message): r"""A quotas entry. - Attributes: limit (float): [Output Only] Quota limit for this metric. @@ -17829,120 +16755,117 @@ class Metric(proto.Enum): UNDEFINED_METRIC = 0 A2_CPUS = 153206585 AFFINITY_GROUPS = 108303563 - AUTOSCALERS = 202813532 + AUTOSCALERS = 471248988 BACKEND_BUCKETS = 137626846 - BACKEND_SERVICES = 1188297 - C2_CPUS = 49165755 - COMMITMENTS = 187706334 + BACKEND_SERVICES = 269623753 + C2_CPUS = 317601211 + COMMITMENTS = 456141790 COMMITTED_A2_CPUS = 59330902 COMMITTED_C2_CPUS = 223725528 - COMMITTED_CPUS = 23959246 - COMMITTED_LICENSES = 89171413 - COMMITTED_LOCAL_SSD_TOTAL_GB = 39958024 - COMMITTED_MEMORY_OPTIMIZED_CPUS = 220622430 + COMMITTED_CPUS = 292394702 + COMMITTED_LICENSES = 357606869 + COMMITTED_LOCAL_SSD_TOTAL_GB = 308393480 + COMMITTED_MEMORY_OPTIMIZED_CPUS = 489057886 COMMITTED_N2D_CPUS = 125951757 - COMMITTED_N2_CPUS = 54154147 - COMMITTED_NVIDIA_A100_GPUS = 107363989 + COMMITTED_N2_CPUS = 322589603 + COMMITTED_NVIDIA_A100_GPUS = 375799445 COMMITTED_NVIDIA_K80_GPUS = 3857188 COMMITTED_NVIDIA_P100_GPUS = 107528100 - COMMITTED_NVIDIA_P4_GPUS = 79517441 + COMMITTED_NVIDIA_P4_GPUS = 347952897 COMMITTED_NVIDIA_T4_GPUS = 139871237 COMMITTED_NVIDIA_V100_GPUS = 219562 CPUS = 2075595 - CPUS_ALL_REGIONS = 202475693 - DISKS_TOTAL_GB = 85085087 - EXTERNAL_NETWORK_LB_FORWARDING_RULES = 105862809 + CPUS_ALL_REGIONS = 470911149 + DISKS_TOTAL_GB = 353520543 + EXTERNAL_NETWORK_LB_FORWARDING_RULES = 374298265 EXTERNAL_PROTOCOL_FORWARDING_RULES = 63478888 - EXTERNAL_VPN_GATEWAYS = 4021678 - FIREWALLS = 106050387 - FORWARDING_RULES = 164233493 + EXTERNAL_VPN_GATEWAYS = 272457134 + FIREWALLS = 374485843 + FORWARDING_RULES = 432668949 GLOBAL_INTERNAL_ADDRESSES = 42738332 GPUS_ALL_REGIONS = 39387177 - HEALTH_CHECKS = 20912046 + HEALTH_CHECKS = 289347502 IMAGES = 15562360 INSTANCES = 131337822 - INSTANCE_GROUPS = 87483582 + INSTANCE_GROUPS = 355919038 INSTANCE_GROUP_MANAGERS = 101798192 INSTANCE_TEMPLATES = 226188271 - INTERCONNECTS = 146769285 + INTERCONNECTS = 415204741 INTERCONNECT_ATTACHMENTS_PER_REGION = 159968086 - INTERCONNECT_ATTACHMENTS_TOTAL_MBPS = 156654963 - INTERCONNECT_TOTAL_GBPS = 16906410 + INTERCONNECT_ATTACHMENTS_TOTAL_MBPS = 425090419 + INTERCONNECT_TOTAL_GBPS = 285341866 INTERNAL_ADDRESSES = 197899392 INTERNAL_TRAFFIC_DIRECTOR_FORWARDING_RULES = 266433668 IN_PLACE_SNAPSHOTS = 151359133 - IN_USE_ADDRESSES = 133689616 + IN_USE_ADDRESSES = 402125072 IN_USE_BACKUP_SCHEDULES = 32786705 - IN_USE_SNAPSHOT_SCHEDULES = 193668627 - LOCAL_SSD_TOTAL_GB = 62442565 + IN_USE_SNAPSHOT_SCHEDULES = 462104083 + LOCAL_SSD_TOTAL_GB = 330878021 M1_CPUS = 37203366 M2_CPUS = 65832517 - MACHINE_IMAGES = 178551184 - N2D_CPUS = 83307914 - N2_CPUS = 148029830 - NETWORKS = 217046021 + MACHINE_IMAGES = 446986640 + N2D_CPUS = 351743370 + N2_CPUS = 416465286 + NETWORKS = 485481477 NETWORK_ENDPOINT_GROUPS = 102144909 NETWORK_FIREWALL_POLICIES = 101117374 NODE_GROUPS = 24624817 - NODE_TEMPLATES = 206461212 - NVIDIA_A100_GPUS = 236437522 + NODE_TEMPLATES = 474896668 + NVIDIA_A100_GPUS = 504872978 NVIDIA_K80_GPUS = 163886599 NVIDIA_P100_GPUS = 236601633 NVIDIA_P100_VWS_GPUS = 213970574 - NVIDIA_P4_GPUS = 15406014 - NVIDIA_P4_VWS_GPUS = 259861163 + NVIDIA_P4_GPUS = 283841470 + NVIDIA_P4_VWS_GPUS = 528296619 NVIDIA_T4_GPUS = 75759810 - NVIDIA_T4_VWS_GPUS = 51377583 + NVIDIA_T4_VWS_GPUS = 319813039 NVIDIA_V100_GPUS = 129293095 PACKET_MIRRORINGS = 15578407 PREEMPTIBLE_CPUS = 251184841 PREEMPTIBLE_LOCAL_SSD_GB = 260819336 PREEMPTIBLE_NVIDIA_A100_GPUS = 68832784 - PREEMPTIBLE_NVIDIA_K80_GPUS = 106524745 - PREEMPTIBLE_NVIDIA_P100_GPUS = 68996895 - PREEMPTIBLE_NVIDIA_P100_VWS_GPUS = 45108620 - PREEMPTIBLE_NVIDIA_P4_GPUS = 160762172 + PREEMPTIBLE_NVIDIA_K80_GPUS = 374960201 + PREEMPTIBLE_NVIDIA_P100_GPUS = 337432351 + PREEMPTIBLE_NVIDIA_P100_VWS_GPUS = 313544076 + PREEMPTIBLE_NVIDIA_P4_GPUS = 429197628 PREEMPTIBLE_NVIDIA_P4_VWS_GPUS = 252981545 PREEMPTIBLE_NVIDIA_T4_GPUS = 221115968 PREEMPTIBLE_NVIDIA_T4_VWS_GPUS = 44497965 PREEMPTIBLE_NVIDIA_V100_GPUS = 230123813 PSC_ILB_CONSUMER_FORWARDING_RULES_PER_PRODUCER_NETWORK = 231164291 - PUBLIC_ADVERTISED_PREFIXES = 202936524 - PUBLIC_DELEGATED_PREFIXES = 264030518 + PUBLIC_ADVERTISED_PREFIXES = 471371980 + PUBLIC_DELEGATED_PREFIXES = 532465974 REGIONAL_AUTOSCALERS = 29363772 REGIONAL_INSTANCE_GROUP_MANAGERS = 37543696 RESERVATIONS = 32644647 RESOURCE_POLICIES = 83955297 - ROUTERS = 224583210 - ROUTES = 7244618 + ROUTERS = 493018666 + ROUTES = 275680074 SECURITY_POLICIES = 189518703 - SECURITY_POLICY_CEVAL_RULES = 202380233 + SECURITY_POLICY_CEVAL_RULES = 470815689 SECURITY_POLICY_RULES = 203549225 - SNAPSHOTS = 74969871 + SNAPSHOTS = 343405327 SSD_TOTAL_GB = 161732561 - SSL_CERTIFICATES = 109936943 + SSL_CERTIFICATES = 378372399 STATIC_ADDRESSES = 93624049 - STATIC_BYOIP_ADDRESSES = 7374193 - SUBNETWORKS = 152895013 + STATIC_BYOIP_ADDRESSES = 275809649 + SUBNETWORKS = 421330469 TARGET_HTTPS_PROXIES = 219522506 TARGET_HTTP_PROXIES = 164117155 - TARGET_INSTANCES = 16084272 - TARGET_POOLS = 79825801 + TARGET_INSTANCES = 284519728 + TARGET_POOLS = 348261257 TARGET_SSL_PROXIES = 159216235 TARGET_TCP_PROXIES = 182243136 TARGET_VPN_GATEWAYS = 75029928 - URL_MAPS = 110225287 + URL_MAPS = 378660743 VPN_GATEWAYS = 35620282 VPN_TUNNELS = 104327296 XPN_SERVICE_PROJECTS = 95191981 - limit = proto.Field(proto.DOUBLE, number=102976443) - - metric = proto.Field(proto.ENUM, number=264631728, enum=Metric,) - - owner = proto.Field(proto.STRING, number=106164915) - - usage = proto.Field(proto.DOUBLE, number=111574433) + limit = proto.Field(proto.DOUBLE, number=102976443, optional=True,) + metric = proto.Field(proto.ENUM, number=533067184, optional=True, enum=Metric,) + owner = proto.Field(proto.STRING, number=106164915, optional=True,) + usage = proto.Field(proto.DOUBLE, number=111574433, optional=True,) class UsageExportLocation(proto.Message): @@ -17969,9 +16892,8 @@ class UsageExportLocation(proto.Message): conventions. """ - bucket_name = proto.Field(proto.STRING, number=15174592) - - report_name_prefix = proto.Field(proto.STRING, number=51763259) + bucket_name = proto.Field(proto.STRING, number=283610048, optional=True,) + report_name_prefix = proto.Field(proto.STRING, number=320198715, optional=True,) class Project(proto.Message): @@ -18036,8 +16958,8 @@ class DefaultNetworkTier(proto.Enum): PREMIUM. """ UNDEFINED_DEFAULT_NETWORK_TIER = 0 - PREMIUM = 131095095 - STANDARD = 216207037 + PREMIUM = 399530551 + STANDARD = 484642493 class XpnProjectStatus(proto.Enum): r"""[Output Only] The role this project has in a shared VPC @@ -18046,46 +16968,35 @@ class XpnProjectStatus(proto.Enum): """ UNDEFINED_XPN_PROJECT_STATUS = 0 HOST = 2223528 - UNSPECIFIED_XPN_PROJECT_STATUS = 71957801 + UNSPECIFIED_XPN_PROJECT_STATUS = 340393257 common_instance_metadata = proto.Field( - proto.MESSAGE, number=185794117, message="Metadata", + proto.MESSAGE, number=185794117, optional=True, message="Metadata", ) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) default_network_tier = proto.Field( - proto.ENUM, number=203317905, enum=DefaultNetworkTier, + proto.ENUM, number=471753361, optional=True, enum=DefaultNetworkTier, ) - - default_service_account = proto.Field(proto.STRING, number=30276773) - - description = proto.Field(proto.STRING, number=154502140) - - enabled_features = proto.RepeatedField(proto.STRING, number=200582011) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - + default_service_account = proto.Field( + proto.STRING, number=298712229, optional=True, + ) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + enabled_features = proto.RepeatedField(proto.STRING, number=469017467,) + 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,) quotas = proto.RepeatedField(proto.MESSAGE, number=125341947, message="Quota",) - - self_link = proto.Field(proto.STRING, number=187779341) - + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) usage_export_location = proto.Field( - proto.MESSAGE, number=79108418, message="UsageExportLocation", + proto.MESSAGE, number=347543874, optional=True, message="UsageExportLocation", ) - xpn_project_status = proto.Field( - proto.ENUM, number=228419265, enum=XpnProjectStatus, + proto.ENUM, number=228419265, optional=True, enum=XpnProjectStatus, ) class XpnResourceId(proto.Message): r"""Service resource (a.k.a service project) ID. - Attributes: id (str): The ID of the service resource. In the case @@ -18099,43 +17010,39 @@ class XpnResourceId(proto.Message): class Type(proto.Enum): r"""The type of the service resource.""" UNDEFINED_TYPE = 0 - PROJECT = 140236537 + PROJECT = 408671993 XPN_RESOURCE_TYPE_UNSPECIFIED = 151607034 - id = proto.Field(proto.STRING, number=3355) - - type_ = proto.Field(proto.ENUM, number=3575610, enum=Type,) + id = proto.Field(proto.STRING, number=3355, optional=True,) + type_ = proto.Field(proto.ENUM, number=3575610, optional=True, enum=Type,) class ProjectsDisableXpnResourceRequest(proto.Message): r""" - Attributes: xpn_resource (google.cloud.compute_v1.types.XpnResourceId): Service resource (a.k.a service project) ID. """ xpn_resource = proto.Field( - proto.MESSAGE, number=133384631, message="XpnResourceId", + proto.MESSAGE, number=133384631, optional=True, message="XpnResourceId", ) class ProjectsEnableXpnResourceRequest(proto.Message): r""" - Attributes: xpn_resource (google.cloud.compute_v1.types.XpnResourceId): Service resource (a.k.a service project) ID. """ xpn_resource = proto.Field( - proto.MESSAGE, number=133384631, message="XpnResourceId", + proto.MESSAGE, number=133384631, optional=True, message="XpnResourceId", ) class ProjectsGetXpnResources(proto.Message): r""" - Attributes: kind (str): [Output Only] Type of resource. Always @@ -18158,10 +17065,8 @@ class ProjectsGetXpnResources(proto.Message): def raw_page(self): return self - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - + kind = proto.Field(proto.STRING, number=3292052, optional=True,) + next_page_token = proto.Field(proto.STRING, number=79797525, optional=True,) resources = proto.RepeatedField( proto.MESSAGE, number=164412965, message="XpnResourceId", ) @@ -18169,7 +17074,6 @@ def raw_page(self): class ProjectsListXpnHostsRequest(proto.Message): r""" - Attributes: organization (str): Optional organization ID managed by Cloud @@ -18178,12 +17082,11 @@ class ProjectsListXpnHostsRequest(proto.Message): organization will be inferred from the project. """ - organization = proto.Field(proto.STRING, number=105180467) + organization = proto.Field(proto.STRING, number=105180467, optional=True,) class ProjectsSetDefaultNetworkTierRequest(proto.Message): r""" - Attributes: network_tier (google.cloud.compute_v1.types.ProjectsSetDefaultNetworkTierRequest.NetworkTier): Default network tier to be set. @@ -18192,10 +17095,12 @@ class ProjectsSetDefaultNetworkTierRequest(proto.Message): class NetworkTier(proto.Enum): r"""Default network tier to be set.""" UNDEFINED_NETWORK_TIER = 0 - PREMIUM = 131095095 - STANDARD = 216207037 + PREMIUM = 399530551 + STANDARD = 484642493 - network_tier = proto.Field(proto.ENUM, number=248962387, enum=NetworkTier,) + network_tier = proto.Field( + proto.ENUM, number=517397843, optional=True, enum=NetworkTier, + ) class Region(proto.Message): @@ -18238,32 +17143,22 @@ class Status(proto.Enum): DOWN = 2104482 UP = 2715 - creation_timestamp = proto.Field(proto.STRING, number=30525366) - + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) deprecated = proto.Field( - proto.MESSAGE, number=246703539, message="DeprecationStatus", + proto.MESSAGE, number=515138995, optional=True, message="DeprecationStatus", ) - - description = proto.Field(proto.STRING, number=154502140) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - + description = proto.Field(proto.STRING, number=422937596, 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,) quotas = proto.RepeatedField(proto.MESSAGE, number=125341947, message="Quota",) - - self_link = proto.Field(proto.STRING, number=187779341) - - status = proto.Field(proto.ENUM, number=181260274, enum=Status,) - - zones = proto.RepeatedField(proto.STRING, number=116085319) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + status = proto.Field(proto.ENUM, number=181260274, optional=True, enum=Status,) + zones = proto.RepeatedField(proto.STRING, number=116085319,) class RegionAutoscalerList(proto.Message): r"""Contains a list of autoscalers. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -18289,22 +17184,18 @@ class RegionAutoscalerList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="Autoscaler",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 RegionDiskTypeList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -18331,57 +17222,50 @@ class RegionDiskTypeList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="DiskType",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 RegionDisksAddResourcePoliciesRequest(proto.Message): r""" - Attributes: resource_policies (Sequence[str]): Resource policies to be added to this disk. """ - resource_policies = proto.RepeatedField(proto.STRING, number=22220385) + resource_policies = proto.RepeatedField(proto.STRING, number=22220385,) class RegionDisksRemoveResourcePoliciesRequest(proto.Message): r""" - Attributes: resource_policies (Sequence[str]): Resource policies to be removed from this disk. """ - resource_policies = proto.RepeatedField(proto.STRING, number=22220385) + resource_policies = proto.RepeatedField(proto.STRING, number=22220385,) class RegionDisksResizeRequest(proto.Message): r""" - Attributes: size_gb (str): The new size of the regional persistent disk, which is specified in GB. """ - size_gb = proto.Field(proto.STRING, number=226493913) + size_gb = proto.Field(proto.STRING, number=494929369, optional=True,) class RegionInstanceGroupList(proto.Message): r"""Contains a list of InstanceGroup resources. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -18407,24 +17291,20 @@ class RegionInstanceGroupList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="InstanceGroup", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 RegionInstanceGroupManagerDeleteInstanceConfigReq(proto.Message): r"""RegionInstanceGroupManagers.deletePerInstanceConfigs - Attributes: names (Sequence[str]): The list of instance names for which we want @@ -18432,12 +17312,11 @@ class RegionInstanceGroupManagerDeleteInstanceConfigReq(proto.Message): instance group. """ - names = proto.RepeatedField(proto.STRING, number=104585032) + names = proto.RepeatedField(proto.STRING, number=104585032,) class RegionInstanceGroupManagerList(proto.Message): r"""Contains a list of managed instance groups. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -18465,24 +17344,20 @@ class RegionInstanceGroupManagerList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="InstanceGroupManager", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 RegionInstanceGroupManagerPatchInstanceConfigReq(proto.Message): r"""RegionInstanceGroupManagers.patchPerInstanceConfigs - Attributes: per_instance_configs (Sequence[google.cloud.compute_v1.types.PerInstanceConfig]): The list of per-instance configs to insert or @@ -18490,13 +17365,12 @@ class RegionInstanceGroupManagerPatchInstanceConfigReq(proto.Message): """ per_instance_configs = proto.RepeatedField( - proto.MESSAGE, number=257829545, message="PerInstanceConfig", + proto.MESSAGE, number=526265001, message="PerInstanceConfig", ) class RegionInstanceGroupManagerUpdateInstanceConfigReq(proto.Message): r"""RegionInstanceGroupManagers.updatePerInstanceConfigs - Attributes: per_instance_configs (Sequence[google.cloud.compute_v1.types.PerInstanceConfig]): The list of per-instance configs to insert or @@ -18504,13 +17378,12 @@ class RegionInstanceGroupManagerUpdateInstanceConfigReq(proto.Message): """ per_instance_configs = proto.RepeatedField( - proto.MESSAGE, number=257829545, message="PerInstanceConfig", + proto.MESSAGE, number=526265001, message="PerInstanceConfig", ) class RegionInstanceGroupManagersAbandonInstancesRequest(proto.Message): r""" - Attributes: instances (Sequence[str]): The URLs of one or more instances to abandon. This can be a @@ -18518,12 +17391,11 @@ class RegionInstanceGroupManagersAbandonInstancesRequest(proto.Message): zones/[ZONE]/instances/[INSTANCE_NAME]. """ - instances = proto.RepeatedField(proto.STRING, number=29097598) + instances = proto.RepeatedField(proto.STRING, number=29097598,) class RegionInstanceGroupManagersApplyUpdatesRequest(proto.Message): r"""RegionInstanceGroupManagers.applyUpdatesToInstances - Attributes: all_instances (bool): Flag to update all instances instead of @@ -18558,18 +17430,16 @@ class RegionInstanceGroupManagersApplyUpdatesRequest(proto.Message): the update request will fail. """ - all_instances = proto.Field(proto.BOOL, number=135241056) - - instances = proto.RepeatedField(proto.STRING, number=29097598) - - minimal_action = proto.Field(proto.STRING, number=2131604) - - most_disruptive_allowed_action = proto.Field(proto.STRING, number=66103053) + all_instances = proto.Field(proto.BOOL, number=403676512, optional=True,) + instances = proto.RepeatedField(proto.STRING, number=29097598,) + minimal_action = proto.Field(proto.STRING, number=270567060, optional=True,) + most_disruptive_allowed_action = proto.Field( + proto.STRING, number=66103053, optional=True, + ) class RegionInstanceGroupManagersCreateInstancesRequest(proto.Message): r"""RegionInstanceGroupManagers.createInstances - Attributes: instances (Sequence[google.cloud.compute_v1.types.PerInstanceConfig]): [Required] List of specifications of per-instance configs. @@ -18582,7 +17452,6 @@ class RegionInstanceGroupManagersCreateInstancesRequest(proto.Message): class RegionInstanceGroupManagersDeleteInstancesRequest(proto.Message): r""" - Attributes: instances (Sequence[str]): The URLs of one or more instances to delete. This can be a @@ -18590,12 +17459,11 @@ class RegionInstanceGroupManagersDeleteInstancesRequest(proto.Message): zones/[ZONE]/instances/[INSTANCE_NAME]. """ - instances = proto.RepeatedField(proto.STRING, number=29097598) + instances = proto.RepeatedField(proto.STRING, number=29097598,) class RegionInstanceGroupManagersListErrorsResponse(proto.Message): r""" - Attributes: items (Sequence[google.cloud.compute_v1.types.InstanceManagedByIgmError]): [Output Only] The list of errors of the managed instance @@ -18616,13 +17484,11 @@ def raw_page(self): items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="InstanceManagedByIgmError", ) - - next_page_token = proto.Field(proto.STRING, number=79797525) + next_page_token = proto.Field(proto.STRING, number=79797525, optional=True,) class RegionInstanceGroupManagersListInstanceConfigsResp(proto.Message): r""" - Attributes: items (Sequence[google.cloud.compute_v1.types.PerInstanceConfig]): [Output Only] The list of PerInstanceConfig. @@ -18644,15 +17510,14 @@ def raw_page(self): items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="PerInstanceConfig", ) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + next_page_token = proto.Field(proto.STRING, number=79797525, optional=True,) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", + ) class RegionInstanceGroupManagersListInstancesResponse(proto.Message): r""" - Attributes: managed_instances (Sequence[google.cloud.compute_v1.types.ManagedInstance]): A list of managed instances. @@ -18670,15 +17535,13 @@ def raw_page(self): return self managed_instances = proto.RepeatedField( - proto.MESSAGE, number=67784158, message="ManagedInstance", + proto.MESSAGE, number=336219614, message="ManagedInstance", ) - - next_page_token = proto.Field(proto.STRING, number=79797525) + next_page_token = proto.Field(proto.STRING, number=79797525, optional=True,) class RegionInstanceGroupManagersRecreateRequest(proto.Message): r""" - Attributes: instances (Sequence[str]): The URLs of one or more instances to recreate. This can be a @@ -18686,12 +17549,11 @@ class RegionInstanceGroupManagersRecreateRequest(proto.Message): zones/[ZONE]/instances/[INSTANCE_NAME]. """ - instances = proto.RepeatedField(proto.STRING, number=29097598) + instances = proto.RepeatedField(proto.STRING, number=29097598,) class RegionInstanceGroupManagersSetTargetPoolsRequest(proto.Message): r""" - Attributes: fingerprint (str): Fingerprint of the target pools information, @@ -18705,26 +17567,23 @@ class RegionInstanceGroupManagersSetTargetPoolsRequest(proto.Message): the instances in the managed instance group. """ - fingerprint = proto.Field(proto.STRING, number=234678500) - - target_pools = proto.RepeatedField(proto.STRING, number=67637161) + fingerprint = proto.Field(proto.STRING, number=234678500, optional=True,) + target_pools = proto.RepeatedField(proto.STRING, number=336072617,) class RegionInstanceGroupManagersSetTemplateRequest(proto.Message): r""" - Attributes: instance_template (str): URL of the InstanceTemplate resource from which all new instances will be created. """ - instance_template = proto.Field(proto.STRING, number=40812772) + instance_template = proto.Field(proto.STRING, number=309248228, optional=True,) class RegionInstanceGroupsListInstances(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -18750,24 +17609,20 @@ class RegionInstanceGroupsListInstances(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="InstanceWithNamedPorts", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 RegionInstanceGroupsListInstancesRequest(proto.Message): r""" - Attributes: instance_state (google.cloud.compute_v1.types.RegionInstanceGroupsListInstancesRequest.InstanceState): Instances in which state should be returned. @@ -18789,14 +17644,14 @@ class InstanceState(proto.Enum): ALL = 64897 RUNNING = 121282975 - instance_state = proto.Field(proto.ENUM, number=92223591, enum=InstanceState,) - - port_name = proto.Field(proto.STRING, number=41534345) + instance_state = proto.Field( + proto.ENUM, number=92223591, optional=True, enum=InstanceState, + ) + port_name = proto.Field(proto.STRING, number=41534345, optional=True,) class RegionInstanceGroupsSetNamedPortsRequest(proto.Message): r""" - Attributes: fingerprint (str): The fingerprint of the named ports @@ -18813,16 +17668,14 @@ class RegionInstanceGroupsSetNamedPortsRequest(proto.Message): instance group. """ - fingerprint = proto.Field(proto.STRING, number=234678500) - + fingerprint = proto.Field(proto.STRING, number=234678500, optional=True,) named_ports = proto.RepeatedField( - proto.MESSAGE, number=159163276, message="NamedPort", + proto.MESSAGE, number=427598732, message="NamedPort", ) class RegionList(proto.Message): r"""Contains a list of region resources. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -18849,22 +17702,18 @@ class RegionList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="Region",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 RegionSetLabelsRequest(proto.Message): r""" - Attributes: label_fingerprint (str): The fingerprint of the previous set of labels @@ -18879,14 +17728,12 @@ class RegionSetLabelsRequest(proto.Message): The labels to set for this resource. """ - label_fingerprint = proto.Field(proto.STRING, number=178124825) - - labels = proto.MapField(proto.STRING, proto.STRING, number=231759871) + label_fingerprint = proto.Field(proto.STRING, number=178124825, optional=True,) + labels = proto.MapField(proto.STRING, proto.STRING, number=500195327,) class RegionSetPolicyRequest(proto.Message): r""" - Attributes: bindings (Sequence[google.cloud.compute_v1.types.Binding]): Flatten Policy to create a backwacd @@ -18904,16 +17751,15 @@ class RegionSetPolicyRequest(proto.Message): (like Projects) might reject them. """ - bindings = proto.RepeatedField(proto.MESSAGE, number=134816398, message="Binding",) - - etag = proto.Field(proto.STRING, number=3123477) - - policy = proto.Field(proto.MESSAGE, number=91071794, message="Policy",) + 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 RegionTargetHttpsProxiesSetSslCertificatesRequest(proto.Message): r""" - Attributes: ssl_certificates (Sequence[str]): New set of SslCertificate resources to @@ -18922,7 +17768,7 @@ class RegionTargetHttpsProxiesSetSslCertificatesRequest(proto.Message): must be specified. """ - ssl_certificates = proto.RepeatedField(proto.STRING, number=97571087) + ssl_certificates = proto.RepeatedField(proto.STRING, number=366006543,) class UrlMap(proto.Message): @@ -19062,61 +17908,47 @@ class UrlMap(proto.Message): that has validateForProxyless field set to true. """ - creation_timestamp = proto.Field(proto.STRING, number=30525366) - + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) default_route_action = proto.Field( - proto.MESSAGE, number=110484010, message="HttpRouteAction", + proto.MESSAGE, number=378919466, optional=True, message="HttpRouteAction", ) - - default_service = proto.Field(proto.STRING, number=101806775) - + default_service = proto.Field(proto.STRING, number=370242231, optional=True,) default_url_redirect = proto.Field( - proto.MESSAGE, number=91067882, message="HttpRedirectAction", + proto.MESSAGE, number=359503338, optional=True, message="HttpRedirectAction", ) - - description = proto.Field(proto.STRING, number=154502140) - - fingerprint = proto.Field(proto.STRING, number=234678500) - + description = proto.Field(proto.STRING, number=422937596, optional=True,) + fingerprint = proto.Field(proto.STRING, number=234678500, optional=True,) header_action = proto.Field( - proto.MESSAGE, number=59641896, message="HttpHeaderAction", + proto.MESSAGE, number=328077352, optional=True, message="HttpHeaderAction", ) - host_rules = proto.RepeatedField( - proto.MESSAGE, number=43369376, message="HostRule", + proto.MESSAGE, number=311804832, message="HostRule", ) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - + 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,) path_matchers = proto.RepeatedField( - proto.MESSAGE, number=3228763, message="PathMatcher", + proto.MESSAGE, number=271664219, message="PathMatcher", ) - - region = proto.Field(proto.STRING, number=138946292) - - self_link = proto.Field(proto.STRING, number=187779341) - + region = proto.Field(proto.STRING, number=138946292, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) tests = proto.RepeatedField(proto.MESSAGE, number=110251553, message="UrlMapTest",) class RegionUrlMapsValidateRequest(proto.Message): r""" - Attributes: resource (google.cloud.compute_v1.types.UrlMap): Content of the UrlMap to be validated. """ - resource = proto.Field(proto.MESSAGE, number=195806222, message="UrlMap",) + resource = proto.Field( + proto.MESSAGE, number=195806222, optional=True, message="UrlMap", + ) class ReservationsScopedList(proto.Message): r""" - Attributes: reservations (Sequence[google.cloud.compute_v1.types.Reservation]): A list of reservations contained in this @@ -19127,15 +17959,15 @@ class ReservationsScopedList(proto.Message): """ reservations = proto.RepeatedField( - proto.MESSAGE, number=131282471, message="Reservation", + proto.MESSAGE, number=399717927, message="Reservation", + ) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", ) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) class ReservationAggregatedList(proto.Message): r"""Contains a list of reservations. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -19163,26 +17995,21 @@ class ReservationAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="ReservationsScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 ReservationList(proto.Message): r""" - Attributes: id (str): [Output Only] The unique identifier for the resource. This @@ -19209,34 +18036,29 @@ class ReservationList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="Reservation",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 ReservationsResizeRequest(proto.Message): r""" - Attributes: specific_sku_count (str): Number of allocated resources can be resized with minimum = 1 and maximum = 1000. """ - specific_sku_count = proto.Field(proto.STRING, number=13890720) + specific_sku_count = proto.Field(proto.STRING, number=13890720, optional=True,) class ResourceGroupReference(proto.Message): r""" - Attributes: group (str): A URI referencing one of the instance groups @@ -19244,7 +18066,7 @@ class ResourceGroupReference(proto.Message): service. """ - group = proto.Field(proto.STRING, number=98629247) + group = proto.Field(proto.STRING, number=98629247, optional=True,) class ResourcePolicy(proto.Message): @@ -19292,39 +18114,35 @@ class ResourcePolicy(proto.Message): class Status(proto.Enum): r"""[Output Only] The status of resource policy creation.""" UNDEFINED_STATUS = 0 - CREATING = 187129529 - DELETING = 260166568 - INVALID = 261848535 + CREATING = 455564985 + DELETING = 528602024 + INVALID = 530283991 READY = 77848963 - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) group_placement_policy = proto.Field( - proto.MESSAGE, number=10931596, message="ResourcePolicyGroupPlacementPolicy", - ) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - - region = proto.Field(proto.STRING, number=138946292) - - self_link = proto.Field(proto.STRING, number=187779341) - + proto.MESSAGE, + number=10931596, + optional=True, + message="ResourcePolicyGroupPlacementPolicy", + ) + 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,) + region = proto.Field(proto.STRING, number=138946292, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) snapshot_schedule_policy = proto.Field( - proto.MESSAGE, number=218131295, message="ResourcePolicySnapshotSchedulePolicy", + proto.MESSAGE, + number=218131295, + optional=True, + message="ResourcePolicySnapshotSchedulePolicy", ) - - status = proto.Field(proto.ENUM, number=181260274, enum=Status,) + status = proto.Field(proto.ENUM, number=181260274, optional=True, enum=Status,) class ResourcePoliciesScopedList(proto.Message): r""" - Attributes: resource_policies (Sequence[google.cloud.compute_v1.types.ResourcePolicy]): A list of resourcePolicies contained in this @@ -19337,8 +18155,9 @@ class ResourcePoliciesScopedList(proto.Message): resource_policies = proto.RepeatedField( proto.MESSAGE, number=22220385, message="ResourcePolicy", ) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", + ) class ResourcePolicyGroupPlacementPolicy(proto.Message): @@ -19362,13 +18181,15 @@ class Collocation(proto.Enum): r"""Specifies network collocation""" UNDEFINED_COLLOCATION = 0 COLLOCATED = 103257554 - UNSPECIFIED_COLLOCATION = 195872749 - - availability_domain_count = proto.Field(proto.INT32, number=12453432) + UNSPECIFIED_COLLOCATION = 464308205 - collocation = proto.Field(proto.ENUM, number=242721077, enum=Collocation,) - - vm_count = proto.Field(proto.INT32, number=261463431) + availability_domain_count = proto.Field( + proto.INT32, number=12453432, optional=True, + ) + collocation = proto.Field( + proto.ENUM, number=511156533, optional=True, enum=Collocation, + ) + vm_count = proto.Field(proto.INT32, number=261463431, optional=True,) class ResourcePolicySnapshotSchedulePolicy(proto.Message): @@ -19394,25 +18215,25 @@ class ResourcePolicySnapshotSchedulePolicy(proto.Message): retention_policy = proto.Field( proto.MESSAGE, number=68625779, + optional=True, message="ResourcePolicySnapshotSchedulePolicyRetentionPolicy", ) - schedule = proto.Field( proto.MESSAGE, - number=107385495, + number=375820951, + optional=True, message="ResourcePolicySnapshotSchedulePolicySchedule", ) - snapshot_properties = proto.Field( proto.MESSAGE, number=185371278, + optional=True, message="ResourcePolicySnapshotSchedulePolicySnapshotProperties", ) class ResourcePolicyAggregatedList(proto.Message): r"""Contains a list of resourcePolicies. - Attributes: etag (str): @@ -19442,31 +18263,25 @@ class ResourcePolicyAggregatedList(proto.Message): def raw_page(self): return self - etag = proto.Field(proto.STRING, number=3123477) - - id = proto.Field(proto.STRING, number=3355) - + etag = proto.Field(proto.STRING, number=3123477, optional=True,) + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="ResourcePoliciesScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 ResourcePolicyDailyCycle(proto.Message): r"""Time window specified for daily operations. - Attributes: days_in_cycle (int): Defines a schedule with units measured in @@ -19483,16 +18298,13 @@ class ResourcePolicyDailyCycle(proto.Message): 13:00-5 and 08:00 are valid. """ - days_in_cycle = proto.Field(proto.INT32, number=101354548) - - duration = proto.Field(proto.STRING, number=155471252) - - start_time = proto.Field(proto.STRING, number=37467274) + days_in_cycle = proto.Field(proto.INT32, number=369790004, optional=True,) + duration = proto.Field(proto.STRING, number=155471252, optional=True,) + start_time = proto.Field(proto.STRING, number=37467274, optional=True,) class ResourcePolicyHourlyCycle(proto.Message): r"""Time window specified for hourly operations. - Attributes: duration (str): [Output only] Duration of the time window, automatically @@ -19506,16 +18318,13 @@ class ResourcePolicyHourlyCycle(proto.Message): in format "HH:MM", where HH : [00-23] and MM : [00-00] GMT. """ - duration = proto.Field(proto.STRING, number=155471252) - - hours_in_cycle = proto.Field(proto.INT32, number=258327676) - - start_time = proto.Field(proto.STRING, number=37467274) + duration = proto.Field(proto.STRING, number=155471252, optional=True,) + hours_in_cycle = proto.Field(proto.INT32, number=526763132, optional=True,) + start_time = proto.Field(proto.STRING, number=37467274, optional=True,) class ResourcePolicyList(proto.Message): r""" - Attributes: etag (str): @@ -19544,26 +18353,21 @@ class ResourcePolicyList(proto.Message): def raw_page(self): return self - etag = proto.Field(proto.STRING, number=3123477) - - id = proto.Field(proto.STRING, number=3355) - + etag = proto.Field(proto.STRING, number=3123477, optional=True,) + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="ResourcePolicy", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 ResourcePolicySnapshotSchedulePolicyRetentionPolicy(proto.Message): r"""Policy for retention of scheduled snapshots. - Attributes: max_retention_days (int): Maximum age of the snapshot that is allowed @@ -19578,14 +18382,13 @@ class OnSourceDiskDelete(proto.Enum): the source disk is deleted. """ UNDEFINED_ON_SOURCE_DISK_DELETE = 0 - APPLY_RETENTION_POLICY = 266635876 + APPLY_RETENTION_POLICY = 535071332 KEEP_AUTO_SNAPSHOTS = 258925689 UNSPECIFIED_ON_SOURCE_DISK_DELETE = 239140769 - max_retention_days = proto.Field(proto.INT32, number=55861523) - + max_retention_days = proto.Field(proto.INT32, number=324296979, optional=True,) on_source_disk_delete = proto.Field( - proto.ENUM, number=53520073, enum=OnSourceDiskDelete, + proto.ENUM, number=321955529, optional=True, enum=OnSourceDiskDelete, ) @@ -19603,15 +18406,22 @@ class ResourcePolicySnapshotSchedulePolicySchedule(proto.Message): """ daily_schedule = proto.Field( - proto.MESSAGE, number=86159869, message="ResourcePolicyDailyCycle", + proto.MESSAGE, + number=86159869, + optional=True, + message="ResourcePolicyDailyCycle", ) - hourly_schedule = proto.Field( - proto.MESSAGE, number=38328485, message="ResourcePolicyHourlyCycle", + proto.MESSAGE, + number=38328485, + optional=True, + message="ResourcePolicyHourlyCycle", ) - weekly_schedule = proto.Field( - proto.MESSAGE, number=91112597, message="ResourcePolicyWeeklyCycle", + proto.MESSAGE, + number=359548053, + optional=True, + message="ResourcePolicyWeeklyCycle", ) @@ -19634,18 +18444,14 @@ class ResourcePolicySnapshotSchedulePolicySnapshotProperties(proto.Message): auto snapshot (regional or multi-regional). """ - chain_name = proto.Field(proto.STRING, number=68644169) - - guest_flush = proto.Field(proto.BOOL, number=117115357) - - labels = proto.MapField(proto.STRING, proto.STRING, number=231759871) - - storage_locations = proto.RepeatedField(proto.STRING, number=59569818) + chain_name = proto.Field(proto.STRING, number=68644169, optional=True,) + guest_flush = proto.Field(proto.BOOL, number=385550813, optional=True,) + labels = proto.MapField(proto.STRING, proto.STRING, number=500195327,) + storage_locations = proto.RepeatedField(proto.STRING, number=328005274,) class ResourcePolicyWeeklyCycle(proto.Message): r"""Time window specified for weekly operations. - Attributes: day_of_weeks (Sequence[google.cloud.compute_v1.types.ResourcePolicyWeeklyCycleDayOfWeek]): Up to 7 intervals/windows, one for each day @@ -19659,7 +18465,6 @@ class ResourcePolicyWeeklyCycle(proto.Message): class ResourcePolicyWeeklyCycleDayOfWeek(proto.Message): r""" - Attributes: day (google.cloud.compute_v1.types.ResourcePolicyWeeklyCycleDayOfWeek.Day): Defines a schedule that runs on specific days @@ -19681,20 +18486,18 @@ class Day(proto.Enum): MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY. """ UNDEFINED_DAY = 0 - FRIDAY = 202963295 - INVALID = 261848535 + FRIDAY = 471398751 + INVALID = 530283991 MONDAY = 132310288 - SATURDAY = 10602425 - SUNDAY = 41190864 + SATURDAY = 279037881 + SUNDAY = 309626320 THURSDAY = 207198682 - TUESDAY = 9074221 - WEDNESDAY = 153593654 - - day = proto.Field(proto.ENUM, number=99228, enum=Day,) - - duration = proto.Field(proto.STRING, number=155471252) + TUESDAY = 277509677 + WEDNESDAY = 422029110 - start_time = proto.Field(proto.STRING, number=37467274) + day = proto.Field(proto.ENUM, number=99228, optional=True, enum=Day,) + duration = proto.Field(proto.STRING, number=155471252, optional=True,) + start_time = proto.Field(proto.STRING, number=37467274, optional=True,) class Route(proto.Message): @@ -19785,46 +18588,28 @@ class Route(proto.Message): messages. """ - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - dest_range = proto.Field(proto.STRING, number=112892256) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - - network = proto.Field(proto.STRING, number=232872494) - - next_hop_gateway = proto.Field(proto.STRING, number=108739842) - - next_hop_ilb = proto.Field(proto.STRING, number=198679901) - - next_hop_instance = proto.Field(proto.STRING, number=125072791) - - next_hop_ip = proto.Field(proto.STRING, number=110319529) - - next_hop_network = proto.Field(proto.STRING, number=262295788) - - next_hop_peering = proto.Field(proto.STRING, number=144247294) - - next_hop_vpn_tunnel = proto.Field(proto.STRING, number=251409045) - - priority = proto.Field(proto.UINT32, number=176716196) - - self_link = proto.Field(proto.STRING, number=187779341) - - tags = proto.RepeatedField(proto.STRING, number=3552281) - - warnings = proto.RepeatedField(proto.MESSAGE, number=229655639, message="Warnings",) + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + dest_range = proto.Field(proto.STRING, number=381327712, 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,) + network = proto.Field(proto.STRING, number=232872494, optional=True,) + next_hop_gateway = proto.Field(proto.STRING, number=377175298, optional=True,) + next_hop_ilb = proto.Field(proto.STRING, number=198679901, optional=True,) + next_hop_instance = proto.Field(proto.STRING, number=393508247, optional=True,) + next_hop_ip = proto.Field(proto.STRING, number=110319529, optional=True,) + next_hop_network = proto.Field(proto.STRING, number=262295788, optional=True,) + next_hop_peering = proto.Field(proto.STRING, number=412682750, optional=True,) + next_hop_vpn_tunnel = proto.Field(proto.STRING, number=519844501, optional=True,) + priority = proto.Field(proto.UINT32, number=445151652, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + tags = proto.RepeatedField(proto.STRING, number=3552281,) + warnings = proto.RepeatedField(proto.MESSAGE, number=498091095, message="Warnings",) class RouteList(proto.Message): r"""Contains a list of Route resources. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -19850,22 +18635,18 @@ class RouteList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="Route",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 RouterBgp(proto.Message): r""" - Attributes: advertise_mode (google.cloud.compute_v1.types.RouterBgp.AdvertiseMode): User-specified flag to indicate which mode to @@ -19898,7 +18679,7 @@ class AdvertiseMode(proto.Enum): advertisement. The options are DEFAULT or CUSTOM. """ UNDEFINED_ADVERTISE_MODE = 0 - CUSTOM = 120160113 + CUSTOM = 388595569 DEFAULT = 115302945 class AdvertisedGroups(proto.Enum): @@ -19906,22 +18687,20 @@ class AdvertisedGroups(proto.Enum): UNDEFINED_ADVERTISED_GROUPS = 0 ALL_SUBNETS = 3622872 - advertise_mode = proto.Field(proto.ENUM, number=43698875, enum=AdvertiseMode,) - + advertise_mode = proto.Field( + proto.ENUM, number=312134331, optional=True, enum=AdvertiseMode, + ) advertised_groups = proto.RepeatedField( proto.ENUM, number=21065526, enum=AdvertisedGroups, ) - advertised_ip_ranges = proto.RepeatedField( proto.MESSAGE, number=35449932, message="RouterAdvertisedIpRange", ) - - asn = proto.Field(proto.UINT32, number=96892) + asn = proto.Field(proto.UINT32, number=96892, optional=True,) class RouterBgpPeer(proto.Message): r""" - Attributes: advertise_mode (google.cloud.compute_v1.types.RouterBgpPeer.AdvertiseMode): User-specified flag to indicate which mode to @@ -19991,7 +18770,7 @@ class AdvertiseMode(proto.Enum): advertisement. """ UNDEFINED_ADVERTISE_MODE = 0 - CUSTOM = 120160113 + CUSTOM = 388595569 DEFAULT = 115302945 class AdvertisedGroups(proto.Enum): @@ -20012,37 +18791,33 @@ class ManagementType(proto.Enum): PARTNER InterconnectAttachment is created, updated, or deleted. """ UNDEFINED_MANAGEMENT_TYPE = 0 - MANAGED_BY_ATTACHMENT = 190490955 - MANAGED_BY_USER = 48858611 - - advertise_mode = proto.Field(proto.ENUM, number=43698875, enum=AdvertiseMode,) + MANAGED_BY_ATTACHMENT = 458926411 + MANAGED_BY_USER = 317294067 + advertise_mode = proto.Field( + proto.ENUM, number=312134331, optional=True, enum=AdvertiseMode, + ) advertised_groups = proto.RepeatedField( proto.ENUM, number=21065526, enum=AdvertisedGroups, ) - advertised_ip_ranges = proto.RepeatedField( proto.MESSAGE, number=35449932, message="RouterAdvertisedIpRange", ) - - advertised_route_priority = proto.Field(proto.UINT32, number=186486332) - - interface_name = proto.Field(proto.STRING, number=169419217) - - ip_address = proto.Field(proto.STRING, number=137836764) - - management_type = proto.Field(proto.ENUM, number=173703606, enum=ManagementType,) - - name = proto.Field(proto.STRING, number=3373707) - - peer_asn = proto.Field(proto.UINT32, number=69573151) - - peer_ip_address = proto.Field(proto.STRING, number=207735769) + advertised_route_priority = proto.Field( + proto.UINT32, number=186486332, optional=True, + ) + interface_name = proto.Field(proto.STRING, number=437854673, optional=True,) + ip_address = proto.Field(proto.STRING, number=406272220, optional=True,) + management_type = proto.Field( + proto.ENUM, number=173703606, optional=True, enum=ManagementType, + ) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + peer_asn = proto.Field(proto.UINT32, number=69573151, optional=True,) + peer_ip_address = proto.Field(proto.STRING, number=207735769, optional=True,) class RouterInterface(proto.Message): r""" - Attributes: ip_range (str): IP address and range of the interface. The IP @@ -20098,18 +18873,18 @@ class ManagementType(proto.Enum): PARTNER InterconnectAttachment is created, updated, or deleted. """ UNDEFINED_MANAGEMENT_TYPE = 0 - MANAGED_BY_ATTACHMENT = 190490955 - MANAGED_BY_USER = 48858611 - - ip_range = proto.Field(proto.STRING, number=145092645) - - linked_interconnect_attachment = proto.Field(proto.STRING, number=232650062) - - linked_vpn_tunnel = proto.Field(proto.STRING, number=83861497) + MANAGED_BY_ATTACHMENT = 458926411 + MANAGED_BY_USER = 317294067 - management_type = proto.Field(proto.ENUM, number=173703606, enum=ManagementType,) - - name = proto.Field(proto.STRING, number=3373707) + ip_range = proto.Field(proto.STRING, number=145092645, optional=True,) + linked_interconnect_attachment = proto.Field( + proto.STRING, number=501085518, optional=True, + ) + linked_vpn_tunnel = proto.Field(proto.STRING, number=352296953, optional=True,) + management_type = proto.Field( + proto.ENUM, number=173703606, optional=True, enum=ManagementType, + ) + name = proto.Field(proto.STRING, number=3373707, optional=True,) class RouterNat(proto.Message): @@ -20224,41 +18999,35 @@ class SourceSubnetworkIpRangesToNat(proto.Enum): UNDEFINED_SOURCE_SUBNETWORK_IP_RANGES_TO_NAT = 0 ALL_SUBNETWORKS_ALL_IP_RANGES = 179964376 ALL_SUBNETWORKS_ALL_PRIMARY_IP_RANGES = 185573819 - LIST_OF_SUBNETWORKS = 249106814 - - drain_nat_ips = proto.RepeatedField(proto.STRING, number=235643079) - - enable_endpoint_independent_mapping = proto.Field(proto.BOOL, number=259441819) - - icmp_idle_timeout_sec = proto.Field(proto.INT32, number=3647562) + LIST_OF_SUBNETWORKS = 517542270 + drain_nat_ips = proto.RepeatedField(proto.STRING, number=504078535,) + enable_endpoint_independent_mapping = proto.Field( + proto.BOOL, number=259441819, optional=True, + ) + icmp_idle_timeout_sec = proto.Field(proto.INT32, number=3647562, optional=True,) log_config = proto.Field( - proto.MESSAGE, number=82864285, message="RouterNatLogConfig", + proto.MESSAGE, number=351299741, optional=True, message="RouterNatLogConfig", ) - - min_ports_per_vm = proto.Field(proto.INT32, number=186193587) - - name = proto.Field(proto.STRING, number=3373707) - + min_ports_per_vm = proto.Field(proto.INT32, number=186193587, optional=True,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) nat_ip_allocate_option = proto.Field( - proto.ENUM, number=161291389, enum=NatIpAllocateOption, + proto.ENUM, number=429726845, optional=True, enum=NatIpAllocateOption, ) - - nat_ips = proto.RepeatedField(proto.STRING, number=117635086) - + nat_ips = proto.RepeatedField(proto.STRING, number=117635086,) source_subnetwork_ip_ranges_to_nat = proto.Field( - proto.ENUM, number=252213211, enum=SourceSubnetworkIpRangesToNat, + proto.ENUM, number=252213211, optional=True, enum=SourceSubnetworkIpRangesToNat, ) - subnetworks = proto.RepeatedField( - proto.MESSAGE, number=147417669, message="RouterNatSubnetworkToNat", + proto.MESSAGE, number=415853125, message="RouterNatSubnetworkToNat", ) - - tcp_established_idle_timeout_sec = proto.Field(proto.INT32, number=223098349) - - tcp_transitory_idle_timeout_sec = proto.Field(proto.INT32, number=205028774) - - udp_idle_timeout_sec = proto.Field(proto.INT32, number=64919878) + tcp_established_idle_timeout_sec = proto.Field( + proto.INT32, number=223098349, optional=True, + ) + tcp_transitory_idle_timeout_sec = proto.Field( + proto.INT32, number=205028774, optional=True, + ) + udp_idle_timeout_sec = proto.Field(proto.INT32, number=64919878, optional=True,) class Router(proto.Message): @@ -20315,38 +19084,26 @@ class Router(proto.Message): [Output Only] Server-defined URL for the resource. """ - bgp = proto.Field(proto.MESSAGE, number=97483, message="RouterBgp",) - + bgp = proto.Field(proto.MESSAGE, number=97483, optional=True, message="RouterBgp",) bgp_peers = proto.RepeatedField( - proto.MESSAGE, number=184260317, message="RouterBgpPeer", + proto.MESSAGE, number=452695773, message="RouterBgpPeer", ) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - id = proto.Field(proto.STRING, number=3355) - + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + id = proto.Field(proto.STRING, number=3355, optional=True,) interfaces = proto.RepeatedField( proto.MESSAGE, number=12073562, message="RouterInterface", ) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - + kind = proto.Field(proto.STRING, number=3292052, optional=True,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) nats = proto.RepeatedField(proto.MESSAGE, number=3373938, message="RouterNat",) - - network = proto.Field(proto.STRING, number=232872494) - - region = proto.Field(proto.STRING, number=138946292) - - self_link = proto.Field(proto.STRING, number=187779341) + network = proto.Field(proto.STRING, number=232872494, optional=True,) + region = proto.Field(proto.STRING, number=138946292, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) class RouterAdvertisedIpRange(proto.Message): r"""Description-tagged IP ranges for the router to advertise. - Attributes: description (str): User-specified description for the IP range. @@ -20355,14 +19112,12 @@ class RouterAdvertisedIpRange(proto.Message): a CIDR-formatted string. """ - description = proto.Field(proto.STRING, number=154502140) - - range_ = proto.Field(proto.STRING, number=108280125) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + range_ = proto.Field(proto.STRING, number=108280125, optional=True,) class RoutersScopedList(proto.Message): r""" - Attributes: routers (Sequence[google.cloud.compute_v1.types.Router]): A list of routers contained in this scope. @@ -20371,14 +19126,14 @@ class RoutersScopedList(proto.Message): of routers when the list is empty. """ - routers = proto.RepeatedField(proto.MESSAGE, number=43471434, message="Router",) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + routers = proto.RepeatedField(proto.MESSAGE, number=311906890, message="Router",) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", + ) class RouterAggregatedList(proto.Message): r"""Contains a list of routers. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -20406,26 +19161,21 @@ class RouterAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="RoutersScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 RouterList(proto.Message): r"""Contains a list of Router resources. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -20452,22 +19202,18 @@ class RouterList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="Router",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 RouterNatLogConfig(proto.Message): r"""Configuration of logging on a NAT. - Attributes: enable (bool): Indicates whether or not to export logs. This @@ -20497,17 +19243,15 @@ class Filter(proto.Enum): """ UNDEFINED_FILTER = 0 ALL = 64897 - ERRORS_ONLY = 39049216 - TRANSLATIONS_ONLY = 88777193 - - enable = proto.Field(proto.BOOL, number=43328899) + ERRORS_ONLY = 307484672 + TRANSLATIONS_ONLY = 357212649 - filter = proto.Field(proto.ENUM, number=67685240, enum=Filter,) + enable = proto.Field(proto.BOOL, number=311764355, optional=True,) + filter = proto.Field(proto.ENUM, number=336120696, optional=True, enum=Filter,) class RouterNatSubnetworkToNat(proto.Message): r"""Defines the IP ranges that want to use NAT for a subnetwork. - Attributes: name (str): URL for the subnetwork resource that will use @@ -20530,20 +19274,17 @@ class SourceIpRangesToNat(proto.Enum): UNDEFINED_SOURCE_IP_RANGES_TO_NAT = 0 ALL_IP_RANGES = 35608496 LIST_OF_SECONDARY_IP_RANGES = 192289308 - PRIMARY_IP_RANGE = 28674498 - - name = proto.Field(proto.STRING, number=3373707) - - secondary_ip_range_names = proto.RepeatedField(proto.STRING, number=264315097) + PRIMARY_IP_RANGE = 297109954 + name = proto.Field(proto.STRING, number=3373707, optional=True,) + secondary_ip_range_names = proto.RepeatedField(proto.STRING, number=264315097,) source_ip_ranges_to_nat = proto.RepeatedField( - proto.ENUM, number=119874930, enum=SourceIpRangesToNat, + proto.ENUM, number=388310386, enum=SourceIpRangesToNat, ) class RouterStatusBgpPeerStatus(proto.Message): r""" - Attributes: advertised_routes (Sequence[google.cloud.compute_v1.types.Route]): Routes that were advertised to the remote BGP @@ -20578,35 +19319,25 @@ class Status(proto.Enum): r"""Status of the BGP peer: {UP, DOWN}""" UNDEFINED_STATUS = 0 DOWN = 2104482 - UNKNOWN = 164706346 + UNKNOWN = 433141802 UP = 2715 advertised_routes = proto.RepeatedField( - proto.MESSAGE, number=64957612, message="Route", + proto.MESSAGE, number=333393068, message="Route", ) - - ip_address = proto.Field(proto.STRING, number=137836764) - - linked_vpn_tunnel = proto.Field(proto.STRING, number=83861497) - - name = proto.Field(proto.STRING, number=3373707) - - num_learned_routes = proto.Field(proto.UINT32, number=135457535) - - peer_ip_address = proto.Field(proto.STRING, number=207735769) - - state = proto.Field(proto.STRING, number=109757585) - - status = proto.Field(proto.ENUM, number=181260274, enum=Status,) - - uptime = proto.Field(proto.STRING, number=235379688) - - uptime_seconds = proto.Field(proto.STRING, number=104736040) + ip_address = proto.Field(proto.STRING, number=406272220, optional=True,) + linked_vpn_tunnel = proto.Field(proto.STRING, number=352296953, optional=True,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + num_learned_routes = proto.Field(proto.UINT32, number=135457535, optional=True,) + peer_ip_address = proto.Field(proto.STRING, number=207735769, optional=True,) + state = proto.Field(proto.STRING, number=109757585, optional=True,) + status = proto.Field(proto.ENUM, number=181260274, optional=True, enum=Status,) + uptime = proto.Field(proto.STRING, number=235379688, optional=True,) + uptime_seconds = proto.Field(proto.STRING, number=104736040, optional=True,) class RouterStatusNatStatus(proto.Message): r"""Status of a NAT contained in this router. - Attributes: auto_allocated_nat_ips (Sequence[str]): A list of IPs auto-allocated for NAT. Example: ["1.1.1.1", @@ -20635,28 +19366,24 @@ class RouterStatusNatStatus(proto.Message): will be raw IP strings like "179.12.26.133". """ - auto_allocated_nat_ips = proto.RepeatedField(proto.STRING, number=242358790) - - drain_auto_allocated_nat_ips = proto.RepeatedField(proto.STRING, number=40749101) - - drain_user_allocated_nat_ips = proto.RepeatedField(proto.STRING, number=36833097) - - min_extra_nat_ips_needed = proto.Field(proto.INT32, number=97350882) - - name = proto.Field(proto.STRING, number=3373707) - - num_vm_endpoints_with_nat_mappings = proto.Field(proto.INT32, number=243932012) - + auto_allocated_nat_ips = proto.RepeatedField(proto.STRING, number=510794246,) + drain_auto_allocated_nat_ips = proto.RepeatedField(proto.STRING, number=309184557,) + drain_user_allocated_nat_ips = proto.RepeatedField(proto.STRING, number=305268553,) + min_extra_nat_ips_needed = proto.Field( + proto.INT32, number=365786338, optional=True, + ) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + num_vm_endpoints_with_nat_mappings = proto.Field( + proto.INT32, number=512367468, optional=True, + ) user_allocated_nat_ip_resources = proto.RepeatedField( - proto.STRING, number=212776151 + proto.STRING, number=212776151, ) - - user_allocated_nat_ips = proto.RepeatedField(proto.STRING, number=238442786) + user_allocated_nat_ips = proto.RepeatedField(proto.STRING, number=506878242,) class RouterStatus(proto.Message): r""" - Attributes: best_routes (Sequence[google.cloud.compute_v1.types.Route]): Best routes for this router's network. @@ -20671,26 +19398,21 @@ class RouterStatus(proto.Message): belongs. """ - best_routes = proto.RepeatedField(proto.MESSAGE, number=127391237, message="Route",) - + best_routes = proto.RepeatedField(proto.MESSAGE, number=395826693, message="Route",) best_routes_for_router = proto.RepeatedField( proto.MESSAGE, number=119389689, message="Route", ) - bgp_peer_status = proto.RepeatedField( proto.MESSAGE, number=218459131, message="RouterStatusBgpPeerStatus", ) - nat_status = proto.RepeatedField( proto.MESSAGE, number=63098064, message="RouterStatusNatStatus", ) - - network = proto.Field(proto.STRING, number=232872494) + network = proto.Field(proto.STRING, number=232872494, optional=True,) class RouterStatusResponse(proto.Message): r""" - Attributes: kind (str): Type of resource. @@ -20698,20 +19420,22 @@ class RouterStatusResponse(proto.Message): """ - kind = proto.Field(proto.STRING, number=3292052) - - result = proto.Field(proto.MESSAGE, number=139315229, message="RouterStatus",) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) + result = proto.Field( + proto.MESSAGE, number=139315229, optional=True, message="RouterStatus", + ) class RoutersPreviewResponse(proto.Message): r""" - Attributes: resource (google.cloud.compute_v1.types.Router): Preview of given router. """ - resource = proto.Field(proto.MESSAGE, number=195806222, message="Router",) + resource = proto.Field( + proto.MESSAGE, number=195806222, optional=True, message="Router", + ) class SchedulingNodeAffinity(proto.Message): @@ -20739,16 +19463,13 @@ class Operator(proto.Enum): NOT_IN = 161144369 OPERATOR_UNSPECIFIED = 128892924 - key = proto.Field(proto.STRING, number=106079) - - operator = proto.Field(proto.ENUM, number=36317348, enum=Operator,) - - values = proto.RepeatedField(proto.STRING, number=249928994) + key = proto.Field(proto.STRING, number=106079, optional=True,) + operator = proto.Field(proto.ENUM, number=36317348, optional=True, enum=Operator,) + values = proto.RepeatedField(proto.STRING, number=249928994,) class Screenshot(proto.Message): r"""An instance's screenshot. - Attributes: contents (str): [Output Only] The Base64-encoded screenshot data. @@ -20757,34 +19478,34 @@ class Screenshot(proto.Message): compute#screenshot for the screenshots. """ - contents = proto.Field(proto.STRING, number=237984538) - - kind = proto.Field(proto.STRING, number=3292052) + contents = proto.Field(proto.STRING, number=506419994, optional=True,) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) class SecurityPoliciesWafConfig(proto.Message): r""" - Attributes: waf_rules (google.cloud.compute_v1.types.PreconfiguredWafSet): """ waf_rules = proto.Field( - proto.MESSAGE, number=74899924, message="PreconfiguredWafSet", + proto.MESSAGE, number=74899924, optional=True, message="PreconfiguredWafSet", ) class SecurityPoliciesListPreconfiguredExpressionSetsResponse(proto.Message): r""" - Attributes: preconfigured_expression_sets (google.cloud.compute_v1.types.SecurityPoliciesWafConfig): """ preconfigured_expression_sets = proto.Field( - proto.MESSAGE, number=267765370, message="SecurityPoliciesWafConfig", + proto.MESSAGE, + number=536200826, + optional=True, + message="SecurityPoliciesWafConfig", ) @@ -20822,19 +19543,17 @@ class SecurityPolicyRule(proto.Message): lowest priority. """ - action = proto.Field(proto.STRING, number=187661878) - - description = proto.Field(proto.STRING, number=154502140) - - kind = proto.Field(proto.STRING, number=3292052) - + action = proto.Field(proto.STRING, number=187661878, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) match = proto.Field( - proto.MESSAGE, number=103668165, message="SecurityPolicyRuleMatcher", + proto.MESSAGE, + number=103668165, + optional=True, + message="SecurityPolicyRuleMatcher", ) - - preview = proto.Field(proto.BOOL, number=218686408) - - priority = proto.Field(proto.INT32, number=176716196) + preview = proto.Field(proto.BOOL, number=218686408, optional=True,) + priority = proto.Field(proto.INT32, number=445151652, optional=True,) class SecurityPolicy(proto.Message): @@ -20889,28 +19608,20 @@ class SecurityPolicy(proto.Message): [Output Only] Server-defined URL for the resource. """ - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - fingerprint = proto.Field(proto.STRING, number=234678500) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - + 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,) rules = proto.RepeatedField( proto.MESSAGE, number=108873975, message="SecurityPolicyRule", ) - - self_link = proto.Field(proto.STRING, number=187779341) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) class SecurityPolicyList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -20935,28 +19646,25 @@ class SecurityPolicyList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="SecurityPolicy", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 SecurityPolicyReference(proto.Message): r""" - Attributes: security_policy (str): """ - security_policy = proto.Field(proto.STRING, number=171082513) + security_policy = proto.Field(proto.STRING, number=171082513, optional=True,) class SecurityPolicyRuleMatcher(proto.Message): @@ -20991,29 +19699,30 @@ class VersionedExpr(proto.Enum): SRC_IPS_V1 = 70925961 config = proto.Field( - proto.MESSAGE, number=255820610, message="SecurityPolicyRuleMatcherConfig", + proto.MESSAGE, + number=255820610, + optional=True, + message="SecurityPolicyRuleMatcherConfig", + ) + expr = proto.Field(proto.MESSAGE, number=3127797, optional=True, message="Expr",) + versioned_expr = proto.Field( + proto.ENUM, number=322286013, optional=True, enum=VersionedExpr, ) - - expr = proto.Field(proto.MESSAGE, number=3127797, message="Expr",) - - versioned_expr = proto.Field(proto.ENUM, number=53850557, enum=VersionedExpr,) class SecurityPolicyRuleMatcherConfig(proto.Message): r""" - Attributes: src_ip_ranges (Sequence[str]): CIDR IP address range. Maximum number of src_ip_ranges allowed is 10. """ - src_ip_ranges = proto.RepeatedField(proto.STRING, number=163692627) + src_ip_ranges = proto.RepeatedField(proto.STRING, number=432128083,) class SerialPortOutput(proto.Message): r"""An instance's serial console output. - Attributes: contents (str): [Output Only] The contents of the console output. @@ -21037,20 +19746,15 @@ class SerialPortOutput(proto.Message): ``start`` value that was specified in the request. """ - contents = proto.Field(proto.STRING, number=237984538) - - kind = proto.Field(proto.STRING, number=3292052) - - next_ = proto.Field(proto.STRING, number=3377907) - - self_link = proto.Field(proto.STRING, number=187779341) - - start = proto.Field(proto.STRING, number=109757538) + contents = proto.Field(proto.STRING, number=506419994, optional=True,) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) + next_ = proto.Field(proto.STRING, number=3377907, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + start = proto.Field(proto.STRING, number=109757538, optional=True,) class ShieldedInstanceIdentityEntry(proto.Message): r"""A Shielded Instance Identity Entry. - Attributes: ek_cert (str): A PEM-encoded X.509 certificate. This field @@ -21059,14 +19763,12 @@ class ShieldedInstanceIdentityEntry(proto.Message): A PEM-encoded public key. """ - ek_cert = proto.Field(proto.STRING, number=181743133) - - ek_pub = proto.Field(proto.STRING, number=40512484) + ek_cert = proto.Field(proto.STRING, number=450178589, optional=True,) + ek_pub = proto.Field(proto.STRING, number=308947940, optional=True,) class ShieldedInstanceIdentity(proto.Message): r"""A shielded Instance identity entry. - Attributes: encryption_key (google.cloud.compute_v1.types.ShieldedInstanceIdentityEntry): An Endorsement Key (EK) made by the RSA 2048 @@ -21083,13 +19785,17 @@ class ShieldedInstanceIdentity(proto.Message): """ encryption_key = proto.Field( - proto.MESSAGE, number=219833251, message="ShieldedInstanceIdentityEntry", + proto.MESSAGE, + number=488268707, + optional=True, + message="ShieldedInstanceIdentityEntry", ) - - kind = proto.Field(proto.STRING, number=3292052) - + kind = proto.Field(proto.STRING, number=3292052, optional=True,) signing_key = proto.Field( - proto.MESSAGE, number=52512805, message="ShieldedInstanceIdentityEntry", + proto.MESSAGE, + number=320948261, + optional=True, + message="ShieldedInstanceIdentityEntry", ) @@ -21112,9 +19818,8 @@ class SignedUrlKey(proto.Message): base64url encoded string. """ - key_name = proto.Field(proto.STRING, number=232503403) - - key_value = proto.Field(proto.STRING, number=235671441) + key_name = proto.Field(proto.STRING, number=500938859, optional=True,) + key_value = proto.Field(proto.STRING, number=504106897, optional=True,) class Snapshot(proto.Message): @@ -21239,9 +19944,9 @@ class Status(proto.Enum): DELETING, FAILED, READY, or UPLOADING. """ UNDEFINED_STATUS = 0 - CREATING = 187129529 - DELETING = 260166568 - FAILED = 187271229 + CREATING = 455564985 + DELETING = 528602024 + FAILED = 455706685 READY = 77848963 UPLOADING = 267603489 @@ -21253,63 +19958,41 @@ class StorageBytesStatus(proto.Enum): up-to-date. """ UNDEFINED_STORAGE_BYTES_STATUS = 0 - UPDATING = 226178886 + UPDATING = 494614342 UP_TO_DATE = 101306702 - auto_created = proto.Field(proto.BOOL, number=195486808) - - chain_name = proto.Field(proto.STRING, number=68644169) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - disk_size_gb = proto.Field(proto.STRING, number=47828279) - - download_bytes = proto.Field(proto.STRING, number=166618612) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - label_fingerprint = proto.Field(proto.STRING, number=178124825) - - labels = proto.MapField(proto.STRING, proto.STRING, number=231759871) - - license_codes = proto.RepeatedField(proto.STRING, number=45482664) - - licenses = proto.RepeatedField(proto.STRING, number=69207122) - - name = proto.Field(proto.STRING, number=3373707) - - self_link = proto.Field(proto.STRING, number=187779341) - + auto_created = proto.Field(proto.BOOL, number=463922264, optional=True,) + chain_name = proto.Field(proto.STRING, number=68644169, optional=True,) + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + disk_size_gb = proto.Field(proto.STRING, number=316263735, optional=True,) + download_bytes = proto.Field(proto.STRING, number=435054068, optional=True,) + id = proto.Field(proto.STRING, number=3355, 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,) + license_codes = proto.RepeatedField(proto.STRING, number=45482664,) + licenses = proto.RepeatedField(proto.STRING, number=337642578,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) snapshot_encryption_key = proto.Field( - proto.MESSAGE, number=43334526, message="CustomerEncryptionKey", + proto.MESSAGE, number=43334526, optional=True, message="CustomerEncryptionKey", ) - - source_disk = proto.Field(proto.STRING, number=183318337) - + source_disk = proto.Field(proto.STRING, number=451753793, optional=True,) source_disk_encryption_key = proto.Field( - proto.MESSAGE, number=263065697, message="CustomerEncryptionKey", + proto.MESSAGE, number=531501153, optional=True, message="CustomerEncryptionKey", ) - - source_disk_id = proto.Field(proto.STRING, number=185755353) - - status = proto.Field(proto.ENUM, number=181260274, enum=Status,) - - storage_bytes = proto.Field(proto.STRING, number=156196263) - + source_disk_id = proto.Field(proto.STRING, number=454190809, optional=True,) + status = proto.Field(proto.ENUM, number=181260274, optional=True, enum=Status,) + storage_bytes = proto.Field(proto.STRING, number=424631719, optional=True,) storage_bytes_status = proto.Field( - proto.ENUM, number=222303626, enum=StorageBytesStatus, + proto.ENUM, number=490739082, optional=True, enum=StorageBytesStatus, ) - - storage_locations = proto.RepeatedField(proto.STRING, number=59569818) + storage_locations = proto.RepeatedField(proto.STRING, number=328005274,) class SnapshotList(proto.Message): r"""Contains a list of Snapshot resources. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -21335,22 +20018,18 @@ class SnapshotList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="Snapshot",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 SslCertificateManagedSslCertificate(proto.Message): r"""Configuration and status of a managed SSL certificate. - Attributes: domain_status (Sequence[google.cloud.compute_v1.types.SslCertificateManagedSslCertificate.DomainStatusEntry]): [Output only] Detailed statuses of the domains specified for @@ -21366,23 +20045,20 @@ class SslCertificateManagedSslCertificate(proto.Message): class Status(proto.Enum): r"""[Output only] Status of the managed certificate resource.""" UNDEFINED_STATUS = 0 - ACTIVE = 46297862 - MANAGED_CERTIFICATE_STATUS_UNSPECIFIED = 206365394 - PROVISIONING = 22461165 + ACTIVE = 314733318 + MANAGED_CERTIFICATE_STATUS_UNSPECIFIED = 474800850 + PROVISIONING = 290896621 PROVISIONING_FAILED = 76813775 - PROVISIONING_FAILED_PERMANENTLY = 6600747 - RENEWAL_FAILED = 166223620 + PROVISIONING_FAILED_PERMANENTLY = 275036203 + RENEWAL_FAILED = 434659076 - domain_status = proto.MapField(proto.STRING, proto.STRING, number=91870157) - - domains = proto.RepeatedField(proto.STRING, number=226935855) - - status = proto.Field(proto.ENUM, number=181260274, enum=Status,) + domain_status = proto.MapField(proto.STRING, proto.STRING, number=360305613,) + domains = proto.RepeatedField(proto.STRING, number=226935855,) + status = proto.Field(proto.ENUM, number=181260274, optional=True, enum=Status,) class SslCertificateSelfManagedSslCertificate(proto.Message): r"""Configuration and status of a self-managed SSL certificate. - Attributes: certificate (str): A local certificate file. The certificate @@ -21394,9 +20070,8 @@ class SslCertificateSelfManagedSslCertificate(proto.Message): insert requests will include this field. """ - certificate = proto.Field(proto.STRING, number=73351575) - - private_key = proto.Field(proto.STRING, number=92895651) + certificate = proto.Field(proto.STRING, number=341787031, optional=True,) + private_key = proto.Field(proto.STRING, number=361331107, optional=True,) class SslCertificate(proto.Message): @@ -21487,48 +20162,38 @@ class Type(proto.Enum): self-managed and the fields certificate and private_key are used. """ UNDEFINED_TYPE = 0 - MANAGED = 211065727 - SELF_MANAGED = 166002060 - TYPE_UNSPECIFIED = 169278866 - - certificate = proto.Field(proto.STRING, number=73351575) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - expire_time = proto.Field(proto.STRING, number=172255725) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - + MANAGED = 479501183 + SELF_MANAGED = 434437516 + TYPE_UNSPECIFIED = 437714322 + + certificate = proto.Field(proto.STRING, number=341787031, optional=True,) + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + expire_time = proto.Field(proto.STRING, number=440691181, optional=True,) + id = proto.Field(proto.STRING, number=3355, optional=True,) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) managed = proto.Field( - proto.MESSAGE, number=29953951, message="SslCertificateManagedSslCertificate", - ) - - name = proto.Field(proto.STRING, number=3373707) - - private_key = proto.Field(proto.STRING, number=92895651) - - region = proto.Field(proto.STRING, number=138946292) - - self_link = proto.Field(proto.STRING, number=187779341) - + proto.MESSAGE, + number=298389407, + optional=True, + message="SslCertificateManagedSslCertificate", + ) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + private_key = proto.Field(proto.STRING, number=361331107, optional=True,) + region = proto.Field(proto.STRING, number=138946292, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) self_managed = proto.Field( proto.MESSAGE, - number=60848556, + number=329284012, + optional=True, message="SslCertificateSelfManagedSslCertificate", ) - - subject_alternative_names = proto.RepeatedField(proto.STRING, number=260372451) - - type_ = proto.Field(proto.ENUM, number=3575610, enum=Type,) + subject_alternative_names = proto.RepeatedField(proto.STRING, number=528807907,) + type_ = proto.Field(proto.ENUM, number=3575610, optional=True, enum=Type,) class SslCertificatesScopedList(proto.Message): r""" - Attributes: ssl_certificates (Sequence[google.cloud.compute_v1.types.SslCertificate]): List of SslCertificates contained in this @@ -21539,15 +20204,15 @@ class SslCertificatesScopedList(proto.Message): """ ssl_certificates = proto.RepeatedField( - proto.MESSAGE, number=97571087, message="SslCertificate", + proto.MESSAGE, number=366006543, message="SslCertificate", + ) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", ) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) class SslCertificateAggregatedList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -21578,29 +20243,24 @@ class SslCertificateAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="SslCertificatesScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 SslCertificateList(proto.Message): r"""Contains a list of SslCertificate resources. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -21626,19 +20286,16 @@ class SslCertificateList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="SslCertificate", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 SslPolicy(proto.Message): @@ -21727,38 +20384,28 @@ class Profile(proto.Enum): """ UNDEFINED_PROFILE = 0 COMPATIBLE = 179357396 - CUSTOM = 120160113 + CUSTOM = 388595569 MODERN = 132013855 RESTRICTED = 261551195 - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - custom_features = proto.RepeatedField(proto.STRING, number=34789707) - - description = proto.Field(proto.STRING, number=154502140) - - enabled_features = proto.RepeatedField(proto.STRING, number=200582011) - - fingerprint = proto.Field(proto.STRING, number=234678500) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - min_tls_version = proto.Field(proto.ENUM, number=8155943, enum=MinTlsVersion,) - - name = proto.Field(proto.STRING, number=3373707) - - profile = proto.Field(proto.ENUM, number=227445161, enum=Profile,) - - self_link = proto.Field(proto.STRING, number=187779341) - - warnings = proto.RepeatedField(proto.MESSAGE, number=229655639, message="Warnings",) + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + custom_features = proto.RepeatedField(proto.STRING, number=34789707,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + enabled_features = proto.RepeatedField(proto.STRING, number=469017467,) + 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,) + min_tls_version = proto.Field( + proto.ENUM, number=8155943, optional=True, enum=MinTlsVersion, + ) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + profile = proto.Field(proto.ENUM, number=227445161, optional=True, enum=Profile,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + warnings = proto.RepeatedField(proto.MESSAGE, number=498091095, message="Warnings",) class SslPoliciesList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -21785,33 +20432,28 @@ class SslPoliciesList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="SslPolicy",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 SslPoliciesListAvailableFeaturesResponse(proto.Message): r""" - Attributes: features (Sequence[str]): """ - features = proto.RepeatedField(proto.STRING, number=246211645) + features = proto.RepeatedField(proto.STRING, number=246211645,) class SslPolicyReference(proto.Message): r""" - Attributes: ssl_policy (str): URL of the SSL policy resource. Set this to @@ -21819,12 +20461,11 @@ class SslPolicyReference(proto.Message): associated with the target proxy resource. """ - ssl_policy = proto.Field(proto.STRING, number=26754757) + ssl_policy = proto.Field(proto.STRING, number=295190213, optional=True,) class StatefulPolicyPreservedState(proto.Message): r"""Configuration of preserved resources. - Attributes: disks (Sequence[google.cloud.compute_v1.types.StatefulPolicyPreservedState.DisksEntry]): Disks created on the instances that will be @@ -21842,7 +20483,6 @@ class StatefulPolicyPreservedState(proto.Message): class StatefulPolicyPreservedStateDiskDevice(proto.Message): r""" - Attributes: auto_delete (google.cloud.compute_v1.types.StatefulPolicyPreservedStateDiskDevice.AutoDelete): These stateful disks will never be deleted during @@ -21865,12 +20505,13 @@ class AutoDelete(proto.Enum): NEVER = 74175084 ON_PERMANENT_INSTANCE_DELETION = 95727719 - auto_delete = proto.Field(proto.ENUM, number=196325947, enum=AutoDelete,) + auto_delete = proto.Field( + proto.ENUM, number=464761403, optional=True, enum=AutoDelete, + ) class SubnetworkLogConfig(proto.Message): r"""The available logging options for this subnetwork. - Attributes: aggregation_interval (google.cloud.compute_v1.types.SubnetworkLogConfig.AggregationInterval): Can only be specified if VPC flow logging for @@ -21914,8 +20555,8 @@ class AggregationInterval(proto.Enum): interval of 5 seconds per connection. """ UNDEFINED_AGGREGATION_INTERVAL = 0 - INTERVAL_10_MIN = 218720460 - INTERVAL_15_MIN = 223338065 + INTERVAL_10_MIN = 487155916 + INTERVAL_15_MIN = 491773521 INTERVAL_1_MIN = 69052714 INTERVAL_30_SEC = 7548937 INTERVAL_5_MIN = 72746798 @@ -21929,27 +20570,21 @@ class Metadata(proto.Enum): """ UNDEFINED_METADATA = 0 CUSTOM_METADATA = 62450749 - EXCLUDE_ALL_METADATA = 66084498 + EXCLUDE_ALL_METADATA = 334519954 INCLUDE_ALL_METADATA = 164619908 aggregation_interval = proto.Field( - proto.ENUM, number=174919042, enum=AggregationInterval, + proto.ENUM, number=174919042, optional=True, enum=AggregationInterval, ) - - enable = proto.Field(proto.BOOL, number=43328899) - - filter_expr = proto.Field(proto.STRING, number=183374428) - - flow_sampling = proto.Field(proto.FLOAT, number=261714904) - - metadata = proto.Field(proto.ENUM, number=86866735, enum=Metadata,) - - metadata_fields = proto.RepeatedField(proto.STRING, number=110026185) + enable = proto.Field(proto.BOOL, number=311764355, optional=True,) + filter_expr = proto.Field(proto.STRING, number=183374428, optional=True,) + flow_sampling = proto.Field(proto.FLOAT, number=530150360, optional=True,) + metadata = proto.Field(proto.ENUM, number=86866735, optional=True, enum=Metadata,) + metadata_fields = proto.RepeatedField(proto.STRING, number=378461641,) class SubnetworkSecondaryRange(proto.Message): r"""Represents a secondary IP range of a subnetwork. - Attributes: ip_cidr_range (str): The range of IP addresses belonging to this @@ -21968,9 +20603,8 @@ class SubnetworkSecondaryRange(proto.Message): name must be unique within the subnetwork. """ - ip_cidr_range = proto.Field(proto.STRING, number=98117322) - - range_name = proto.Field(proto.STRING, number=63780941) + ip_cidr_range = proto.Field(proto.STRING, number=98117322, optional=True,) + range_name = proto.Field(proto.STRING, number=332216397, optional=True,) class Subnetwork(proto.Message): @@ -22112,9 +20746,9 @@ class PrivateIpv6GoogleAccess(proto.Enum): using patch. """ UNDEFINED_PRIVATE_IPV6_GOOGLE_ACCESS = 0 - DISABLE_GOOGLE_ACCESS = 182523123 - ENABLE_BIDIRECTIONAL_ACCESS_TO_GOOGLE = 159540538 - ENABLE_OUTBOUND_VM_ACCESS_TO_GOOGLE = 19774807 + DISABLE_GOOGLE_ACCESS = 450958579 + ENABLE_BIDIRECTIONAL_ACCESS_TO_GOOGLE = 427975994 + ENABLE_OUTBOUND_VM_ACCESS_TO_GOOGLE = 288210263 class Purpose(proto.Enum): r"""The purpose of the resource. This field can be either @@ -22127,7 +20761,7 @@ class Purpose(proto.Enum): """ UNDEFINED_PURPOSE = 0 INTERNAL_HTTPS_LOAD_BALANCER = 248748889 - PRIVATE = 135049571 + PRIVATE = 403485027 PRIVATE_RFC_1918 = 254902107 class Role(proto.Enum): @@ -22139,8 +20773,8 @@ class Role(proto.Enum): draining. This field can be updated with a patch request. """ UNDEFINED_ROLE = 0 - ACTIVE = 46297862 - BACKUP = 72575426 + ACTIVE = 314733318 + BACKUP = 341010882 class State(proto.Enum): r"""[Output Only] The state of the subnetwork, which can be one of the @@ -22153,59 +20787,39 @@ class State(proto.Enum): deleted UPDATING: Subnetwork is being updated """ UNDEFINED_STATE = 0 - DRAINING = 212019946 + DRAINING = 480455402 READY = 77848963 - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - enable_flow_logs = proto.Field(proto.BOOL, number=151544420) - - fingerprint = proto.Field(proto.STRING, number=234678500) - - gateway_address = proto.Field(proto.STRING, number=191431929) - - id = proto.Field(proto.STRING, number=3355) - - ip_cidr_range = proto.Field(proto.STRING, number=98117322) - - ipv6_cidr_range = proto.Field(proto.STRING, number=4705802) - - kind = proto.Field(proto.STRING, number=3292052) - + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + enable_flow_logs = proto.Field(proto.BOOL, number=151544420, optional=True,) + fingerprint = proto.Field(proto.STRING, number=234678500, optional=True,) + gateway_address = proto.Field(proto.STRING, number=459867385, optional=True,) + id = proto.Field(proto.STRING, number=3355, optional=True,) + ip_cidr_range = proto.Field(proto.STRING, number=98117322, optional=True,) + ipv6_cidr_range = proto.Field(proto.STRING, number=273141258, optional=True,) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) log_config = proto.Field( - proto.MESSAGE, number=82864285, message="SubnetworkLogConfig", + proto.MESSAGE, number=351299741, optional=True, message="SubnetworkLogConfig", ) - - name = proto.Field(proto.STRING, number=3373707) - - network = proto.Field(proto.STRING, number=232872494) - - private_ip_google_access = proto.Field(proto.BOOL, number=153056334) - + name = proto.Field(proto.STRING, number=3373707, optional=True,) + network = proto.Field(proto.STRING, number=232872494, optional=True,) + private_ip_google_access = proto.Field(proto.BOOL, number=421491790, optional=True,) private_ipv6_google_access = proto.Field( - proto.ENUM, number=48277006, enum=PrivateIpv6GoogleAccess, + proto.ENUM, number=48277006, optional=True, enum=PrivateIpv6GoogleAccess, ) - - purpose = proto.Field(proto.ENUM, number=47971614, enum=Purpose,) - - region = proto.Field(proto.STRING, number=138946292) - - role = proto.Field(proto.ENUM, number=3506294, enum=Role,) - + purpose = proto.Field(proto.ENUM, number=316407070, optional=True, enum=Purpose,) + region = proto.Field(proto.STRING, number=138946292, optional=True,) + role = proto.Field(proto.ENUM, number=3506294, optional=True, enum=Role,) secondary_ip_ranges = proto.RepeatedField( proto.MESSAGE, number=136658915, message="SubnetworkSecondaryRange", ) - - self_link = proto.Field(proto.STRING, number=187779341) - - state = proto.Field(proto.ENUM, number=109757585, enum=State,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + state = proto.Field(proto.ENUM, number=109757585, optional=True, enum=State,) class SubnetworksScopedList(proto.Message): r""" - Attributes: subnetworks (Sequence[google.cloud.compute_v1.types.Subnetwork]): A list of subnetworks contained in this @@ -22216,15 +20830,15 @@ class SubnetworksScopedList(proto.Message): """ subnetworks = proto.RepeatedField( - proto.MESSAGE, number=147417669, message="Subnetwork", + proto.MESSAGE, number=415853125, message="Subnetwork", + ) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", ) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) class SubnetworkAggregatedList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -22254,26 +20868,21 @@ class SubnetworkAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="SubnetworksScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 SubnetworkList(proto.Message): r"""Contains a list of Subnetwork resources. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -22300,22 +20909,18 @@ class SubnetworkList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="Subnetwork",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 SubnetworksExpandIpCidrRangeRequest(proto.Message): r""" - Attributes: ip_cidr_range (str): The IP (in CIDR format or netmask) of @@ -22327,18 +20932,17 @@ class SubnetworksExpandIpCidrRangeRequest(proto.Message): update. """ - ip_cidr_range = proto.Field(proto.STRING, number=98117322) + ip_cidr_range = proto.Field(proto.STRING, number=98117322, optional=True,) class SubnetworksSetPrivateIpGoogleAccessRequest(proto.Message): r""" - Attributes: private_ip_google_access (bool): """ - private_ip_google_access = proto.Field(proto.BOOL, number=153056334) + private_ip_google_access = proto.Field(proto.BOOL, number=421491790, optional=True,) class TargetGrpcProxy(proto.Message): @@ -22408,30 +21012,20 @@ class TargetGrpcProxy(proto.Message): target URI of the service it is connecting to """ - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - fingerprint = proto.Field(proto.STRING, number=234678500) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - - self_link = proto.Field(proto.STRING, number=187779341) - - self_link_with_id = proto.Field(proto.STRING, number=44520962) - - url_map = proto.Field(proto.STRING, number=98585228) - - validate_for_proxyless = proto.Field(proto.BOOL, number=101822888) + 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,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + self_link_with_id = proto.Field(proto.STRING, number=44520962, optional=True,) + url_map = proto.Field(proto.STRING, number=367020684, optional=True,) + validate_for_proxyless = proto.Field(proto.BOOL, number=101822888, optional=True,) class TargetGrpcProxyList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -22458,19 +21052,16 @@ class TargetGrpcProxyList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="TargetGrpcProxy", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 TargetHttpProxy(proto.Message): @@ -22552,30 +21143,20 @@ class TargetHttpProxy(proto.Message): mapping from URL to the BackendService. """ - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - fingerprint = proto.Field(proto.STRING, number=234678500) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - - proxy_bind = proto.Field(proto.BOOL, number=17590126) - - region = proto.Field(proto.STRING, number=138946292) - - self_link = proto.Field(proto.STRING, number=187779341) - - url_map = proto.Field(proto.STRING, number=98585228) + 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,) + proxy_bind = proto.Field(proto.BOOL, number=286025582, optional=True,) + region = proto.Field(proto.STRING, number=138946292, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + url_map = proto.Field(proto.STRING, number=367020684, optional=True,) class TargetHttpProxiesScopedList(proto.Message): r""" - Attributes: target_http_proxies (Sequence[google.cloud.compute_v1.types.TargetHttpProxy]): A list of TargetHttpProxies contained in this @@ -22588,13 +21169,13 @@ class TargetHttpProxiesScopedList(proto.Message): target_http_proxies = proto.RepeatedField( proto.MESSAGE, number=162147011, message="TargetHttpProxy", ) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", + ) class TargetHttpProxyAggregatedList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -22623,27 +21204,21 @@ class TargetHttpProxyAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="TargetHttpProxiesScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) + 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,) class TargetHttpProxyList(proto.Message): r"""A list of TargetHttpProxy resources. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -22671,19 +21246,16 @@ class TargetHttpProxyList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="TargetHttpProxy", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 TargetHttpsProxy(proto.Message): @@ -22815,41 +21387,29 @@ class QuicOverride(proto.Enum): """ UNDEFINED_QUIC_OVERRIDE = 0 DISABLE = 241807048 - ENABLE = 170400131 + ENABLE = 438835587 NONE = 2402104 - authorization_policy = proto.Field(proto.STRING, number=33945528) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - - proxy_bind = proto.Field(proto.BOOL, number=17590126) - - quic_override = proto.Field(proto.ENUM, number=188141741, enum=QuicOverride,) - - region = proto.Field(proto.STRING, number=138946292) - - self_link = proto.Field(proto.STRING, number=187779341) - - server_tls_policy = proto.Field(proto.STRING, number=27389810) - - ssl_certificates = proto.RepeatedField(proto.STRING, number=97571087) - - ssl_policy = proto.Field(proto.STRING, number=26754757) - - url_map = proto.Field(proto.STRING, number=98585228) + 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,) + 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,) + quic_override = proto.Field( + proto.ENUM, number=456577197, optional=True, enum=QuicOverride, + ) + region = proto.Field(proto.STRING, number=138946292, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + server_tls_policy = proto.Field(proto.STRING, number=295825266, optional=True,) + ssl_certificates = proto.RepeatedField(proto.STRING, number=366006543,) + ssl_policy = proto.Field(proto.STRING, number=295190213, optional=True,) + url_map = proto.Field(proto.STRING, number=367020684, optional=True,) class TargetHttpsProxiesScopedList(proto.Message): r""" - Attributes: target_https_proxies (Sequence[google.cloud.compute_v1.types.TargetHttpsProxy]): A list of TargetHttpsProxies contained in @@ -22860,15 +21420,15 @@ class TargetHttpsProxiesScopedList(proto.Message): """ target_https_proxies = proto.RepeatedField( - proto.MESSAGE, number=98172426, message="TargetHttpsProxy", + proto.MESSAGE, number=366607882, message="TargetHttpsProxy", + ) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", ) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) class TargetHttpsProxiesSetQuicOverrideRequest(proto.Message): r""" - Attributes: quic_override (google.cloud.compute_v1.types.TargetHttpsProxiesSetQuicOverrideRequest.QuicOverride): QUIC policy for the TargetHttpsProxy @@ -22879,15 +21439,16 @@ class QuicOverride(proto.Enum): r"""QUIC policy for the TargetHttpsProxy resource.""" UNDEFINED_QUIC_OVERRIDE = 0 DISABLE = 241807048 - ENABLE = 170400131 + ENABLE = 438835587 NONE = 2402104 - quic_override = proto.Field(proto.ENUM, number=188141741, enum=QuicOverride,) + quic_override = proto.Field( + proto.ENUM, number=456577197, optional=True, enum=QuicOverride, + ) class TargetHttpsProxiesSetSslCertificatesRequest(proto.Message): r""" - Attributes: ssl_certificates (Sequence[str]): New set of SslCertificate resources to @@ -22896,12 +21457,11 @@ class TargetHttpsProxiesSetSslCertificatesRequest(proto.Message): must be specified. """ - ssl_certificates = proto.RepeatedField(proto.STRING, number=97571087) + ssl_certificates = proto.RepeatedField(proto.STRING, number=366006543,) class TargetHttpsProxyAggregatedList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -22932,29 +21492,24 @@ class TargetHttpsProxyAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="TargetHttpsProxiesScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 TargetHttpsProxyList(proto.Message): r"""Contains a list of TargetHttpsProxy resources. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -22982,19 +21537,16 @@ class TargetHttpsProxyList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="TargetHttpsProxy", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 TargetInstance(proto.Message): @@ -23057,28 +21609,21 @@ class NatPolicy(proto.Enum): UNDEFINED_NAT_POLICY = 0 NO_NAT = 161455491 - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - id = proto.Field(proto.STRING, number=3355) - - instance = proto.Field(proto.STRING, number=18257045) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - - nat_policy = proto.Field(proto.ENUM, number=241345040, enum=NatPolicy,) - - self_link = proto.Field(proto.STRING, number=187779341) - - zone = proto.Field(proto.STRING, number=3744684) + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + id = proto.Field(proto.STRING, number=3355, optional=True,) + instance = proto.Field(proto.STRING, number=18257045, optional=True,) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + nat_policy = proto.Field( + proto.ENUM, number=509780496, optional=True, enum=NatPolicy, + ) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + zone = proto.Field(proto.STRING, number=3744684, optional=True,) class TargetInstancesScopedList(proto.Message): r""" - Attributes: target_instances (Sequence[google.cloud.compute_v1.types.TargetInstance]): A list of target instances contained in this @@ -23089,15 +21634,15 @@ class TargetInstancesScopedList(proto.Message): """ target_instances = proto.RepeatedField( - proto.MESSAGE, number=124479824, message="TargetInstance", + proto.MESSAGE, number=392915280, message="TargetInstance", + ) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", ) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) class TargetInstanceAggregatedList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -23125,29 +21670,24 @@ class TargetInstanceAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="TargetInstancesScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 TargetInstanceList(proto.Message): r"""Contains a list of TargetInstance resources. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -23173,19 +21713,16 @@ class TargetInstanceList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="TargetInstance", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 TargetPool(proto.Message): @@ -23294,42 +21831,32 @@ class SessionAffinity(proto.Enum): instance remains healthy. """ UNDEFINED_SESSION_AFFINITY = 0 - CLIENT_IP = 77229595 + CLIENT_IP = 345665051 CLIENT_IP_PORT_PROTO = 221722926 CLIENT_IP_PROTO = 25322148 - GENERATED_COOKIE = 101885748 + GENERATED_COOKIE = 370321204 HEADER_FIELD = 200737960 - HTTP_COOKIE = 226546171 + HTTP_COOKIE = 494981627 NONE = 2402104 - backup_pool = proto.Field(proto.STRING, number=45884537) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - failover_ratio = proto.Field(proto.FLOAT, number=212667006) - - health_checks = proto.RepeatedField(proto.STRING, number=179935150) - - id = proto.Field(proto.STRING, number=3355) - - instances = proto.RepeatedField(proto.STRING, number=29097598) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - - region = proto.Field(proto.STRING, number=138946292) - - self_link = proto.Field(proto.STRING, number=187779341) - - session_affinity = proto.Field(proto.ENUM, number=195453105, enum=SessionAffinity,) + backup_pool = proto.Field(proto.STRING, number=45884537, optional=True,) + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + failover_ratio = proto.Field(proto.FLOAT, number=212667006, optional=True,) + health_checks = proto.RepeatedField(proto.STRING, number=448370606,) + id = proto.Field(proto.STRING, number=3355, optional=True,) + instances = proto.RepeatedField(proto.STRING, number=29097598,) + 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,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + session_affinity = proto.Field( + proto.ENUM, number=463888561, optional=True, enum=SessionAffinity, + ) class TargetPoolsScopedList(proto.Message): r""" - Attributes: target_pools (Sequence[google.cloud.compute_v1.types.TargetPool]): A list of target pools contained in this @@ -23340,15 +21867,15 @@ class TargetPoolsScopedList(proto.Message): """ target_pools = proto.RepeatedField( - proto.MESSAGE, number=67637161, message="TargetPool", + proto.MESSAGE, number=336072617, message="TargetPool", + ) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", ) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) class TargetPoolAggregatedList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -23378,26 +21905,21 @@ class TargetPoolAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="TargetPoolsScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 TargetPoolInstanceHealth(proto.Message): r""" - Attributes: health_status (Sequence[google.cloud.compute_v1.types.HealthStatus]): @@ -23408,15 +21930,13 @@ class TargetPoolInstanceHealth(proto.Message): """ health_status = proto.RepeatedField( - proto.MESSAGE, number=112110389, message="HealthStatus", + proto.MESSAGE, number=380545845, message="HealthStatus", ) - - kind = proto.Field(proto.STRING, number=3292052) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) class TargetPoolList(proto.Message): r"""Contains a list of TargetPool resources. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -23443,22 +21963,18 @@ class TargetPoolList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="TargetPool",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 TargetPoolsAddHealthCheckRequest(proto.Message): r""" - Attributes: health_checks (Sequence[google.cloud.compute_v1.types.HealthCheckReference]): The HttpHealthCheck to add to the target @@ -23466,13 +21982,12 @@ class TargetPoolsAddHealthCheckRequest(proto.Message): """ health_checks = proto.RepeatedField( - proto.MESSAGE, number=179935150, message="HealthCheckReference", + proto.MESSAGE, number=448370606, message="HealthCheckReference", ) class TargetPoolsAddInstanceRequest(proto.Message): r""" - Attributes: instances (Sequence[google.cloud.compute_v1.types.InstanceReference]): A full or partial URL to an instance to add @@ -23493,7 +22008,6 @@ class TargetPoolsAddInstanceRequest(proto.Message): class TargetPoolsRemoveHealthCheckRequest(proto.Message): r""" - Attributes: health_checks (Sequence[google.cloud.compute_v1.types.HealthCheckReference]): Health check URL to be removed. This can be a @@ -23506,13 +22020,12 @@ class TargetPoolsRemoveHealthCheckRequest(proto.Message): """ health_checks = proto.RepeatedField( - proto.MESSAGE, number=179935150, message="HealthCheckReference", + proto.MESSAGE, number=448370606, message="HealthCheckReference", ) class TargetPoolsRemoveInstanceRequest(proto.Message): r""" - Attributes: instances (Sequence[google.cloud.compute_v1.types.InstanceReference]): URLs of the instances to be removed from @@ -23526,30 +22039,27 @@ class TargetPoolsRemoveInstanceRequest(proto.Message): class TargetReference(proto.Message): r""" - Attributes: target (str): """ - target = proto.Field(proto.STRING, number=192835985) + target = proto.Field(proto.STRING, number=192835985, optional=True,) class TargetSslProxiesSetBackendServiceRequest(proto.Message): r""" - Attributes: service (str): The URL of the new BackendService resource for the targetSslProxy. """ - service = proto.Field(proto.STRING, number=105105077) + service = proto.Field(proto.STRING, number=373540533, optional=True,) class TargetSslProxiesSetProxyHeaderRequest(proto.Message): r""" - Attributes: proxy_header (google.cloud.compute_v1.types.TargetSslProxiesSetProxyHeaderRequest.ProxyHeader): The new type of proxy header to append before sending data @@ -23562,14 +22072,15 @@ class ProxyHeader(proto.Enum): """ UNDEFINED_PROXY_HEADER = 0 NONE = 2402104 - PROXY_V1 = 65917484 + PROXY_V1 = 334352940 - proxy_header = proto.Field(proto.ENUM, number=160374142, enum=ProxyHeader,) + proxy_header = proto.Field( + proto.ENUM, number=160374142, optional=True, enum=ProxyHeader, + ) class TargetSslProxiesSetSslCertificatesRequest(proto.Message): r""" - Attributes: ssl_certificates (Sequence[str]): New set of URLs to SslCertificate resources @@ -23577,7 +22088,7 @@ class TargetSslProxiesSetSslCertificatesRequest(proto.Message): exactly one ssl certificate must be specified. """ - ssl_certificates = proto.RepeatedField(proto.STRING, number=97571087) + ssl_certificates = proto.RepeatedField(proto.STRING, number=366006543,) class TargetSslProxy(proto.Message): @@ -23638,32 +22149,24 @@ class ProxyHeader(proto.Enum): """ UNDEFINED_PROXY_HEADER = 0 NONE = 2402104 - PROXY_V1 = 65917484 - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - - proxy_header = proto.Field(proto.ENUM, number=160374142, enum=ProxyHeader,) - - self_link = proto.Field(proto.STRING, number=187779341) + PROXY_V1 = 334352940 - service = proto.Field(proto.STRING, number=105105077) - - ssl_certificates = proto.RepeatedField(proto.STRING, number=97571087) - - ssl_policy = proto.Field(proto.STRING, number=26754757) + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, 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,) + proxy_header = proto.Field( + proto.ENUM, number=160374142, optional=True, enum=ProxyHeader, + ) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + service = proto.Field(proto.STRING, number=373540533, optional=True,) + ssl_certificates = proto.RepeatedField(proto.STRING, number=366006543,) + ssl_policy = proto.Field(proto.STRING, number=295190213, optional=True,) class TargetSslProxyList(proto.Message): r"""Contains a list of TargetSslProxy resources. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -23689,36 +22192,31 @@ class TargetSslProxyList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="TargetSslProxy", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 TargetTcpProxiesSetBackendServiceRequest(proto.Message): r""" - Attributes: service (str): The URL of the new BackendService resource for the targetTcpProxy. """ - service = proto.Field(proto.STRING, number=105105077) + service = proto.Field(proto.STRING, number=373540533, optional=True,) class TargetTcpProxiesSetProxyHeaderRequest(proto.Message): r""" - Attributes: proxy_header (google.cloud.compute_v1.types.TargetTcpProxiesSetProxyHeaderRequest.ProxyHeader): The new type of proxy header to append before sending data @@ -23731,9 +22229,11 @@ class ProxyHeader(proto.Enum): """ UNDEFINED_PROXY_HEADER = 0 NONE = 2402104 - PROXY_V1 = 65917484 + PROXY_V1 = 334352940 - proxy_header = proto.Field(proto.ENUM, number=160374142, enum=ProxyHeader,) + proxy_header = proto.Field( + proto.ENUM, number=160374142, optional=True, enum=ProxyHeader, + ) class TargetTcpProxy(proto.Message): @@ -23783,28 +22283,22 @@ class ProxyHeader(proto.Enum): """ UNDEFINED_PROXY_HEADER = 0 NONE = 2402104 - PROXY_V1 = 65917484 + PROXY_V1 = 334352940 - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - - proxy_header = proto.Field(proto.ENUM, number=160374142, enum=ProxyHeader,) - - self_link = proto.Field(proto.STRING, number=187779341) - - service = proto.Field(proto.STRING, number=105105077) + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, 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,) + proxy_header = proto.Field( + proto.ENUM, number=160374142, optional=True, enum=ProxyHeader, + ) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + service = proto.Field(proto.STRING, number=373540533, optional=True,) class TargetTcpProxyList(proto.Message): r"""Contains a list of TargetTcpProxy resources. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -23830,19 +22324,16 @@ class TargetTcpProxyList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="TargetTcpProxy", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 TargetVpnGateway(proto.Message): @@ -23904,37 +22395,26 @@ class Status(proto.Enum): following: CREATING, READY, FAILED, or DELETING. """ UNDEFINED_STATUS = 0 - CREATING = 187129529 - DELETING = 260166568 - FAILED = 187271229 + CREATING = 455564985 + DELETING = 528602024 + FAILED = 455706685 READY = 77848963 - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - forwarding_rules = proto.RepeatedField(proto.STRING, number=47385909) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - - network = proto.Field(proto.STRING, number=232872494) - - region = proto.Field(proto.STRING, number=138946292) - - self_link = proto.Field(proto.STRING, number=187779341) - - status = proto.Field(proto.ENUM, number=181260274, enum=Status,) - - tunnels = proto.RepeatedField(proto.STRING, number=104561931) + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + forwarding_rules = proto.RepeatedField(proto.STRING, number=315821365,) + 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,) + network = proto.Field(proto.STRING, number=232872494, optional=True,) + 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,) + tunnels = proto.RepeatedField(proto.STRING, number=104561931,) class TargetVpnGatewaysScopedList(proto.Message): r""" - Attributes: target_vpn_gateways (Sequence[google.cloud.compute_v1.types.TargetVpnGateway]): [Output Only] A list of target VPN gateways contained in @@ -23945,15 +22425,15 @@ class TargetVpnGatewaysScopedList(proto.Message): """ target_vpn_gateways = proto.RepeatedField( - proto.MESSAGE, number=133335432, message="TargetVpnGateway", + proto.MESSAGE, number=401770888, message="TargetVpnGateway", + ) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", ) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) class TargetVpnGatewayAggregatedList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -23982,29 +22462,24 @@ class TargetVpnGatewayAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="TargetVpnGatewaysScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 TargetVpnGatewayList(proto.Message): r"""Contains a list of TargetVpnGateway resources. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -24031,24 +22506,20 @@ class TargetVpnGatewayList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="TargetVpnGateway", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 TestFailure(proto.Message): r""" - Attributes: actual_service (str): BackendService or BackendBucket returned by @@ -24063,18 +22534,14 @@ class TestFailure(proto.Message): the URL. """ - actual_service = proto.Field(proto.STRING, number=171944196) - - expected_service = proto.Field(proto.STRING, number=133987374) - - host = proto.Field(proto.STRING, number=3208616) - - path = proto.Field(proto.STRING, number=3433509) + actual_service = proto.Field(proto.STRING, number=440379652, optional=True,) + expected_service = proto.Field(proto.STRING, number=133987374, optional=True,) + host = proto.Field(proto.STRING, number=3208616, optional=True,) + path = proto.Field(proto.STRING, number=3433509, optional=True,) class TestPermissionsRequest(proto.Message): r""" - Attributes: permissions (Sequence[str]): The set of permissions to check for the 'resource'. @@ -24082,24 +22549,22 @@ class TestPermissionsRequest(proto.Message): not allowed. """ - permissions = proto.RepeatedField(proto.STRING, number=59962500) + permissions = proto.RepeatedField(proto.STRING, number=59962500,) class TestPermissionsResponse(proto.Message): r""" - Attributes: permissions (Sequence[str]): A subset of ``TestPermissionsRequest.permissions`` that the caller is allowed. """ - permissions = proto.RepeatedField(proto.STRING, number=59962500) + permissions = proto.RepeatedField(proto.STRING, number=59962500,) class UrlMapTest(proto.Message): r"""Message for the expected URL mappings. - Attributes: description (str): Description of this test case. @@ -24116,18 +22581,14 @@ class UrlMapTest(proto.Message): expectedRedirectResponseCode is set. """ - description = proto.Field(proto.STRING, number=154502140) - - host = proto.Field(proto.STRING, number=3208616) - - path = proto.Field(proto.STRING, number=3433509) - - service = proto.Field(proto.STRING, number=105105077) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + 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,) class UrlMapList(proto.Message): r"""Contains a list of UrlMap resources. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -24153,33 +22614,28 @@ class UrlMapList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="UrlMap",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 UrlMapReference(proto.Message): r""" - Attributes: url_map (str): """ - url_map = proto.Field(proto.STRING, number=98585228) + url_map = proto.Field(proto.STRING, number=367020684, optional=True,) class UrlMapValidationResult(proto.Message): r"""Message representing the validation result for a UrlMap. - Attributes: load_errors (Sequence[str]): @@ -24195,20 +22651,16 @@ class UrlMapValidationResult(proto.Message): 'testFailures's indicate the reason of failure. """ - load_errors = proto.RepeatedField(proto.STRING, number=41711844) - - load_succeeded = proto.Field(proto.BOOL, number=128326216) - + load_errors = proto.RepeatedField(proto.STRING, number=310147300,) + load_succeeded = proto.Field(proto.BOOL, number=128326216, optional=True,) test_failures = proto.RepeatedField( - proto.MESSAGE, number=237498678, message="TestFailure", + proto.MESSAGE, number=505934134, message="TestFailure", ) - - test_passed = proto.Field(proto.BOOL, number=192708797) + test_passed = proto.Field(proto.BOOL, number=192708797, optional=True,) class UrlMapsScopedList(proto.Message): r""" - Attributes: url_maps (Sequence[google.cloud.compute_v1.types.UrlMap]): A list of UrlMaps contained in this scope. @@ -24218,13 +22670,13 @@ class UrlMapsScopedList(proto.Message): """ url_maps = proto.RepeatedField(proto.MESSAGE, number=103352167, message="UrlMap",) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", + ) class UrlMapsAggregatedList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -24252,50 +22704,48 @@ class UrlMapsAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="UrlMapsScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 UrlMapsValidateRequest(proto.Message): r""" - Attributes: resource (google.cloud.compute_v1.types.UrlMap): Content of the UrlMap to be validated. """ - resource = proto.Field(proto.MESSAGE, number=195806222, message="UrlMap",) + resource = proto.Field( + proto.MESSAGE, number=195806222, optional=True, message="UrlMap", + ) class UrlMapsValidateResponse(proto.Message): r""" - Attributes: result (google.cloud.compute_v1.types.UrlMapValidationResult): """ result = proto.Field( - proto.MESSAGE, number=139315229, message="UrlMapValidationResult", + proto.MESSAGE, + number=139315229, + optional=True, + message="UrlMapValidationResult", ) class UsableSubnetworkSecondaryRange(proto.Message): r"""Secondary IP range of a usable subnetwork. - Attributes: ip_cidr_range (str): The range of IP addresses belonging to this @@ -24308,9 +22758,8 @@ class UsableSubnetworkSecondaryRange(proto.Message): name must be unique within the subnetwork. """ - ip_cidr_range = proto.Field(proto.STRING, number=98117322) - - range_name = proto.Field(proto.STRING, number=63780941) + ip_cidr_range = proto.Field(proto.STRING, number=98117322, optional=True,) + range_name = proto.Field(proto.STRING, number=332216397, optional=True,) class UsableSubnetwork(proto.Message): @@ -24329,20 +22778,16 @@ class UsableSubnetwork(proto.Message): Subnetwork URL. """ - ip_cidr_range = proto.Field(proto.STRING, number=98117322) - - network = proto.Field(proto.STRING, number=232872494) - + ip_cidr_range = proto.Field(proto.STRING, number=98117322, optional=True,) + network = proto.Field(proto.STRING, number=232872494, optional=True,) secondary_ip_ranges = proto.RepeatedField( proto.MESSAGE, number=136658915, message="UsableSubnetworkSecondaryRange", ) - - subnetwork = proto.Field(proto.STRING, number=39392238) + subnetwork = proto.Field(proto.STRING, number=307827694, optional=True,) class UsableSubnetworksAggregatedList(proto.Message): r""" - Attributes: id (str): [Output Only] The unique identifier for the resource. This @@ -24370,19 +22815,16 @@ class UsableSubnetworksAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField( proto.MESSAGE, number=100526016, message="UsableSubnetwork", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 VmEndpointNatMappingsInterfaceNatMappings(proto.Message): @@ -24416,17 +22858,14 @@ class VmEndpointNatMappingsInterfaceNatMappings(proto.Message): Primary IP of the VM for this NIC. """ - drain_nat_ip_port_ranges = proto.RepeatedField(proto.STRING, number=127005121) - - nat_ip_port_ranges = proto.RepeatedField(proto.STRING, number=263395354) - - num_total_drain_nat_ports = proto.Field(proto.INT32, number=67097337) - - num_total_nat_ports = proto.Field(proto.INT32, number=31468928) - - source_alias_ip_range = proto.Field(proto.STRING, number=171905496) - - source_virtual_ip = proto.Field(proto.STRING, number=149836159) + drain_nat_ip_port_ranges = proto.RepeatedField(proto.STRING, number=395440577,) + nat_ip_port_ranges = proto.RepeatedField(proto.STRING, number=531830810,) + num_total_drain_nat_ports = proto.Field( + proto.INT32, number=335532793, optional=True, + ) + num_total_nat_ports = proto.Field(proto.INT32, number=299904384, optional=True,) + source_alias_ip_range = proto.Field(proto.STRING, number=440340952, optional=True,) + source_virtual_ip = proto.Field(proto.STRING, number=149836159, optional=True,) class VmEndpointNatMappings(proto.Message): @@ -24441,8 +22880,7 @@ class VmEndpointNatMappings(proto.Message): """ - instance_name = proto.Field(proto.STRING, number=227947509) - + instance_name = proto.Field(proto.STRING, number=227947509, optional=True,) interface_nat_mappings = proto.RepeatedField( proto.MESSAGE, number=256196617, @@ -24452,7 +22890,6 @@ class VmEndpointNatMappings(proto.Message): class VmEndpointNatMappingsList(proto.Message): r"""Contains a list of VmEndpointNatMappings. - Attributes: id (str): [Output Only] The unique identifier for the resource. This @@ -24481,24 +22918,20 @@ class VmEndpointNatMappingsList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - + id = proto.Field(proto.STRING, number=3355, optional=True,) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) + next_page_token = proto.Field(proto.STRING, number=79797525, optional=True,) result = proto.RepeatedField( proto.MESSAGE, number=139315229, message="VmEndpointNatMappings", ) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", + ) class VpnGatewayVpnGatewayInterface(proto.Message): r"""A VPN gateway interface. - Attributes: id (int): The numeric ID of this VPN gateway interface. @@ -24507,9 +22940,8 @@ class VpnGatewayVpnGatewayInterface(proto.Message): interface. """ - id = proto.Field(proto.UINT32, number=3355) - - ip_address = proto.Field(proto.STRING, number=137836764) + id = proto.Field(proto.UINT32, number=3355, optional=True,) + ip_address = proto.Field(proto.STRING, number=406272220, optional=True,) class VpnGateway(proto.Message): @@ -24574,26 +23006,16 @@ class VpnGateway(proto.Message): A list of interfaces on this VPN gateway. """ - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - label_fingerprint = proto.Field(proto.STRING, number=178124825) - - labels = proto.MapField(proto.STRING, proto.STRING, number=231759871) - - name = proto.Field(proto.STRING, number=3373707) - - network = proto.Field(proto.STRING, number=232872494) - - region = proto.Field(proto.STRING, number=138946292) - - self_link = proto.Field(proto.STRING, number=187779341) - + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + id = proto.Field(proto.STRING, number=3355, 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,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + network = proto.Field(proto.STRING, number=232872494, optional=True,) + region = proto.Field(proto.STRING, number=138946292, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) vpn_interfaces = proto.RepeatedField( proto.MESSAGE, number=91842181, message="VpnGatewayVpnGatewayInterface", ) @@ -24601,7 +23023,6 @@ class VpnGateway(proto.Message): class VpnGatewaysScopedList(proto.Message): r""" - Attributes: vpn_gateways (Sequence[google.cloud.compute_v1.types.VpnGateway]): [Output Only] A list of VPN gateways contained in this @@ -24614,13 +23035,13 @@ class VpnGatewaysScopedList(proto.Message): vpn_gateways = proto.RepeatedField( proto.MESSAGE, number=259177882, message="VpnGateway", ) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", + ) class VpnGatewayAggregatedList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -24649,26 +23070,21 @@ class VpnGatewayAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="VpnGatewaysScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 VpnGatewayList(proto.Message): r"""Contains a list of VpnGateway resources. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -24695,17 +23111,14 @@ class VpnGatewayList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="VpnGateway",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 VpnGatewayStatusVpnConnection(proto.Message): @@ -24730,16 +23143,14 @@ class VpnGatewayStatusVpnConnection(proto.Message): connection. """ - peer_external_gateway = proto.Field(proto.STRING, number=116520717) - - peer_gcp_gateway = proto.Field(proto.STRING, number=13431996) - + peer_external_gateway = proto.Field(proto.STRING, number=384956173, optional=True,) + peer_gcp_gateway = proto.Field(proto.STRING, number=281867452, optional=True,) state = proto.Field( proto.MESSAGE, number=109757585, + optional=True, message="VpnGatewayStatusHighAvailabilityRequirementState", ) - tunnels = proto.RepeatedField( proto.MESSAGE, number=104561931, message="VpnGatewayStatusTunnel", ) @@ -24747,14 +23158,13 @@ class VpnGatewayStatusVpnConnection(proto.Message): class VpnGatewayStatus(proto.Message): r""" - Attributes: vpn_connections (Sequence[google.cloud.compute_v1.types.VpnGatewayStatusVpnConnection]): List of VPN connection for this VpnGateway. """ vpn_connections = proto.RepeatedField( - proto.MESSAGE, number=170899082, message="VpnGatewayStatusVpnConnection", + proto.MESSAGE, number=439334538, message="VpnGatewayStatusVpnConnection", ) @@ -24779,8 +23189,8 @@ class State(proto.Enum): CONNECTION_REDUNDANCY_NOT_MET. """ UNDEFINED_STATE = 0 - CONNECTION_REDUNDANCY_MET = 236807451 - CONNECTION_REDUNDANCY_NOT_MET = 243427855 + CONNECTION_REDUNDANCY_MET = 505242907 + CONNECTION_REDUNDANCY_NOT_MET = 511863311 class UnsatisfiedReason(proto.Enum): r"""Indicates the reason why the VPN connection does not meet the high @@ -24790,16 +23200,14 @@ class UnsatisfiedReason(proto.Enum): UNDEFINED_UNSATISFIED_REASON = 0 INCOMPLETE_TUNNELS_COVERAGE = 55917437 - state = proto.Field(proto.ENUM, number=109757585, enum=State,) - + state = proto.Field(proto.ENUM, number=109757585, optional=True, enum=State,) unsatisfied_reason = proto.Field( - proto.ENUM, number=55016330, enum=UnsatisfiedReason, + proto.ENUM, number=55016330, optional=True, enum=UnsatisfiedReason, ) class VpnGatewayStatusTunnel(proto.Message): r"""Contains some information about a VPN tunnel. - Attributes: local_gateway_interface (int): The VPN gateway interface this VPN tunnel is @@ -24812,22 +23220,23 @@ class VpnGatewayStatusTunnel(proto.Message): URL reference to the VPN tunnel. """ - local_gateway_interface = proto.Field(proto.UINT32, number=158764330) - - peer_gateway_interface = proto.Field(proto.UINT32, number=214380385) - - tunnel_url = proto.Field(proto.STRING, number=78975256) + local_gateway_interface = proto.Field( + proto.UINT32, number=158764330, optional=True, + ) + peer_gateway_interface = proto.Field(proto.UINT32, number=214380385, optional=True,) + tunnel_url = proto.Field(proto.STRING, number=78975256, optional=True,) class VpnGatewaysGetStatusResponse(proto.Message): r""" - Attributes: result (google.cloud.compute_v1.types.VpnGatewayStatus): """ - result = proto.Field(proto.MESSAGE, number=139315229, message="VpnGatewayStatus",) + result = proto.Field( + proto.MESSAGE, number=139315229, optional=True, message="VpnGatewayStatus", + ) class VpnTunnel(proto.Message): @@ -24998,68 +23407,48 @@ class Status(proto.Enum): for an HA-VPN tunnel. """ UNDEFINED_STATUS = 0 - ALLOCATING_RESOURCES = 52487360 + ALLOCATING_RESOURCES = 320922816 AUTHORIZATION_ERROR = 23580290 - DEPROVISIONING = 160500206 + DEPROVISIONING = 428935662 ESTABLISHED = 88852344 - FAILED = 187271229 + FAILED = 455706685 FIRST_HANDSHAKE = 191393000 - NEGOTIATION_FAILURE = 91890412 + NEGOTIATION_FAILURE = 360325868 NETWORK_ERROR = 193912951 NO_INCOMING_PACKETS = 119983216 - PROVISIONING = 22461165 + PROVISIONING = 290896621 REJECTED = 174130302 - STOPPED = 175840685 + STOPPED = 444276141 WAITING_FOR_FULL_CONFIG = 41640522 - creation_timestamp = proto.Field(proto.STRING, number=30525366) - - description = proto.Field(proto.STRING, number=154502140) - - detailed_status = proto.Field(proto.STRING, number=65065569) - - id = proto.Field(proto.STRING, number=3355) - - ike_version = proto.Field(proto.INT32, number=218376220) - - kind = proto.Field(proto.STRING, number=3292052) - - local_traffic_selector = proto.RepeatedField(proto.STRING, number=48879157) - - name = proto.Field(proto.STRING, number=3373707) - - peer_external_gateway = proto.Field(proto.STRING, number=116520717) - - peer_external_gateway_interface = proto.Field(proto.INT32, number=184332935) - - peer_gcp_gateway = proto.Field(proto.STRING, number=13431996) - - peer_ip = proto.Field(proto.STRING, number=114814244) - - region = proto.Field(proto.STRING, number=138946292) - - remote_traffic_selector = proto.RepeatedField(proto.STRING, number=90451642) - - router = proto.Field(proto.STRING, number=148608841) - - self_link = proto.Field(proto.STRING, number=187779341) - - shared_secret = proto.Field(proto.STRING, number=113497034) - - shared_secret_hash = proto.Field(proto.STRING, number=130446435) - - status = proto.Field(proto.ENUM, number=181260274, enum=Status,) - - target_vpn_gateway = proto.Field(proto.STRING, number=264077387) - - vpn_gateway = proto.Field(proto.STRING, number=138248697) - - vpn_gateway_interface = proto.Field(proto.INT32, number=95979123) + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) + description = proto.Field(proto.STRING, number=422937596, optional=True,) + detailed_status = proto.Field(proto.STRING, number=333501025, optional=True,) + id = proto.Field(proto.STRING, number=3355, optional=True,) + ike_version = proto.Field(proto.INT32, number=218376220, optional=True,) + kind = proto.Field(proto.STRING, number=3292052, optional=True,) + local_traffic_selector = proto.RepeatedField(proto.STRING, number=317314613,) + name = proto.Field(proto.STRING, number=3373707, optional=True,) + peer_external_gateway = proto.Field(proto.STRING, number=384956173, optional=True,) + peer_external_gateway_interface = proto.Field( + proto.INT32, number=452768391, optional=True, + ) + peer_gcp_gateway = proto.Field(proto.STRING, number=281867452, optional=True,) + peer_ip = proto.Field(proto.STRING, number=383249700, optional=True,) + region = proto.Field(proto.STRING, number=138946292, optional=True,) + remote_traffic_selector = proto.RepeatedField(proto.STRING, number=358887098,) + router = proto.Field(proto.STRING, number=148608841, optional=True,) + self_link = proto.Field(proto.STRING, number=456214797, optional=True,) + shared_secret = proto.Field(proto.STRING, number=381932490, optional=True,) + shared_secret_hash = proto.Field(proto.STRING, number=398881891, optional=True,) + status = proto.Field(proto.ENUM, number=181260274, optional=True, enum=Status,) + target_vpn_gateway = proto.Field(proto.STRING, number=532512843, optional=True,) + vpn_gateway = proto.Field(proto.STRING, number=406684153, optional=True,) + vpn_gateway_interface = proto.Field(proto.INT32, number=95979123, optional=True,) class VpnTunnelsScopedList(proto.Message): r""" - Attributes: vpn_tunnels (Sequence[google.cloud.compute_v1.types.VpnTunnel]): A list of VPN tunnels contained in this @@ -25072,13 +23461,13 @@ class VpnTunnelsScopedList(proto.Message): vpn_tunnels = proto.RepeatedField( proto.MESSAGE, number=163494080, message="VpnTunnel", ) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + warning = proto.Field( + proto.MESSAGE, number=50704284, optional=True, message="Warning", + ) class VpnTunnelAggregatedList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -25107,26 +23496,21 @@ class VpnTunnelAggregatedList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.MapField( proto.STRING, proto.MESSAGE, number=100526016, message="VpnTunnelsScopedList", ) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - unreachables = proto.RepeatedField(proto.STRING, number=243372063) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 VpnTunnelList(proto.Message): r"""Contains a list of VpnTunnel resources. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -25153,22 +23537,18 @@ class VpnTunnelList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="VpnTunnel",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 WafExpressionSetExpression(proto.Message): r""" - Attributes: id (str): Expression ID should uniquely identify the @@ -25181,12 +23561,11 @@ class WafExpressionSetExpression(proto.Message): false positive. """ - id = proto.Field(proto.STRING, number=3355) + id = proto.Field(proto.STRING, number=3355, optional=True,) class XpnHostList(proto.Message): r""" - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -25213,17 +23592,14 @@ class XpnHostList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="Project",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 Zone(proto.Message): @@ -25268,32 +23644,22 @@ class Status(proto.Enum): DOWN = 2104482 UP = 2715 - available_cpu_platforms = proto.RepeatedField(proto.STRING, number=175536531) - - creation_timestamp = proto.Field(proto.STRING, number=30525366) - + available_cpu_platforms = proto.RepeatedField(proto.STRING, number=175536531,) + creation_timestamp = proto.Field(proto.STRING, number=30525366, optional=True,) deprecated = proto.Field( - proto.MESSAGE, number=246703539, message="DeprecationStatus", + proto.MESSAGE, number=515138995, optional=True, message="DeprecationStatus", ) - - description = proto.Field(proto.STRING, number=154502140) - - id = proto.Field(proto.STRING, number=3355) - - kind = proto.Field(proto.STRING, number=3292052) - - name = proto.Field(proto.STRING, number=3373707) - - region = proto.Field(proto.STRING, number=138946292) - - self_link = proto.Field(proto.STRING, number=187779341) - - status = proto.Field(proto.ENUM, number=181260274, enum=Status,) + description = proto.Field(proto.STRING, number=422937596, 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,) + 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 ZoneList(proto.Message): r"""Contains a list of zone resources. - Attributes: id (str): [Output Only] Unique identifier for the resource; defined by @@ -25319,22 +23685,18 @@ class ZoneList(proto.Message): def raw_page(self): return self - id = proto.Field(proto.STRING, number=3355) - + id = proto.Field(proto.STRING, number=3355, optional=True,) items = proto.RepeatedField(proto.MESSAGE, number=100526016, message="Zone",) - - kind = proto.Field(proto.STRING, number=3292052) - - next_page_token = proto.Field(proto.STRING, number=79797525) - - self_link = proto.Field(proto.STRING, number=187779341) - - warning = proto.Field(proto.MESSAGE, number=50704284, message="Warning",) + 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 ZoneSetLabelsRequest(proto.Message): r""" - Attributes: label_fingerprint (str): The fingerprint of the previous set of labels @@ -25349,14 +23711,12 @@ class ZoneSetLabelsRequest(proto.Message): The labels to set for this resource. """ - label_fingerprint = proto.Field(proto.STRING, number=178124825) - - labels = proto.MapField(proto.STRING, proto.STRING, number=231759871) + label_fingerprint = proto.Field(proto.STRING, number=178124825, optional=True,) + labels = proto.MapField(proto.STRING, proto.STRING, number=500195327,) class ZoneSetPolicyRequest(proto.Message): r""" - Attributes: bindings (Sequence[google.cloud.compute_v1.types.Binding]): Flatten Policy to create a backwacd @@ -25374,11 +23734,11 @@ class ZoneSetPolicyRequest(proto.Message): (like Projects) might reject them. """ - bindings = proto.RepeatedField(proto.MESSAGE, number=134816398, message="Binding",) - - etag = proto.Field(proto.STRING, number=3123477) - - policy = proto.Field(proto.MESSAGE, number=91071794, message="Policy",) + 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 AggregatedListAcceleratorTypesRequest(proto.Message): @@ -25457,19 +23817,13 @@ class AggregatedListAcceleratorTypesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 GetAcceleratorTypeRequest(proto.Message): @@ -25485,11 +23839,9 @@ class GetAcceleratorTypeRequest(proto.Message): The name of the zone for this request. """ - accelerator_type = proto.Field(proto.STRING, number=138031246) - - project = proto.Field(proto.STRING, number=227560217) - - zone = proto.Field(proto.STRING, number=3744684) + accelerator_type = proto.Field(proto.STRING, number=138031246,) + project = proto.Field(proto.STRING, number=227560217,) + zone = proto.Field(proto.STRING, number=3744684,) class ListAcceleratorTypesRequest(proto.Message): @@ -25559,19 +23911,13 @@ class ListAcceleratorTypesRequest(proto.Message): The name of the zone for this request. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) - - zone = proto.Field(proto.STRING, number=3744684) + 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,) + zone = proto.Field(proto.STRING, number=3744684,) class AggregatedListAddressesRequest(proto.Message): @@ -25650,19 +23996,13 @@ class AggregatedListAddressesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 DeleteAddressRequest(proto.Message): @@ -25694,13 +24034,10 @@ class DeleteAddressRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - address = proto.Field(proto.STRING, number=194485236) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + address = proto.Field(proto.STRING, number=462920692,) + 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 GetAddressRequest(proto.Message): @@ -25716,11 +24053,9 @@ class GetAddressRequest(proto.Message): Name of the region for this request. """ - address = proto.Field(proto.STRING, number=194485236) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) + address = proto.Field(proto.STRING, number=462920692,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) class InsertAddressRequest(proto.Message): @@ -25752,13 +24087,10 @@ class InsertAddressRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - address_resource = proto.Field(proto.MESSAGE, number=215452665, message="Address",) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + address_resource = proto.Field(proto.MESSAGE, number=483888121, message="Address",) + 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 ListAddressesRequest(proto.Message): @@ -25828,19 +24160,13 @@ class ListAddressesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class AggregatedListAutoscalersRequest(proto.Message): @@ -25919,19 +24245,13 @@ class AggregatedListAutoscalersRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 DeleteAutoscalerRequest(proto.Message): @@ -25963,13 +24283,10 @@ class DeleteAutoscalerRequest(proto.Message): Name of the zone for this request. """ - autoscaler = proto.Field(proto.STRING, number=248823511) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + autoscaler = proto.Field(proto.STRING, number=517258967,) + 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 GetAutoscalerRequest(proto.Message): @@ -25985,11 +24302,9 @@ class GetAutoscalerRequest(proto.Message): Name of the zone for this request. """ - autoscaler = proto.Field(proto.STRING, number=248823511) - - project = proto.Field(proto.STRING, number=227560217) - - zone = proto.Field(proto.STRING, number=3744684) + autoscaler = proto.Field(proto.STRING, number=517258967,) + project = proto.Field(proto.STRING, number=227560217,) + zone = proto.Field(proto.STRING, number=3744684,) class InsertAutoscalerRequest(proto.Message): @@ -26024,12 +24339,9 @@ class InsertAutoscalerRequest(proto.Message): autoscaler_resource = proto.Field( proto.MESSAGE, number=207616118, message="Autoscaler", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 ListAutoscalersRequest(proto.Message): @@ -26099,19 +24411,13 @@ class ListAutoscalersRequest(proto.Message): Name of the zone for this request. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) - - zone = proto.Field(proto.STRING, number=3744684) + 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,) + zone = proto.Field(proto.STRING, number=3744684,) class PatchAutoscalerRequest(proto.Message): @@ -26145,17 +24451,13 @@ class PatchAutoscalerRequest(proto.Message): Name of the zone for this request. """ - autoscaler = proto.Field(proto.STRING, number=248823511) - + autoscaler = proto.Field(proto.STRING, number=517258967, optional=True,) autoscaler_resource = proto.Field( proto.MESSAGE, number=207616118, message="Autoscaler", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 UpdateAutoscalerRequest(proto.Message): @@ -26189,17 +24491,13 @@ class UpdateAutoscalerRequest(proto.Message): Name of the zone for this request. """ - autoscaler = proto.Field(proto.STRING, number=248823511) - + autoscaler = proto.Field(proto.STRING, number=517258967, optional=True,) autoscaler_resource = proto.Field( proto.MESSAGE, number=207616118, message="Autoscaler", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 AddSignedUrlKeyBackendBucketRequest(proto.Message): @@ -26233,14 +24531,11 @@ class AddSignedUrlKeyBackendBucketRequest(proto.Message): The body resource for this request """ - backend_bucket = proto.Field(proto.STRING, number=91714037) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - + backend_bucket = proto.Field(proto.STRING, number=91714037,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) signed_url_key_resource = proto.Field( - proto.MESSAGE, number=189190529, message="SignedUrlKey", + proto.MESSAGE, number=457625985, message="SignedUrlKey", ) @@ -26271,11 +24566,9 @@ class DeleteBackendBucketRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - backend_bucket = proto.Field(proto.STRING, number=91714037) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + backend_bucket = proto.Field(proto.STRING, number=91714037,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class DeleteSignedUrlKeyBackendBucketRequest(proto.Message): @@ -26309,13 +24602,10 @@ class DeleteSignedUrlKeyBackendBucketRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - backend_bucket = proto.Field(proto.STRING, number=91714037) - - key_name = proto.Field(proto.STRING, number=232503403) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + backend_bucket = proto.Field(proto.STRING, number=91714037,) + key_name = proto.Field(proto.STRING, number=500938859,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class GetBackendBucketRequest(proto.Message): @@ -26329,9 +24619,8 @@ class GetBackendBucketRequest(proto.Message): Project ID for this request. """ - backend_bucket = proto.Field(proto.STRING, number=91714037) - - project = proto.Field(proto.STRING, number=227560217) + backend_bucket = proto.Field(proto.STRING, number=91714037,) + project = proto.Field(proto.STRING, number=227560217,) class InsertBackendBucketRequest(proto.Message): @@ -26362,12 +24651,10 @@ class InsertBackendBucketRequest(proto.Message): """ backend_bucket_resource = proto.Field( - proto.MESSAGE, number=112322328, message="BackendBucket", + proto.MESSAGE, number=380757784, message="BackendBucket", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class ListBackendBucketsRequest(proto.Message): @@ -26435,17 +24722,12 @@ class ListBackendBucketsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 PatchBackendBucketRequest(proto.Message): @@ -26477,15 +24759,12 @@ class PatchBackendBucketRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - backend_bucket = proto.Field(proto.STRING, number=91714037) - + backend_bucket = proto.Field(proto.STRING, number=91714037,) backend_bucket_resource = proto.Field( - proto.MESSAGE, number=112322328, message="BackendBucket", + proto.MESSAGE, number=380757784, message="BackendBucket", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class UpdateBackendBucketRequest(proto.Message): @@ -26517,15 +24796,12 @@ class UpdateBackendBucketRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - backend_bucket = proto.Field(proto.STRING, number=91714037) - + backend_bucket = proto.Field(proto.STRING, number=91714037,) backend_bucket_resource = proto.Field( - proto.MESSAGE, number=112322328, message="BackendBucket", + proto.MESSAGE, number=380757784, message="BackendBucket", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class AddSignedUrlKeyBackendServiceRequest(proto.Message): @@ -26559,14 +24835,11 @@ class AddSignedUrlKeyBackendServiceRequest(proto.Message): The body resource for this request """ - backend_service = proto.Field(proto.STRING, number=38510602) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - + backend_service = proto.Field(proto.STRING, number=306946058,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) signed_url_key_resource = proto.Field( - proto.MESSAGE, number=189190529, message="SignedUrlKey", + proto.MESSAGE, number=457625985, message="SignedUrlKey", ) @@ -26646,19 +24919,13 @@ class AggregatedListBackendServicesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 DeleteBackendServiceRequest(proto.Message): @@ -26689,11 +24956,9 @@ class DeleteBackendServiceRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - backend_service = proto.Field(proto.STRING, number=38510602) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + backend_service = proto.Field(proto.STRING, number=306946058,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class DeleteSignedUrlKeyBackendServiceRequest(proto.Message): @@ -26727,13 +24992,10 @@ class DeleteSignedUrlKeyBackendServiceRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - backend_service = proto.Field(proto.STRING, number=38510602) - - key_name = proto.Field(proto.STRING, number=232503403) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + backend_service = proto.Field(proto.STRING, number=306946058,) + key_name = proto.Field(proto.STRING, number=500938859,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class GetBackendServiceRequest(proto.Message): @@ -26748,9 +25010,8 @@ class GetBackendServiceRequest(proto.Message): Project ID for this request. """ - backend_service = proto.Field(proto.STRING, number=38510602) - - project = proto.Field(proto.STRING, number=227560217) + backend_service = proto.Field(proto.STRING, number=306946058,) + project = proto.Field(proto.STRING, number=227560217,) class GetHealthBackendServiceRequest(proto.Message): @@ -26767,10 +25028,8 @@ class GetHealthBackendServiceRequest(proto.Message): The body resource for this request """ - backend_service = proto.Field(proto.STRING, number=38510602) - - project = proto.Field(proto.STRING, number=227560217) - + backend_service = proto.Field(proto.STRING, number=306946058,) + project = proto.Field(proto.STRING, number=227560217,) resource_group_reference_resource = proto.Field( proto.MESSAGE, number=112951123, message="ResourceGroupReference", ) @@ -26804,12 +25063,10 @@ class InsertBackendServiceRequest(proto.Message): """ backend_service_resource = proto.Field( - proto.MESSAGE, number=79151267, message="BackendService", + proto.MESSAGE, number=347586723, message="BackendService", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class ListBackendServicesRequest(proto.Message): @@ -26877,17 +25134,12 @@ class ListBackendServicesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 PatchBackendServiceRequest(proto.Message): @@ -26919,15 +25171,12 @@ class PatchBackendServiceRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - backend_service = proto.Field(proto.STRING, number=38510602) - + backend_service = proto.Field(proto.STRING, number=306946058,) backend_service_resource = proto.Field( - proto.MESSAGE, number=79151267, message="BackendService", + proto.MESSAGE, number=347586723, message="BackendService", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class SetSecurityPolicyBackendServiceRequest(proto.Message): @@ -26961,12 +25210,9 @@ class SetSecurityPolicyBackendServiceRequest(proto.Message): The body resource for this request """ - backend_service = proto.Field(proto.STRING, number=38510602) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - + backend_service = proto.Field(proto.STRING, number=306946058,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) security_policy_reference_resource = proto.Field( proto.MESSAGE, number=204135024, message="SecurityPolicyReference", ) @@ -27002,15 +25248,12 @@ class UpdateBackendServiceRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - backend_service = proto.Field(proto.STRING, number=38510602) - + backend_service = proto.Field(proto.STRING, number=306946058,) backend_service_resource = proto.Field( - proto.MESSAGE, number=79151267, message="BackendService", + proto.MESSAGE, number=347586723, message="BackendService", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class AggregatedListDiskTypesRequest(proto.Message): @@ -27089,19 +25332,13 @@ class AggregatedListDiskTypesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 GetDiskTypeRequest(proto.Message): @@ -27117,11 +25354,9 @@ class GetDiskTypeRequest(proto.Message): The name of the zone for this request. """ - disk_type = proto.Field(proto.STRING, number=93009052) - - project = proto.Field(proto.STRING, number=227560217) - - zone = proto.Field(proto.STRING, number=3744684) + disk_type = proto.Field(proto.STRING, number=93009052,) + project = proto.Field(proto.STRING, number=227560217,) + zone = proto.Field(proto.STRING, number=3744684,) class ListDiskTypesRequest(proto.Message): @@ -27191,19 +25426,13 @@ class ListDiskTypesRequest(proto.Message): The name of the zone for this request. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) - - zone = proto.Field(proto.STRING, number=3744684) + 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,) + zone = proto.Field(proto.STRING, number=3744684,) class AddResourcePoliciesDiskRequest(proto.Message): @@ -27237,17 +25466,13 @@ class AddResourcePoliciesDiskRequest(proto.Message): The name of the zone for this request. """ - disk = proto.Field(proto.STRING, number=3083677) - + disk = proto.Field(proto.STRING, number=3083677,) disks_add_resource_policies_request_resource = proto.Field( - proto.MESSAGE, number=228047907, message="DisksAddResourcePoliciesRequest", + proto.MESSAGE, number=496483363, message="DisksAddResourcePoliciesRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 AggregatedListDisksRequest(proto.Message): @@ -27326,19 +25551,13 @@ class AggregatedListDisksRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 CreateSnapshotDiskRequest(proto.Message): @@ -27377,19 +25596,14 @@ class CreateSnapshotDiskRequest(proto.Message): The name of the zone for this request. """ - disk = proto.Field(proto.STRING, number=3083677) - - guest_flush = proto.Field(proto.BOOL, number=117115357) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - + disk = proto.Field(proto.STRING, number=3083677,) + guest_flush = proto.Field(proto.BOOL, number=385550813, optional=True,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) snapshot_resource = proto.Field( - proto.MESSAGE, number=212884521, message="Snapshot", + proto.MESSAGE, number=481319977, message="Snapshot", ) - - zone = proto.Field(proto.STRING, number=3744684) + zone = proto.Field(proto.STRING, number=3744684,) class DeleteDiskRequest(proto.Message): @@ -27421,13 +25635,10 @@ class DeleteDiskRequest(proto.Message): The name of the zone for this request. """ - disk = proto.Field(proto.STRING, number=3083677) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + disk = proto.Field(proto.STRING, number=3083677,) + 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 GetDiskRequest(proto.Message): @@ -27443,11 +25654,9 @@ class GetDiskRequest(proto.Message): The name of the zone for this request. """ - disk = proto.Field(proto.STRING, number=3083677) - - project = proto.Field(proto.STRING, number=227560217) - - zone = proto.Field(proto.STRING, number=3744684) + disk = proto.Field(proto.STRING, number=3083677,) + project = proto.Field(proto.STRING, number=227560217,) + zone = proto.Field(proto.STRING, number=3744684,) class GetIamPolicyDiskRequest(proto.Message): @@ -27465,13 +25674,12 @@ class GetIamPolicyDiskRequest(proto.Message): The name of the zone for this request. """ - options_requested_policy_version = proto.Field(proto.INT32, number=230784573) - - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) - - zone = proto.Field(proto.STRING, number=3744684) + options_requested_policy_version = proto.Field( + proto.INT32, number=499220029, optional=True, + ) + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) + zone = proto.Field(proto.STRING, number=3744684,) class InsertDiskRequest(proto.Message): @@ -27507,14 +25715,10 @@ class InsertDiskRequest(proto.Message): """ disk_resource = proto.Field(proto.MESSAGE, number=25880688, message="Disk",) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - source_image = proto.Field(proto.STRING, number=50443319) - - zone = proto.Field(proto.STRING, number=3744684) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + source_image = proto.Field(proto.STRING, number=50443319, optional=True,) + zone = proto.Field(proto.STRING, number=3744684,) class ListDisksRequest(proto.Message): @@ -27584,19 +25788,13 @@ class ListDisksRequest(proto.Message): The name of the zone for this request. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) - - zone = proto.Field(proto.STRING, number=3744684) + 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,) + zone = proto.Field(proto.STRING, number=3744684,) class RemoveResourcePoliciesDiskRequest(proto.Message): @@ -27630,17 +25828,13 @@ class RemoveResourcePoliciesDiskRequest(proto.Message): The name of the zone for this request. """ - disk = proto.Field(proto.STRING, number=3083677) - + disk = proto.Field(proto.STRING, number=3083677,) disks_remove_resource_policies_request_resource = proto.Field( - proto.MESSAGE, number=168321262, message="DisksRemoveResourcePoliciesRequest", + proto.MESSAGE, number=436756718, message="DisksRemoveResourcePoliciesRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 ResizeDiskRequest(proto.Message): @@ -27674,17 +25868,13 @@ class ResizeDiskRequest(proto.Message): The name of the zone for this request. """ - disk = proto.Field(proto.STRING, number=3083677) - + disk = proto.Field(proto.STRING, number=3083677,) disks_resize_request_resource = proto.Field( proto.MESSAGE, number=78307616, message="DisksResizeRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 SetIamPolicyDiskRequest(proto.Message): @@ -27702,14 +25892,11 @@ class SetIamPolicyDiskRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) - - zone = proto.Field(proto.STRING, number=3744684) - + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) + zone = proto.Field(proto.STRING, number=3744684,) zone_set_policy_request_resource = proto.Field( - proto.MESSAGE, number=113646651, message="ZoneSetPolicyRequest", + proto.MESSAGE, number=382082107, message="ZoneSetPolicyRequest", ) @@ -27744,16 +25931,12 @@ class SetLabelsDiskRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - resource = proto.Field(proto.STRING, number=195806222) - - zone = proto.Field(proto.STRING, number=3744684) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + resource = proto.Field(proto.STRING, number=195806222,) + zone = proto.Field(proto.STRING, number=3744684,) zone_set_labels_request_resource = proto.Field( - proto.MESSAGE, number=96515342, message="ZoneSetLabelsRequest", + proto.MESSAGE, number=364950798, message="ZoneSetLabelsRequest", ) @@ -27772,15 +25955,12 @@ class TestIamPermissionsDiskRequest(proto.Message): The name of the zone for this request. """ - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) - + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) test_permissions_request_resource = proto.Field( - proto.MESSAGE, number=170779302, message="TestPermissionsRequest", + proto.MESSAGE, number=439214758, message="TestPermissionsRequest", ) - - zone = proto.Field(proto.STRING, number=3744684) + zone = proto.Field(proto.STRING, number=3744684,) class DeleteExternalVpnGatewayRequest(proto.Message): @@ -27810,11 +25990,9 @@ class DeleteExternalVpnGatewayRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - external_vpn_gateway = proto.Field(proto.STRING, number=109898629) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + external_vpn_gateway = proto.Field(proto.STRING, number=109898629,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class GetExternalVpnGatewayRequest(proto.Message): @@ -27828,9 +26006,8 @@ class GetExternalVpnGatewayRequest(proto.Message): Project ID for this request. """ - external_vpn_gateway = proto.Field(proto.STRING, number=109898629) - - project = proto.Field(proto.STRING, number=227560217) + external_vpn_gateway = proto.Field(proto.STRING, number=109898629,) + project = proto.Field(proto.STRING, number=227560217,) class InsertExternalVpnGatewayRequest(proto.Message): @@ -27861,12 +26038,10 @@ class InsertExternalVpnGatewayRequest(proto.Message): """ external_vpn_gateway_resource = proto.Field( - proto.MESSAGE, number=218378120, message="ExternalVpnGateway", + proto.MESSAGE, number=486813576, message="ExternalVpnGateway", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class ListExternalVpnGatewaysRequest(proto.Message): @@ -27934,17 +26109,12 @@ class ListExternalVpnGatewaysRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 SetLabelsExternalVpnGatewayRequest(proto.Message): @@ -27961,12 +26131,10 @@ class SetLabelsExternalVpnGatewayRequest(proto.Message): """ global_set_labels_request_resource = proto.Field( - proto.MESSAGE, number=51481733, message="GlobalSetLabelsRequest", + proto.MESSAGE, number=319917189, message="GlobalSetLabelsRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) class TestIamPermissionsExternalVpnGatewayRequest(proto.Message): @@ -27982,12 +26150,10 @@ class TestIamPermissionsExternalVpnGatewayRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) - + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) test_permissions_request_resource = proto.Field( - proto.MESSAGE, number=170779302, message="TestPermissionsRequest", + proto.MESSAGE, number=439214758, message="TestPermissionsRequest", ) @@ -28018,11 +26184,9 @@ class DeleteFirewallRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - firewall = proto.Field(proto.STRING, number=242580736) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + 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): @@ -28036,9 +26200,8 @@ class GetFirewallRequest(proto.Message): Project ID for this request. """ - firewall = proto.Field(proto.STRING, number=242580736) - - project = proto.Field(proto.STRING, number=227560217) + firewall = proto.Field(proto.STRING, number=511016192,) + project = proto.Field(proto.STRING, number=227560217,) class InsertFirewallRequest(proto.Message): @@ -28069,10 +26232,8 @@ class InsertFirewallRequest(proto.Message): """ 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) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class ListFirewallsRequest(proto.Message): @@ -28140,17 +26301,12 @@ class ListFirewallsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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): @@ -28182,13 +26338,10 @@ class PatchFirewallRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - firewall = proto.Field(proto.STRING, number=242580736) - + 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) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class UpdateFirewallRequest(proto.Message): @@ -28220,13 +26373,10 @@ class UpdateFirewallRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - firewall = proto.Field(proto.STRING, number=242580736) - + 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) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class AggregatedListForwardingRulesRequest(proto.Message): @@ -28305,19 +26455,13 @@ class AggregatedListForwardingRulesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 DeleteForwardingRuleRequest(proto.Message): @@ -28350,13 +26494,10 @@ class DeleteForwardingRuleRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - forwarding_rule = proto.Field(proto.STRING, number=1528574) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + forwarding_rule = proto.Field(proto.STRING, number=269964030,) + 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 GetForwardingRuleRequest(proto.Message): @@ -28373,11 +26514,9 @@ class GetForwardingRuleRequest(proto.Message): Name of the region scoping this request. """ - forwarding_rule = proto.Field(proto.STRING, number=1528574) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) + forwarding_rule = proto.Field(proto.STRING, number=269964030,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) class InsertForwardingRuleRequest(proto.Message): @@ -28410,14 +26549,11 @@ class InsertForwardingRuleRequest(proto.Message): """ forwarding_rule_resource = proto.Field( - proto.MESSAGE, number=32776239, message="ForwardingRule", + proto.MESSAGE, number=301211695, message="ForwardingRule", ) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + 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 ListForwardingRulesRequest(proto.Message): @@ -28487,19 +26623,13 @@ class ListForwardingRulesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class PatchForwardingRuleRequest(proto.Message): @@ -28533,17 +26663,13 @@ class PatchForwardingRuleRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - forwarding_rule = proto.Field(proto.STRING, number=1528574) - + forwarding_rule = proto.Field(proto.STRING, number=269964030,) forwarding_rule_resource = proto.Field( - proto.MESSAGE, number=32776239, message="ForwardingRule", + proto.MESSAGE, number=301211695, message="ForwardingRule", ) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + 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 SetTargetForwardingRuleRequest(proto.Message): @@ -28578,16 +26704,12 @@ class SetTargetForwardingRuleRequest(proto.Message): The body resource for this request """ - forwarding_rule = proto.Field(proto.STRING, number=1528574) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - + forwarding_rule = proto.Field(proto.STRING, number=269964030,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) target_reference_resource = proto.Field( - proto.MESSAGE, number=255286256, message="TargetReference", + proto.MESSAGE, number=523721712, message="TargetReference", ) @@ -28618,11 +26740,9 @@ class DeleteGlobalAddressRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - address = proto.Field(proto.STRING, number=194485236) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + address = proto.Field(proto.STRING, number=462920692,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class GetGlobalAddressRequest(proto.Message): @@ -28636,9 +26756,8 @@ class GetGlobalAddressRequest(proto.Message): Project ID for this request. """ - address = proto.Field(proto.STRING, number=194485236) - - project = proto.Field(proto.STRING, number=227560217) + address = proto.Field(proto.STRING, number=462920692,) + project = proto.Field(proto.STRING, number=227560217,) class InsertGlobalAddressRequest(proto.Message): @@ -28668,11 +26787,9 @@ class InsertGlobalAddressRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - address_resource = proto.Field(proto.MESSAGE, number=215452665, message="Address",) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + address_resource = proto.Field(proto.MESSAGE, number=483888121, message="Address",) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class ListGlobalAddressesRequest(proto.Message): @@ -28740,17 +26857,12 @@ class ListGlobalAddressesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 DeleteGlobalForwardingRuleRequest(proto.Message): @@ -28781,11 +26893,9 @@ class DeleteGlobalForwardingRuleRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - forwarding_rule = proto.Field(proto.STRING, number=1528574) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + forwarding_rule = proto.Field(proto.STRING, number=269964030,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class GetGlobalForwardingRuleRequest(proto.Message): @@ -28800,9 +26910,8 @@ class GetGlobalForwardingRuleRequest(proto.Message): Project ID for this request. """ - forwarding_rule = proto.Field(proto.STRING, number=1528574) - - project = proto.Field(proto.STRING, number=227560217) + forwarding_rule = proto.Field(proto.STRING, number=269964030,) + project = proto.Field(proto.STRING, number=227560217,) class InsertGlobalForwardingRuleRequest(proto.Message): @@ -28833,12 +26942,10 @@ class InsertGlobalForwardingRuleRequest(proto.Message): """ forwarding_rule_resource = proto.Field( - proto.MESSAGE, number=32776239, message="ForwardingRule", + proto.MESSAGE, number=301211695, message="ForwardingRule", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class ListGlobalForwardingRulesRequest(proto.Message): @@ -28906,17 +27013,12 @@ class ListGlobalForwardingRulesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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): @@ -28948,15 +27050,12 @@ class PatchGlobalForwardingRuleRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - forwarding_rule = proto.Field(proto.STRING, number=1528574) - + forwarding_rule = proto.Field(proto.STRING, number=269964030,) forwarding_rule_resource = proto.Field( - proto.MESSAGE, number=32776239, message="ForwardingRule", + proto.MESSAGE, number=301211695, message="ForwardingRule", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class SetTargetGlobalForwardingRuleRequest(proto.Message): @@ -28989,14 +27088,11 @@ class SetTargetGlobalForwardingRuleRequest(proto.Message): The body resource for this request """ - forwarding_rule = proto.Field(proto.STRING, number=1528574) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - + forwarding_rule = proto.Field(proto.STRING, number=269964030,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) target_reference_resource = proto.Field( - proto.MESSAGE, number=255286256, message="TargetReference", + proto.MESSAGE, number=523721712, message="TargetReference", ) @@ -29037,12 +27133,9 @@ class AttachNetworkEndpointsGlobalNetworkEndpointGroupRequest(proto.Message): number=30691563, message="GlobalNetworkEndpointGroupsAttachEndpointsRequest", ) - - network_endpoint_group = proto.Field(proto.STRING, number=165471622) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + network_endpoint_group = proto.Field(proto.STRING, number=433907078,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class DeleteGlobalNetworkEndpointGroupRequest(proto.Message): @@ -29073,11 +27166,9 @@ class DeleteGlobalNetworkEndpointGroupRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - network_endpoint_group = proto.Field(proto.STRING, number=165471622) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + network_endpoint_group = proto.Field(proto.STRING, number=433907078,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class DetachNetworkEndpointsGlobalNetworkEndpointGroupRequest(proto.Message): @@ -29117,12 +27208,9 @@ class DetachNetworkEndpointsGlobalNetworkEndpointGroupRequest(proto.Message): number=8898269, message="GlobalNetworkEndpointGroupsDetachEndpointsRequest", ) - - network_endpoint_group = proto.Field(proto.STRING, number=165471622) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + network_endpoint_group = proto.Field(proto.STRING, number=433907078,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class GetGlobalNetworkEndpointGroupRequest(proto.Message): @@ -29137,9 +27225,8 @@ class GetGlobalNetworkEndpointGroupRequest(proto.Message): Project ID for this request. """ - network_endpoint_group = proto.Field(proto.STRING, number=165471622) - - project = proto.Field(proto.STRING, number=227560217) + network_endpoint_group = proto.Field(proto.STRING, number=433907078,) + project = proto.Field(proto.STRING, number=227560217,) class InsertGlobalNetworkEndpointGroupRequest(proto.Message): @@ -29170,12 +27257,10 @@ class InsertGlobalNetworkEndpointGroupRequest(proto.Message): """ network_endpoint_group_resource = proto.Field( - proto.MESSAGE, number=257353383, message="NetworkEndpointGroup", + proto.MESSAGE, number=525788839, message="NetworkEndpointGroup", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class ListGlobalNetworkEndpointGroupsRequest(proto.Message): @@ -29243,103 +27328,92 @@ class ListGlobalNetworkEndpointGroupsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) - - -class ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest(proto.Message): - r"""A request message for - GlobalNetworkEndpointGroups.ListNetworkEndpoints. 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``) - network_endpoint_group (str): - The name of the network endpoint group from - which you want to generate a list of included - network endpoints. It should comply with - RFC1035. - 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=67685240) + 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,) - max_results = proto.Field(proto.UINT32, number=54715419) - network_endpoint_group = proto.Field(proto.STRING, number=165471622) +class ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest(proto.Message): + r"""A request message for + GlobalNetworkEndpointGroups.ListNetworkEndpoints. See the method + description for details. - order_by = proto.Field(proto.STRING, number=160562920) + 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 ``<``. - page_token = proto.Field(proto.STRING, number=19994697) + For example, if you are filtering Compute Engine instances, + you can exclude instances named ``example-instance`` by + specifying ``name != example-instance``. - project = proto.Field(proto.STRING, number=227560217) + 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. - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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``) + network_endpoint_group (str): + The name of the network endpoint group from + which you want to generate a list of included + network endpoints. It should comply with + RFC1035. + 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,) + network_endpoint_group = proto.Field(proto.STRING, number=433907078,) + 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 AggregatedListGlobalOperationsRequest(proto.Message): @@ -29418,19 +27492,13 @@ class AggregatedListGlobalOperationsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 DeleteGlobalOperationRequest(proto.Message): @@ -29444,15 +27512,14 @@ class DeleteGlobalOperationRequest(proto.Message): Project ID for this request. """ - operation = proto.Field(proto.STRING, number=52090215) - - project = proto.Field(proto.STRING, number=227560217) + operation = proto.Field(proto.STRING, number=52090215,) + project = proto.Field(proto.STRING, number=227560217,) class DeleteGlobalOperationResponse(proto.Message): r"""A response message for GlobalOperations.Delete. See the method description for details. - """ + """ class GetGlobalOperationRequest(proto.Message): @@ -29466,9 +27533,8 @@ class GetGlobalOperationRequest(proto.Message): Project ID for this request. """ - operation = proto.Field(proto.STRING, number=52090215) - - project = proto.Field(proto.STRING, number=227560217) + operation = proto.Field(proto.STRING, number=52090215,) + project = proto.Field(proto.STRING, number=227560217,) class ListGlobalOperationsRequest(proto.Message): @@ -29536,17 +27602,12 @@ class ListGlobalOperationsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 WaitGlobalOperationRequest(proto.Message): @@ -29560,9 +27621,8 @@ class WaitGlobalOperationRequest(proto.Message): Project ID for this request. """ - operation = proto.Field(proto.STRING, number=52090215) - - project = proto.Field(proto.STRING, number=227560217) + operation = proto.Field(proto.STRING, number=52090215,) + project = proto.Field(proto.STRING, number=227560217,) class DeleteGlobalOrganizationOperationRequest(proto.Message): @@ -29576,15 +27636,14 @@ class DeleteGlobalOrganizationOperationRequest(proto.Message): Parent ID for this request. """ - operation = proto.Field(proto.STRING, number=52090215) - - parent_id = proto.Field(proto.STRING, number=191279312) + operation = proto.Field(proto.STRING, number=52090215,) + parent_id = proto.Field(proto.STRING, number=459714768, optional=True,) class DeleteGlobalOrganizationOperationResponse(proto.Message): r"""A response message for GlobalOrganizationOperations.Delete. See the method description for details. - """ + """ class GetGlobalOrganizationOperationRequest(proto.Message): @@ -29598,9 +27657,8 @@ class GetGlobalOrganizationOperationRequest(proto.Message): Parent ID for this request. """ - operation = proto.Field(proto.STRING, number=52090215) - - parent_id = proto.Field(proto.STRING, number=191279312) + operation = proto.Field(proto.STRING, number=52090215,) + parent_id = proto.Field(proto.STRING, number=459714768, optional=True,) class ListGlobalOrganizationOperationsRequest(proto.Message): @@ -29668,17 +27726,12 @@ class ListGlobalOrganizationOperationsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - parent_id = proto.Field(proto.STRING, number=191279312) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 AggregatedListHealthChecksRequest(proto.Message): @@ -29757,19 +27810,13 @@ class AggregatedListHealthChecksRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 DeleteHealthCheckRequest(proto.Message): @@ -29799,11 +27846,9 @@ class DeleteHealthCheckRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - health_check = proto.Field(proto.STRING, number=40441189) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + health_check = proto.Field(proto.STRING, number=308876645,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class GetHealthCheckRequest(proto.Message): @@ -29817,9 +27862,8 @@ class GetHealthCheckRequest(proto.Message): Project ID for this request. """ - health_check = proto.Field(proto.STRING, number=40441189) - - project = proto.Field(proto.STRING, number=227560217) + health_check = proto.Field(proto.STRING, number=308876645,) + project = proto.Field(proto.STRING, number=227560217,) class InsertHealthCheckRequest(proto.Message): @@ -29852,10 +27896,8 @@ class InsertHealthCheckRequest(proto.Message): health_check_resource = proto.Field( proto.MESSAGE, number=201925032, message="HealthCheck", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class ListHealthChecksRequest(proto.Message): @@ -29923,17 +27965,12 @@ class ListHealthChecksRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 PatchHealthCheckRequest(proto.Message): @@ -29965,15 +28002,12 @@ class PatchHealthCheckRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - health_check = proto.Field(proto.STRING, number=40441189) - + health_check = proto.Field(proto.STRING, number=308876645,) health_check_resource = proto.Field( proto.MESSAGE, number=201925032, message="HealthCheck", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class UpdateHealthCheckRequest(proto.Message): @@ -30005,15 +28039,12 @@ class UpdateHealthCheckRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - health_check = proto.Field(proto.STRING, number=40441189) - + health_check = proto.Field(proto.STRING, number=308876645,) health_check_resource = proto.Field( proto.MESSAGE, number=201925032, message="HealthCheck", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class DeleteImageRequest(proto.Message): @@ -30043,11 +28074,9 @@ class DeleteImageRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - image = proto.Field(proto.STRING, number=100313435) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + image = proto.Field(proto.STRING, number=100313435,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class DeprecateImageRequest(proto.Message): @@ -30080,14 +28109,11 @@ class DeprecateImageRequest(proto.Message): """ deprecation_status_resource = proto.Field( - proto.MESSAGE, number=64570608, message="DeprecationStatus", + proto.MESSAGE, number=333006064, message="DeprecationStatus", ) - - image = proto.Field(proto.STRING, number=100313435) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + image = proto.Field(proto.STRING, number=100313435,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class GetImageRequest(proto.Message): @@ -30101,9 +28127,8 @@ class GetImageRequest(proto.Message): Project ID for this request. """ - image = proto.Field(proto.STRING, number=100313435) - - project = proto.Field(proto.STRING, number=227560217) + image = proto.Field(proto.STRING, number=100313435,) + project = proto.Field(proto.STRING, number=227560217,) class GetFromFamilyImageRequest(proto.Message): @@ -30117,9 +28142,8 @@ class GetFromFamilyImageRequest(proto.Message): Project ID for this request. """ - family = proto.Field(proto.STRING, number=60316516) - - project = proto.Field(proto.STRING, number=227560217) + family = proto.Field(proto.STRING, number=328751972,) + project = proto.Field(proto.STRING, number=227560217,) class GetIamPolicyImageRequest(proto.Message): @@ -30135,11 +28159,11 @@ class GetIamPolicyImageRequest(proto.Message): Name or id of the resource for this request. """ - options_requested_policy_version = proto.Field(proto.INT32, number=230784573) - - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) + options_requested_policy_version = proto.Field( + proto.INT32, number=499220029, optional=True, + ) + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) class InsertImageRequest(proto.Message): @@ -30171,13 +28195,10 @@ class InsertImageRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - force_create = proto.Field(proto.BOOL, number=197723344) - - image_resource = proto.Field(proto.MESSAGE, number=102736498, message="Image",) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + force_create = proto.Field(proto.BOOL, number=197723344, optional=True,) + image_resource = proto.Field(proto.MESSAGE, number=371171954, message="Image",) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class ListImagesRequest(proto.Message): @@ -30245,17 +28266,12 @@ class ListImagesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 PatchImageRequest(proto.Message): @@ -30287,13 +28303,10 @@ class PatchImageRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - image = proto.Field(proto.STRING, number=100313435) - - image_resource = proto.Field(proto.MESSAGE, number=102736498, message="Image",) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + image = proto.Field(proto.STRING, number=100313435,) + image_resource = proto.Field(proto.MESSAGE, number=371171954, message="Image",) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class SetIamPolicyImageRequest(proto.Message): @@ -30310,12 +28323,10 @@ class SetIamPolicyImageRequest(proto.Message): """ global_set_policy_request_resource = proto.Field( - proto.MESSAGE, number=68613042, message="GlobalSetPolicyRequest", + proto.MESSAGE, number=337048498, message="GlobalSetPolicyRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) class SetLabelsImageRequest(proto.Message): @@ -30332,12 +28343,10 @@ class SetLabelsImageRequest(proto.Message): """ global_set_labels_request_resource = proto.Field( - proto.MESSAGE, number=51481733, message="GlobalSetLabelsRequest", + proto.MESSAGE, number=319917189, message="GlobalSetLabelsRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) class TestIamPermissionsImageRequest(proto.Message): @@ -30353,12 +28362,10 @@ class TestIamPermissionsImageRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) - + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) test_permissions_request_resource = proto.Field( - proto.MESSAGE, number=170779302, message="TestPermissionsRequest", + proto.MESSAGE, number=439214758, message="TestPermissionsRequest", ) @@ -30394,19 +28401,15 @@ class AbandonInstancesInstanceGroupManagerRequest(proto.Message): instance group is located. """ - instance_group_manager = proto.Field(proto.STRING, number=249363395) - + instance_group_manager = proto.Field(proto.STRING, number=249363395,) instance_group_managers_abandon_instances_request_resource = proto.Field( proto.MESSAGE, - number=52493560, + number=320929016, message="InstanceGroupManagersAbandonInstancesRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 AggregatedListInstanceGroupManagersRequest(proto.Message): @@ -30485,19 +28488,13 @@ class AggregatedListInstanceGroupManagersRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 ApplyUpdatesToInstancesInstanceGroupManagerRequest(proto.Message): @@ -30519,17 +28516,14 @@ class ApplyUpdatesToInstancesInstanceGroupManagerRequest(proto.Message): RFC1035. """ - instance_group_manager = proto.Field(proto.STRING, number=249363395) - + instance_group_manager = proto.Field(proto.STRING, number=249363395,) instance_group_managers_apply_updates_request_resource = proto.Field( proto.MESSAGE, number=259242835, message="InstanceGroupManagersApplyUpdatesRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - zone = proto.Field(proto.STRING, number=3744684) + project = proto.Field(proto.STRING, number=227560217,) + zone = proto.Field(proto.STRING, number=3744684,) class CreateInstancesInstanceGroupManagerRequest(proto.Message): @@ -30565,19 +28559,15 @@ class CreateInstancesInstanceGroupManagerRequest(proto.Message): RFC1035. """ - instance_group_manager = proto.Field(proto.STRING, number=249363395) - + instance_group_manager = proto.Field(proto.STRING, number=249363395,) instance_group_managers_create_instances_request_resource = proto.Field( proto.MESSAGE, number=24558867, message="InstanceGroupManagersCreateInstancesRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 DeleteInstanceGroupManagerRequest(proto.Message): @@ -30611,13 +28601,10 @@ class DeleteInstanceGroupManagerRequest(proto.Message): instance group is located. """ - instance_group_manager = proto.Field(proto.STRING, number=249363395) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + instance_group_manager = proto.Field(proto.STRING, number=249363395,) + 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 DeleteInstancesInstanceGroupManagerRequest(proto.Message): @@ -30652,19 +28639,15 @@ class DeleteInstancesInstanceGroupManagerRequest(proto.Message): instance group is located. """ - instance_group_manager = proto.Field(proto.STRING, number=249363395) - + instance_group_manager = proto.Field(proto.STRING, number=249363395,) instance_group_managers_delete_instances_request_resource = proto.Field( proto.MESSAGE, number=166421252, message="InstanceGroupManagersDeleteInstancesRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 DeletePerInstanceConfigsInstanceGroupManagerRequest(proto.Message): @@ -30686,17 +28669,14 @@ class DeletePerInstanceConfigsInstanceGroupManagerRequest(proto.Message): RFC1035. """ - instance_group_manager = proto.Field(proto.STRING, number=249363395) - + instance_group_manager = proto.Field(proto.STRING, number=249363395,) instance_group_managers_delete_per_instance_configs_req_resource = proto.Field( proto.MESSAGE, - number=93992224, + number=362427680, message="InstanceGroupManagersDeletePerInstanceConfigsReq", ) - - project = proto.Field(proto.STRING, number=227560217) - - zone = proto.Field(proto.STRING, number=3744684) + project = proto.Field(proto.STRING, number=227560217,) + zone = proto.Field(proto.STRING, number=3744684,) class GetInstanceGroupManagerRequest(proto.Message): @@ -30713,11 +28693,9 @@ class GetInstanceGroupManagerRequest(proto.Message): instance group is located. """ - instance_group_manager = proto.Field(proto.STRING, number=249363395) - - project = proto.Field(proto.STRING, number=227560217) - - zone = proto.Field(proto.STRING, number=3744684) + instance_group_manager = proto.Field(proto.STRING, number=249363395,) + project = proto.Field(proto.STRING, number=227560217,) + zone = proto.Field(proto.STRING, number=3744684,) class InsertInstanceGroupManagerRequest(proto.Message): @@ -30753,12 +28731,9 @@ class InsertInstanceGroupManagerRequest(proto.Message): instance_group_manager_resource = proto.Field( proto.MESSAGE, number=261063946, message="InstanceGroupManager", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 ListInstanceGroupManagersRequest(proto.Message): @@ -30829,19 +28804,13 @@ class ListInstanceGroupManagersRequest(proto.Message): instance group is located. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) - - zone = proto.Field(proto.STRING, number=3744684) + 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,) + zone = proto.Field(proto.STRING, number=3744684,) class ListErrorsInstanceGroupManagersRequest(proto.Message): @@ -30918,21 +28887,14 @@ class ListErrorsInstanceGroupManagersRequest(proto.Message): RFC1035. """ - filter = proto.Field(proto.STRING, number=67685240) - - instance_group_manager = proto.Field(proto.STRING, number=249363395) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) - - zone = proto.Field(proto.STRING, number=3744684) + filter = proto.Field(proto.STRING, number=336120696, optional=True,) + instance_group_manager = proto.Field(proto.STRING, number=249363395,) + 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,) + zone = proto.Field(proto.STRING, number=3744684,) class ListManagedInstancesInstanceGroupManagersRequest(proto.Message): @@ -31006,21 +28968,14 @@ class ListManagedInstancesInstanceGroupManagersRequest(proto.Message): instance group is located. """ - filter = proto.Field(proto.STRING, number=67685240) - - instance_group_manager = proto.Field(proto.STRING, number=249363395) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) - - zone = proto.Field(proto.STRING, number=3744684) + filter = proto.Field(proto.STRING, number=336120696, optional=True,) + instance_group_manager = proto.Field(proto.STRING, number=249363395,) + 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,) + zone = proto.Field(proto.STRING, number=3744684,) class ListPerInstanceConfigsInstanceGroupManagersRequest(proto.Message): @@ -31096,21 +29051,14 @@ class ListPerInstanceConfigsInstanceGroupManagersRequest(proto.Message): RFC1035. """ - filter = proto.Field(proto.STRING, number=67685240) - - instance_group_manager = proto.Field(proto.STRING, number=249363395) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) - - zone = proto.Field(proto.STRING, number=3744684) + filter = proto.Field(proto.STRING, number=336120696, optional=True,) + instance_group_manager = proto.Field(proto.STRING, number=249363395,) + 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,) + zone = proto.Field(proto.STRING, number=3744684,) class PatchInstanceGroupManagerRequest(proto.Message): @@ -31145,17 +29093,13 @@ class PatchInstanceGroupManagerRequest(proto.Message): the managed instance group. """ - instance_group_manager = proto.Field(proto.STRING, number=249363395) - + instance_group_manager = proto.Field(proto.STRING, number=249363395,) instance_group_manager_resource = proto.Field( proto.MESSAGE, number=261063946, message="InstanceGroupManager", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 PatchPerInstanceConfigsInstanceGroupManagerRequest(proto.Message): @@ -31193,19 +29137,15 @@ class PatchPerInstanceConfigsInstanceGroupManagerRequest(proto.Message): RFC1035. """ - instance_group_manager = proto.Field(proto.STRING, number=249363395) - + instance_group_manager = proto.Field(proto.STRING, number=249363395,) instance_group_managers_patch_per_instance_configs_req_resource = proto.Field( proto.MESSAGE, - number=88215039, + number=356650495, message="InstanceGroupManagersPatchPerInstanceConfigsReq", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 RecreateInstancesInstanceGroupManagerRequest(proto.Message): @@ -31241,19 +29181,15 @@ class RecreateInstancesInstanceGroupManagerRequest(proto.Message): instance group is located. """ - instance_group_manager = proto.Field(proto.STRING, number=249363395) - + instance_group_manager = proto.Field(proto.STRING, number=249363395,) instance_group_managers_recreate_instances_request_resource = proto.Field( proto.MESSAGE, number=21405952, message="InstanceGroupManagersRecreateInstancesRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 ResizeInstanceGroupManagerRequest(proto.Message): @@ -31292,15 +29228,11 @@ class ResizeInstanceGroupManagerRequest(proto.Message): instance group is located. """ - instance_group_manager = proto.Field(proto.STRING, number=249363395) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - size = proto.Field(proto.INT32, number=3530753) - - zone = proto.Field(proto.STRING, number=3744684) + instance_group_manager = proto.Field(proto.STRING, number=249363395,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + size = proto.Field(proto.INT32, number=3530753,) + zone = proto.Field(proto.STRING, number=3744684,) class SetInstanceTemplateInstanceGroupManagerRequest(proto.Message): @@ -31336,19 +29268,15 @@ class SetInstanceTemplateInstanceGroupManagerRequest(proto.Message): instance group is located. """ - instance_group_manager = proto.Field(proto.STRING, number=249363395) - + instance_group_manager = proto.Field(proto.STRING, number=249363395,) instance_group_managers_set_instance_template_request_resource = proto.Field( proto.MESSAGE, number=9809093, message="InstanceGroupManagersSetInstanceTemplateRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 SetTargetPoolsInstanceGroupManagerRequest(proto.Message): @@ -31383,19 +29311,15 @@ class SetTargetPoolsInstanceGroupManagerRequest(proto.Message): instance group is located. """ - instance_group_manager = proto.Field(proto.STRING, number=249363395) - + instance_group_manager = proto.Field(proto.STRING, number=249363395,) instance_group_managers_set_target_pools_request_resource = proto.Field( proto.MESSAGE, - number=12714760, + number=281150216, message="InstanceGroupManagersSetTargetPoolsRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 UpdatePerInstanceConfigsInstanceGroupManagerRequest(proto.Message): @@ -31433,19 +29357,15 @@ class UpdatePerInstanceConfigsInstanceGroupManagerRequest(proto.Message): RFC1035. """ - instance_group_manager = proto.Field(proto.STRING, number=249363395) - + instance_group_manager = proto.Field(proto.STRING, number=249363395,) instance_group_managers_update_per_instance_configs_req_resource = proto.Field( proto.MESSAGE, number=141402302, message="InstanceGroupManagersUpdatePerInstanceConfigsReq", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 AddInstancesInstanceGroupRequest(proto.Message): @@ -31481,17 +29401,13 @@ class AddInstancesInstanceGroupRequest(proto.Message): is located. """ - instance_group = proto.Field(proto.STRING, number=81095253) - + instance_group = proto.Field(proto.STRING, number=81095253,) instance_groups_add_instances_request_resource = proto.Field( - proto.MESSAGE, number=185277790, message="InstanceGroupsAddInstancesRequest", + proto.MESSAGE, number=453713246, message="InstanceGroupsAddInstancesRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 AggregatedListInstanceGroupsRequest(proto.Message): @@ -31570,19 +29486,13 @@ class AggregatedListInstanceGroupsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 DeleteInstanceGroupRequest(proto.Message): @@ -31615,13 +29525,10 @@ class DeleteInstanceGroupRequest(proto.Message): is located. """ - instance_group = proto.Field(proto.STRING, number=81095253) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + instance_group = proto.Field(proto.STRING, number=81095253,) + 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 GetInstanceGroupRequest(proto.Message): @@ -31638,11 +29545,9 @@ class GetInstanceGroupRequest(proto.Message): is located. """ - instance_group = proto.Field(proto.STRING, number=81095253) - - project = proto.Field(proto.STRING, number=227560217) - - zone = proto.Field(proto.STRING, number=3744684) + instance_group = proto.Field(proto.STRING, number=81095253,) + project = proto.Field(proto.STRING, number=227560217,) + zone = proto.Field(proto.STRING, number=3744684,) class InsertInstanceGroupRequest(proto.Message): @@ -31676,14 +29581,11 @@ class InsertInstanceGroupRequest(proto.Message): """ instance_group_resource = proto.Field( - proto.MESSAGE, number=18176696, message="InstanceGroup", + proto.MESSAGE, number=286612152, message="InstanceGroup", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 ListInstanceGroupsRequest(proto.Message): @@ -31754,19 +29656,13 @@ class ListInstanceGroupsRequest(proto.Message): is located. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) - - zone = proto.Field(proto.STRING, number=3744684) + 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,) + zone = proto.Field(proto.STRING, number=3744684,) class ListInstancesInstanceGroupsRequest(proto.Message): @@ -31842,25 +29738,17 @@ class ListInstancesInstanceGroupsRequest(proto.Message): is located. """ - filter = proto.Field(proto.STRING, number=67685240) - - instance_group = proto.Field(proto.STRING, number=81095253) - + filter = proto.Field(proto.STRING, number=336120696, optional=True,) + instance_group = proto.Field(proto.STRING, number=81095253,) instance_groups_list_instances_request_resource = proto.Field( - proto.MESSAGE, number=207819807, message="InstanceGroupsListInstancesRequest", + proto.MESSAGE, number=476255263, message="InstanceGroupsListInstancesRequest", ) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) - - zone = proto.Field(proto.STRING, number=3744684) + 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,) + zone = proto.Field(proto.STRING, number=3744684,) class RemoveInstancesInstanceGroupRequest(proto.Message): @@ -31896,17 +29784,13 @@ class RemoveInstancesInstanceGroupRequest(proto.Message): is located. """ - instance_group = proto.Field(proto.STRING, number=81095253) - + instance_group = proto.Field(proto.STRING, number=81095253,) instance_groups_remove_instances_request_resource = proto.Field( - proto.MESSAGE, number=122546361, message="InstanceGroupsRemoveInstancesRequest", + proto.MESSAGE, number=390981817, message="InstanceGroupsRemoveInstancesRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 SetNamedPortsInstanceGroupRequest(proto.Message): @@ -31942,17 +29826,13 @@ class SetNamedPortsInstanceGroupRequest(proto.Message): is located. """ - instance_group = proto.Field(proto.STRING, number=81095253) - + instance_group = proto.Field(proto.STRING, number=81095253,) instance_groups_set_named_ports_request_resource = proto.Field( - proto.MESSAGE, number=116716079, message="InstanceGroupsSetNamedPortsRequest", + proto.MESSAGE, number=385151535, message="InstanceGroupsSetNamedPortsRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 DeleteInstanceTemplateRequest(proto.Message): @@ -31982,11 +29862,9 @@ class DeleteInstanceTemplateRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - instance_template = proto.Field(proto.STRING, number=40812772) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + instance_template = proto.Field(proto.STRING, number=309248228,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class GetInstanceTemplateRequest(proto.Message): @@ -32000,9 +29878,8 @@ class GetInstanceTemplateRequest(proto.Message): Project ID for this request. """ - instance_template = proto.Field(proto.STRING, number=40812772) - - project = proto.Field(proto.STRING, number=227560217) + instance_template = proto.Field(proto.STRING, number=309248228,) + project = proto.Field(proto.STRING, number=227560217,) class GetIamPolicyInstanceTemplateRequest(proto.Message): @@ -32018,11 +29895,11 @@ class GetIamPolicyInstanceTemplateRequest(proto.Message): Name or id of the resource for this request. """ - options_requested_policy_version = proto.Field(proto.INT32, number=230784573) - - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) + options_requested_policy_version = proto.Field( + proto.INT32, number=499220029, optional=True, + ) + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) class InsertInstanceTemplateRequest(proto.Message): @@ -32055,10 +29932,8 @@ class InsertInstanceTemplateRequest(proto.Message): instance_template_resource = proto.Field( proto.MESSAGE, number=10679561, message="InstanceTemplate", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class ListInstanceTemplatesRequest(proto.Message): @@ -32126,17 +30001,12 @@ class ListInstanceTemplatesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 SetIamPolicyInstanceTemplateRequest(proto.Message): @@ -32153,12 +30023,10 @@ class SetIamPolicyInstanceTemplateRequest(proto.Message): """ global_set_policy_request_resource = proto.Field( - proto.MESSAGE, number=68613042, message="GlobalSetPolicyRequest", + proto.MESSAGE, number=337048498, message="GlobalSetPolicyRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) class TestIamPermissionsInstanceTemplateRequest(proto.Message): @@ -32174,12 +30042,10 @@ class TestIamPermissionsInstanceTemplateRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) - + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) test_permissions_request_resource = proto.Field( - proto.MESSAGE, number=170779302, message="TestPermissionsRequest", + proto.MESSAGE, number=439214758, message="TestPermissionsRequest", ) @@ -32218,18 +30084,13 @@ class AddAccessConfigInstanceRequest(proto.Message): """ access_config_resource = proto.Field( - proto.MESSAGE, number=119390096, message="AccessConfig", + proto.MESSAGE, number=387825552, message="AccessConfig", ) - - instance = proto.Field(proto.STRING, number=18257045) - - network_interface = proto.Field(proto.STRING, number=96952424) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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): @@ -32263,17 +30124,13 @@ class AddResourcePoliciesInstanceRequest(proto.Message): The name of the zone for this request. """ - instance = proto.Field(proto.STRING, number=18257045) - + instance = proto.Field(proto.STRING, number=18257045,) instances_add_resource_policies_request_resource = proto.Field( - proto.MESSAGE, number=220916507, message="InstancesAddResourcePoliciesRequest", + proto.MESSAGE, number=489351963, message="InstancesAddResourcePoliciesRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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): @@ -32352,19 +30209,13 @@ class AggregatedListInstancesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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): @@ -32406,16 +30257,11 @@ class AttachDiskInstanceRequest(proto.Message): attached_disk_resource = proto.Field( proto.MESSAGE, number=90605845, message="AttachedDisk", ) - - force_attach = proto.Field(proto.BOOL, number=142758425) - - instance = proto.Field(proto.STRING, number=18257045) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 DeleteInstanceRequest(proto.Message): @@ -32447,13 +30293,10 @@ class DeleteInstanceRequest(proto.Message): 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) - - zone = proto.Field(proto.STRING, number=3744684) + 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): @@ -32489,17 +30332,12 @@ class DeleteAccessConfigInstanceRequest(proto.Message): 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=96952424) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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): @@ -32535,15 +30373,11 @@ class DetachDiskInstanceRequest(proto.Message): 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) - - zone = proto.Field(proto.STRING, number=3744684) + 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): @@ -32559,11 +30393,9 @@ class GetInstanceRequest(proto.Message): 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) + instance = proto.Field(proto.STRING, number=18257045,) + project = proto.Field(proto.STRING, number=227560217,) + zone = proto.Field(proto.STRING, number=3744684,) class GetGuestAttributesInstanceRequest(proto.Message): @@ -32585,15 +30417,11 @@ class GetGuestAttributesInstanceRequest(proto.Message): The name of the zone for this request. """ - instance = proto.Field(proto.STRING, number=18257045) - - project = proto.Field(proto.STRING, number=227560217) - - query_path = proto.Field(proto.STRING, number=100155708) - - variable_key = proto.Field(proto.STRING, number=164364828) - - zone = proto.Field(proto.STRING, number=3744684) + instance = proto.Field(proto.STRING, number=18257045,) + project = proto.Field(proto.STRING, number=227560217,) + query_path = proto.Field(proto.STRING, number=368591164, optional=True,) + variable_key = proto.Field(proto.STRING, number=164364828, optional=True,) + zone = proto.Field(proto.STRING, number=3744684,) class GetIamPolicyInstanceRequest(proto.Message): @@ -32611,13 +30439,12 @@ class GetIamPolicyInstanceRequest(proto.Message): The name of the zone for this request. """ - options_requested_policy_version = proto.Field(proto.INT32, number=230784573) - - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) - - zone = proto.Field(proto.STRING, number=3744684) + options_requested_policy_version = proto.Field( + proto.INT32, number=499220029, optional=True, + ) + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) + zone = proto.Field(proto.STRING, number=3744684,) class GetScreenshotInstanceRequest(proto.Message): @@ -32633,11 +30460,9 @@ class GetScreenshotInstanceRequest(proto.Message): 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) + instance = proto.Field(proto.STRING, number=18257045,) + project = proto.Field(proto.STRING, number=227560217,) + zone = proto.Field(proto.STRING, number=3744684,) class GetSerialPortOutputInstanceRequest(proto.Message): @@ -32674,15 +30499,11 @@ class GetSerialPortOutputInstanceRequest(proto.Message): The name of the zone for this request. """ - instance = proto.Field(proto.STRING, number=18257045) - - port = proto.Field(proto.INT32, number=3446913) - - project = proto.Field(proto.STRING, number=227560217) - - start = proto.Field(proto.STRING, number=109757538) - - zone = proto.Field(proto.STRING, number=3744684) + instance = proto.Field(proto.STRING, number=18257045,) + port = proto.Field(proto.INT32, number=3446913, optional=True,) + project = proto.Field(proto.STRING, number=227560217,) + start = proto.Field(proto.STRING, number=109757538, optional=True,) + zone = proto.Field(proto.STRING, number=3744684,) class GetShieldedInstanceIdentityInstanceRequest(proto.Message): @@ -32699,11 +30520,9 @@ class GetShieldedInstanceIdentityInstanceRequest(proto.Message): 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) + instance = proto.Field(proto.STRING, number=18257045,) + project = proto.Field(proto.STRING, number=227560217,) + zone = proto.Field(proto.STRING, number=3744684,) class InsertInstanceRequest(proto.Message): @@ -32748,14 +30567,12 @@ class InsertInstanceRequest(proto.Message): instance_resource = proto.Field( proto.MESSAGE, number=215988344, message="Instance", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - source_instance_template = proto.Field(proto.STRING, number=63988160) - - zone = proto.Field(proto.STRING, number=3744684) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + source_instance_template = proto.Field( + proto.STRING, number=332423616, optional=True, + ) + zone = proto.Field(proto.STRING, number=3744684,) class ListInstancesRequest(proto.Message): @@ -32825,19 +30642,13 @@ class ListInstancesRequest(proto.Message): The name of the zone for this request. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) - - zone = proto.Field(proto.STRING, number=3744684) + 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,) + zone = proto.Field(proto.STRING, number=3744684,) class ListReferrersInstancesRequest(proto.Message): @@ -32911,21 +30722,14 @@ class ListReferrersInstancesRequest(proto.Message): The name of the zone for this request. """ - filter = proto.Field(proto.STRING, number=67685240) - - instance = proto.Field(proto.STRING, number=18257045) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) - - zone = proto.Field(proto.STRING, number=3744684) + filter = proto.Field(proto.STRING, number=336120696, optional=True,) + instance = proto.Field(proto.STRING, number=18257045,) + 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,) + zone = proto.Field(proto.STRING, number=3744684,) class RemoveResourcePoliciesInstanceRequest(proto.Message): @@ -32959,19 +30763,15 @@ class RemoveResourcePoliciesInstanceRequest(proto.Message): The name of the zone for this request. """ - instance = proto.Field(proto.STRING, number=18257045) - + instance = proto.Field(proto.STRING, number=18257045,) instances_remove_resource_policies_request_resource = proto.Field( proto.MESSAGE, number=49229558, message="InstancesRemoveResourcePoliciesRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 ResetInstanceRequest(proto.Message): @@ -33003,13 +30803,10 @@ class ResetInstanceRequest(proto.Message): 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) - - zone = proto.Field(proto.STRING, number=3744684) + 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 SetDeletionProtectionInstanceRequest(proto.Message): @@ -33044,15 +30841,11 @@ class SetDeletionProtectionInstanceRequest(proto.Message): The name of the zone for this request. """ - deletion_protection = proto.Field(proto.BOOL, number=189579242) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - resource = proto.Field(proto.STRING, number=195806222) - - zone = proto.Field(proto.STRING, number=3744684) + deletion_protection = proto.Field(proto.BOOL, number=458014698, optional=True,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + resource = proto.Field(proto.STRING, number=195806222,) + zone = proto.Field(proto.STRING, number=3744684,) class SetDiskAutoDeleteInstanceRequest(proto.Message): @@ -33091,17 +30884,12 @@ class SetDiskAutoDeleteInstanceRequest(proto.Message): The name of the zone for this request. """ - auto_delete = proto.Field(proto.BOOL, number=196325947) - - 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) - - zone = proto.Field(proto.STRING, number=3744684) + auto_delete = proto.Field(proto.BOOL, number=464761403,) + 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 SetIamPolicyInstanceRequest(proto.Message): @@ -33119,14 +30907,11 @@ class SetIamPolicyInstanceRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) - - zone = proto.Field(proto.STRING, number=3744684) - + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) + zone = proto.Field(proto.STRING, number=3744684,) zone_set_policy_request_resource = proto.Field( - proto.MESSAGE, number=113646651, message="ZoneSetPolicyRequest", + proto.MESSAGE, number=382082107, message="ZoneSetPolicyRequest", ) @@ -33161,17 +30946,13 @@ class SetLabelsInstanceRequest(proto.Message): The name of the zone for this request. """ - instance = proto.Field(proto.STRING, number=18257045) - + instance = proto.Field(proto.STRING, number=18257045,) instances_set_labels_request_resource = proto.Field( proto.MESSAGE, number=207749344, message="InstancesSetLabelsRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 SetMachineResourcesInstanceRequest(proto.Message): @@ -33205,17 +30986,13 @@ class SetMachineResourcesInstanceRequest(proto.Message): The name of the zone for this request. """ - instance = proto.Field(proto.STRING, number=18257045) - + instance = proto.Field(proto.STRING, number=18257045,) instances_set_machine_resources_request_resource = proto.Field( proto.MESSAGE, number=196286318, message="InstancesSetMachineResourcesRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 SetMachineTypeInstanceRequest(proto.Message): @@ -33249,17 +31026,13 @@ class SetMachineTypeInstanceRequest(proto.Message): The name of the zone for this request. """ - instance = proto.Field(proto.STRING, number=18257045) - + instance = proto.Field(proto.STRING, number=18257045,) instances_set_machine_type_request_resource = proto.Field( proto.MESSAGE, number=254157709, message="InstancesSetMachineTypeRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 SetMetadataInstanceRequest(proto.Message): @@ -33293,15 +31066,13 @@ class SetMetadataInstanceRequest(proto.Message): The name of the zone for this request. """ - instance = proto.Field(proto.STRING, number=18257045) - - metadata_resource = proto.Field(proto.MESSAGE, number=22650654, message="Metadata",) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + instance = proto.Field(proto.STRING, number=18257045,) + 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,) + zone = proto.Field(proto.STRING, number=3744684,) class SetMinCpuPlatformInstanceRequest(proto.Message): @@ -33335,17 +31106,13 @@ class SetMinCpuPlatformInstanceRequest(proto.Message): The name of the zone for this request. """ - instance = proto.Field(proto.STRING, number=18257045) - + instance = proto.Field(proto.STRING, number=18257045,) instances_set_min_cpu_platform_request_resource = proto.Field( proto.MESSAGE, number=148459368, message="InstancesSetMinCpuPlatformRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 SetSchedulingInstanceRequest(proto.Message): @@ -33379,17 +31146,13 @@ class SetSchedulingInstanceRequest(proto.Message): 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) - + instance = proto.Field(proto.STRING, number=18257045,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) scheduling_resource = proto.Field( - proto.MESSAGE, number=194745945, message="Scheduling", + proto.MESSAGE, number=463181401, message="Scheduling", ) - - zone = proto.Field(proto.STRING, number=3744684) + zone = proto.Field(proto.STRING, number=3744684,) class SetServiceAccountInstanceRequest(proto.Message): @@ -33423,17 +31186,13 @@ class SetServiceAccountInstanceRequest(proto.Message): The name of the zone for this request. """ - instance = proto.Field(proto.STRING, number=18257045) - + instance = proto.Field(proto.STRING, number=18257045,) instances_set_service_account_request_resource = proto.Field( - proto.MESSAGE, number=7114552, message="InstancesSetServiceAccountRequest", + proto.MESSAGE, number=275550008, message="InstancesSetServiceAccountRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 SetShieldedInstanceIntegrityPolicyInstanceRequest(proto.Message): @@ -33469,17 +31228,13 @@ class SetShieldedInstanceIntegrityPolicyInstanceRequest(proto.Message): 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) - + instance = proto.Field(proto.STRING, number=18257045,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) shielded_instance_integrity_policy_resource = proto.Field( - proto.MESSAGE, number=140734006, message="ShieldedInstanceIntegrityPolicy", + proto.MESSAGE, number=409169462, message="ShieldedInstanceIntegrityPolicy", ) - - zone = proto.Field(proto.STRING, number=3744684) + zone = proto.Field(proto.STRING, number=3744684,) class SetTagsInstanceRequest(proto.Message): @@ -33513,15 +31268,11 @@ class SetTagsInstanceRequest(proto.Message): 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) - - tags_resource = proto.Field(proto.MESSAGE, number=62999924, message="Tags",) - - zone = proto.Field(proto.STRING, number=3744684) + instance = proto.Field(proto.STRING, number=18257045,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + tags_resource = proto.Field(proto.MESSAGE, number=331435380, message="Tags",) + zone = proto.Field(proto.STRING, number=3744684,) class SimulateMaintenanceEventInstanceRequest(proto.Message): @@ -33537,11 +31288,9 @@ class SimulateMaintenanceEventInstanceRequest(proto.Message): 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) + instance = proto.Field(proto.STRING, number=18257045,) + project = proto.Field(proto.STRING, number=227560217,) + zone = proto.Field(proto.STRING, number=3744684,) class StartInstanceRequest(proto.Message): @@ -33573,13 +31322,10 @@ class StartInstanceRequest(proto.Message): 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) - - zone = proto.Field(proto.STRING, number=3744684) + 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 StartWithEncryptionKeyInstanceRequest(proto.Message): @@ -33613,19 +31359,15 @@ class StartWithEncryptionKeyInstanceRequest(proto.Message): The name of the zone for this request. """ - instance = proto.Field(proto.STRING, number=18257045) - + instance = proto.Field(proto.STRING, number=18257045,) instances_start_with_encryption_key_request_resource = proto.Field( proto.MESSAGE, - number=173277055, + number=441712511, message="InstancesStartWithEncryptionKeyRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 StopInstanceRequest(proto.Message): @@ -33657,13 +31399,10 @@ class StopInstanceRequest(proto.Message): 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) - - zone = proto.Field(proto.STRING, number=3744684) + 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 TestIamPermissionsInstanceRequest(proto.Message): @@ -33681,15 +31420,12 @@ class TestIamPermissionsInstanceRequest(proto.Message): The name of the zone for this request. """ - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) - + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) test_permissions_request_resource = proto.Field( - proto.MESSAGE, number=170779302, message="TestPermissionsRequest", + proto.MESSAGE, number=439214758, message="TestPermissionsRequest", ) - - zone = proto.Field(proto.STRING, number=3744684) + zone = proto.Field(proto.STRING, number=3744684,) class UpdateInstanceRequest(proto.Message): @@ -33736,114 +31472,101 @@ class UpdateInstanceRequest(proto.Message): The name of the zone for this request. """ - instance = proto.Field(proto.STRING, number=18257045) - - instance_resource = proto.Field( - proto.MESSAGE, number=215988344, message="Instance", - ) - - minimal_action = proto.Field(proto.STRING, number=2131604) - - most_disruptive_allowed_action = proto.Field(proto.STRING, number=66103053) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) - - -class UpdateAccessConfigInstanceRequest(proto.Message): - r"""A request message for Instances.UpdateAccessConfig. See the - method description for details. - - Attributes: - access_config_resource (google.cloud.compute_v1.types.AccessConfig): - The body resource for this request - instance (str): - The instance name for this request. - network_interface (str): - The name of the network interface where the - access config is attached. - 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_resource = proto.Field( - proto.MESSAGE, number=119390096, message="AccessConfig", - ) - - instance = proto.Field(proto.STRING, number=18257045) - - network_interface = proto.Field(proto.STRING, number=96952424) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) - - -class UpdateDisplayDeviceInstanceRequest(proto.Message): - r"""A request message for Instances.UpdateDisplayDevice. See the - method description for details. - - Attributes: - display_device_resource (google.cloud.compute_v1.types.DisplayDevice): - The body resource for this request - instance (str): - Name of the instance scoping 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. - """ - - display_device_resource = proto.Field( - proto.MESSAGE, number=21250650, message="DisplayDevice", + instance = proto.Field(proto.STRING, number=18257045,) + instance_resource = proto.Field( + proto.MESSAGE, number=215988344, message="Instance", ) + minimal_action = proto.Field(proto.STRING, number=270567060, optional=True,) + most_disruptive_allowed_action = proto.Field( + proto.STRING, number=66103053, optional=True, + ) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + zone = proto.Field(proto.STRING, number=3744684,) - instance = proto.Field(proto.STRING, number=18257045) - project = proto.Field(proto.STRING, number=227560217) +class UpdateAccessConfigInstanceRequest(proto.Message): + r"""A request message for Instances.UpdateAccessConfig. See the + method description for details. + + Attributes: + access_config_resource (google.cloud.compute_v1.types.AccessConfig): + The body resource for this request + instance (str): + The instance name for this request. + network_interface (str): + The name of the network interface where the + access config is attached. + 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. + """ - request_id = proto.Field(proto.STRING, number=37109963) + 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,) - zone = proto.Field(proto.STRING, number=3744684) + +class UpdateDisplayDeviceInstanceRequest(proto.Message): + r"""A request message for Instances.UpdateDisplayDevice. See the + method description for details. + + Attributes: + display_device_resource (google.cloud.compute_v1.types.DisplayDevice): + The body resource for this request + instance (str): + Name of the instance scoping 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. + """ + + display_device_resource = proto.Field( + proto.MESSAGE, number=289686106, message="DisplayDevice", + ) + 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 UpdateNetworkInterfaceInstanceRequest(proto.Message): @@ -33879,19 +31602,14 @@ class UpdateNetworkInterfaceInstanceRequest(proto.Message): The name of the zone for this request. """ - instance = proto.Field(proto.STRING, number=18257045) - - network_interface = proto.Field(proto.STRING, number=96952424) - + instance = proto.Field(proto.STRING, number=18257045,) + network_interface = proto.Field(proto.STRING, number=365387880,) network_interface_resource = proto.Field( - proto.MESSAGE, number=57379333, message="NetworkInterface", + proto.MESSAGE, number=325814789, message="NetworkInterface", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 UpdateShieldedInstanceConfigInstanceRequest(proto.Message): @@ -33926,17 +31644,13 @@ class UpdateShieldedInstanceConfigInstanceRequest(proto.Message): 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) - + instance = proto.Field(proto.STRING, number=18257045,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) shielded_instance_config_resource = proto.Field( - proto.MESSAGE, number=3623768, message="ShieldedInstanceConfig", + proto.MESSAGE, number=272059224, message="ShieldedInstanceConfig", ) - - zone = proto.Field(proto.STRING, number=3744684) + zone = proto.Field(proto.STRING, number=3744684,) class AggregatedListInterconnectAttachmentsRequest(proto.Message): @@ -34015,19 +31729,13 @@ class AggregatedListInterconnectAttachmentsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 DeleteInterconnectAttachmentRequest(proto.Message): @@ -34060,13 +31768,10 @@ class DeleteInterconnectAttachmentRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - interconnect_attachment = proto.Field(proto.STRING, number=39699828) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + interconnect_attachment = proto.Field(proto.STRING, number=308135284,) + 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 GetInterconnectAttachmentRequest(proto.Message): @@ -34083,11 +31788,9 @@ class GetInterconnectAttachmentRequest(proto.Message): Name of the region for this request. """ - interconnect_attachment = proto.Field(proto.STRING, number=39699828) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) + interconnect_attachment = proto.Field(proto.STRING, number=308135284,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) class InsertInterconnectAttachmentRequest(proto.Message): @@ -34124,14 +31827,10 @@ class InsertInterconnectAttachmentRequest(proto.Message): interconnect_attachment_resource = proto.Field( proto.MESSAGE, number=212341369, message="InterconnectAttachment", ) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - - validate_only = proto.Field(proto.BOOL, number=242744629) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + validate_only = proto.Field(proto.BOOL, number=242744629, optional=True,) class ListInterconnectAttachmentsRequest(proto.Message): @@ -34201,19 +31900,13 @@ class ListInterconnectAttachmentsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class PatchInterconnectAttachmentRequest(proto.Message): @@ -34247,17 +31940,13 @@ class PatchInterconnectAttachmentRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - interconnect_attachment = proto.Field(proto.STRING, number=39699828) - + interconnect_attachment = proto.Field(proto.STRING, number=308135284,) interconnect_attachment_resource = proto.Field( proto.MESSAGE, number=212341369, message="InterconnectAttachment", ) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + 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 GetInterconnectLocationRequest(proto.Message): @@ -34271,9 +31960,8 @@ class GetInterconnectLocationRequest(proto.Message): Project ID for this request. """ - interconnect_location = proto.Field(proto.STRING, number=223800390) - - project = proto.Field(proto.STRING, number=227560217) + interconnect_location = proto.Field(proto.STRING, number=492235846,) + project = proto.Field(proto.STRING, number=227560217,) class ListInterconnectLocationsRequest(proto.Message): @@ -34341,17 +32029,12 @@ class ListInterconnectLocationsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 DeleteInterconnectRequest(proto.Message): @@ -34381,11 +32064,9 @@ class DeleteInterconnectRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - interconnect = proto.Field(proto.STRING, number=224601230) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + interconnect = proto.Field(proto.STRING, number=224601230,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class GetInterconnectRequest(proto.Message): @@ -34399,9 +32080,8 @@ class GetInterconnectRequest(proto.Message): Project ID for this request. """ - interconnect = proto.Field(proto.STRING, number=224601230) - - project = proto.Field(proto.STRING, number=227560217) + interconnect = proto.Field(proto.STRING, number=224601230,) + project = proto.Field(proto.STRING, number=227560217,) class GetDiagnosticsInterconnectRequest(proto.Message): @@ -34415,9 +32095,8 @@ class GetDiagnosticsInterconnectRequest(proto.Message): Project ID for this request. """ - interconnect = proto.Field(proto.STRING, number=224601230) - - project = proto.Field(proto.STRING, number=227560217) + interconnect = proto.Field(proto.STRING, number=224601230,) + project = proto.Field(proto.STRING, number=227560217,) class InsertInterconnectRequest(proto.Message): @@ -34448,12 +32127,10 @@ class InsertInterconnectRequest(proto.Message): """ interconnect_resource = proto.Field( - proto.MESSAGE, number=129175711, message="Interconnect", + proto.MESSAGE, number=397611167, message="Interconnect", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class ListInterconnectsRequest(proto.Message): @@ -34521,17 +32198,12 @@ class ListInterconnectsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 PatchInterconnectRequest(proto.Message): @@ -34563,15 +32235,12 @@ class PatchInterconnectRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - interconnect = proto.Field(proto.STRING, number=224601230) - + interconnect = proto.Field(proto.STRING, number=224601230,) interconnect_resource = proto.Field( - proto.MESSAGE, number=129175711, message="Interconnect", + proto.MESSAGE, number=397611167, message="Interconnect", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class GetLicenseCodeRequest(proto.Message): @@ -34586,9 +32255,8 @@ class GetLicenseCodeRequest(proto.Message): Project ID for this request. """ - license_code = proto.Field(proto.STRING, number=1467179) - - project = proto.Field(proto.STRING, number=227560217) + license_code = proto.Field(proto.STRING, number=1467179,) + project = proto.Field(proto.STRING, number=227560217,) class TestIamPermissionsLicenseCodeRequest(proto.Message): @@ -34604,12 +32272,10 @@ class TestIamPermissionsLicenseCodeRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) - + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) test_permissions_request_resource = proto.Field( - proto.MESSAGE, number=170779302, message="TestPermissionsRequest", + proto.MESSAGE, number=439214758, message="TestPermissionsRequest", ) @@ -34640,11 +32306,9 @@ class DeleteLicenseRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - license_ = proto.Field(proto.STRING, number=166757441) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + license_ = proto.Field(proto.STRING, number=166757441,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class GetLicenseRequest(proto.Message): @@ -34658,9 +32322,8 @@ class GetLicenseRequest(proto.Message): Project ID for this request. """ - license_ = proto.Field(proto.STRING, number=166757441) - - project = proto.Field(proto.STRING, number=227560217) + license_ = proto.Field(proto.STRING, number=166757441,) + project = proto.Field(proto.STRING, number=227560217,) class GetIamPolicyLicenseRequest(proto.Message): @@ -34676,11 +32339,11 @@ class GetIamPolicyLicenseRequest(proto.Message): Name or id of the resource for this request. """ - options_requested_policy_version = proto.Field(proto.INT32, number=230784573) - - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) + options_requested_policy_version = proto.Field( + proto.INT32, number=499220029, optional=True, + ) + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) class InsertLicenseRequest(proto.Message): @@ -34710,11 +32373,9 @@ class InsertLicenseRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - license_resource = proto.Field(proto.MESSAGE, number=169519692, message="License",) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + license_resource = proto.Field(proto.MESSAGE, number=437955148, message="License",) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class ListLicensesRequest(proto.Message): @@ -34782,17 +32443,12 @@ class ListLicensesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 SetIamPolicyLicenseRequest(proto.Message): @@ -34809,12 +32465,10 @@ class SetIamPolicyLicenseRequest(proto.Message): """ global_set_policy_request_resource = proto.Field( - proto.MESSAGE, number=68613042, message="GlobalSetPolicyRequest", + proto.MESSAGE, number=337048498, message="GlobalSetPolicyRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) class TestIamPermissionsLicenseRequest(proto.Message): @@ -34830,12 +32484,10 @@ class TestIamPermissionsLicenseRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) - + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) test_permissions_request_resource = proto.Field( - proto.MESSAGE, number=170779302, message="TestPermissionsRequest", + proto.MESSAGE, number=439214758, message="TestPermissionsRequest", ) @@ -34915,19 +32567,13 @@ class AggregatedListMachineTypesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 GetMachineTypeRequest(proto.Message): @@ -34943,11 +32589,9 @@ class GetMachineTypeRequest(proto.Message): The name of the zone for this request. """ - machine_type = proto.Field(proto.STRING, number=227711026) - - project = proto.Field(proto.STRING, number=227560217) - - zone = proto.Field(proto.STRING, number=3744684) + machine_type = proto.Field(proto.STRING, number=227711026,) + project = proto.Field(proto.STRING, number=227560217,) + zone = proto.Field(proto.STRING, number=3744684,) class ListMachineTypesRequest(proto.Message): @@ -35017,19 +32661,13 @@ class ListMachineTypesRequest(proto.Message): The name of the zone for this request. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) - - zone = proto.Field(proto.STRING, number=3744684) + 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,) + zone = proto.Field(proto.STRING, number=3744684,) class AggregatedListNetworkEndpointGroupsRequest(proto.Message): @@ -35108,19 +32746,13 @@ class AggregatedListNetworkEndpointGroupsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 AttachNetworkEndpointsNetworkEndpointGroupRequest(proto.Message): @@ -35159,19 +32791,15 @@ class AttachNetworkEndpointsNetworkEndpointGroupRequest(proto.Message): RFC1035. """ - network_endpoint_group = proto.Field(proto.STRING, number=165471622) - + network_endpoint_group = proto.Field(proto.STRING, number=433907078,) network_endpoint_groups_attach_endpoints_request_resource = proto.Field( proto.MESSAGE, number=531079, message="NetworkEndpointGroupsAttachEndpointsRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 DeleteNetworkEndpointGroupRequest(proto.Message): @@ -35206,13 +32834,10 @@ class DeleteNetworkEndpointGroupRequest(proto.Message): RFC1035. """ - network_endpoint_group = proto.Field(proto.STRING, number=165471622) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + network_endpoint_group = proto.Field(proto.STRING, number=433907078,) + 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 DetachNetworkEndpointsNetworkEndpointGroupRequest(proto.Message): @@ -35251,19 +32876,15 @@ class DetachNetworkEndpointsNetworkEndpointGroupRequest(proto.Message): RFC1035. """ - network_endpoint_group = proto.Field(proto.STRING, number=165471622) - + network_endpoint_group = proto.Field(proto.STRING, number=433907078,) network_endpoint_groups_detach_endpoints_request_resource = proto.Field( proto.MESSAGE, - number=247173241, + number=515608697, message="NetworkEndpointGroupsDetachEndpointsRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 GetNetworkEndpointGroupRequest(proto.Message): @@ -35282,11 +32903,9 @@ class GetNetworkEndpointGroupRequest(proto.Message): RFC1035. """ - network_endpoint_group = proto.Field(proto.STRING, number=165471622) - - project = proto.Field(proto.STRING, number=227560217) - - zone = proto.Field(proto.STRING, number=3744684) + network_endpoint_group = proto.Field(proto.STRING, number=433907078,) + project = proto.Field(proto.STRING, number=227560217,) + zone = proto.Field(proto.STRING, number=3744684,) class InsertNetworkEndpointGroupRequest(proto.Message): @@ -35321,14 +32940,11 @@ class InsertNetworkEndpointGroupRequest(proto.Message): """ network_endpoint_group_resource = proto.Field( - proto.MESSAGE, number=257353383, message="NetworkEndpointGroup", + proto.MESSAGE, number=525788839, message="NetworkEndpointGroup", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 ListNetworkEndpointGroupsRequest(proto.Message): @@ -35400,19 +33016,13 @@ class ListNetworkEndpointGroupsRequest(proto.Message): RFC1035. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) - - zone = proto.Field(proto.STRING, number=3744684) + 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,) + zone = proto.Field(proto.STRING, number=3744684,) class ListNetworkEndpointsNetworkEndpointGroupsRequest(proto.Message): @@ -35492,27 +33102,19 @@ class ListNetworkEndpointsNetworkEndpointGroupsRequest(proto.Message): RFC1035. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - network_endpoint_group = proto.Field(proto.STRING, number=165471622) - + filter = proto.Field(proto.STRING, number=336120696, optional=True,) + max_results = proto.Field(proto.UINT32, number=54715419, optional=True,) + network_endpoint_group = proto.Field(proto.STRING, number=433907078,) network_endpoint_groups_list_endpoints_request_resource = proto.Field( proto.MESSAGE, number=59493390, message="NetworkEndpointGroupsListEndpointsRequest", ) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) - - zone = proto.Field(proto.STRING, number=3744684) + 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,) + zone = proto.Field(proto.STRING, number=3744684,) class TestIamPermissionsNetworkEndpointGroupRequest(proto.Message): @@ -35531,15 +33133,12 @@ class TestIamPermissionsNetworkEndpointGroupRequest(proto.Message): The name of the zone for this request. """ - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) - + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) test_permissions_request_resource = proto.Field( - proto.MESSAGE, number=170779302, message="TestPermissionsRequest", + proto.MESSAGE, number=439214758, message="TestPermissionsRequest", ) - - zone = proto.Field(proto.STRING, number=3744684) + zone = proto.Field(proto.STRING, number=3744684,) class AddPeeringNetworkRequest(proto.Message): @@ -35572,15 +33171,12 @@ class AddPeeringNetworkRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - network = proto.Field(proto.STRING, number=232872494) - + network = proto.Field(proto.STRING, number=232872494,) networks_add_peering_request_resource = proto.Field( - proto.MESSAGE, number=120374965, message="NetworksAddPeeringRequest", + proto.MESSAGE, number=388810421, message="NetworksAddPeeringRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class DeleteNetworkRequest(proto.Message): @@ -35610,11 +33206,9 @@ class DeleteNetworkRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - network = proto.Field(proto.STRING, number=232872494) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + network = proto.Field(proto.STRING, number=232872494,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class GetNetworkRequest(proto.Message): @@ -35628,9 +33222,8 @@ class GetNetworkRequest(proto.Message): Project ID for this request. """ - network = proto.Field(proto.STRING, number=232872494) - - project = proto.Field(proto.STRING, number=227560217) + network = proto.Field(proto.STRING, number=232872494,) + project = proto.Field(proto.STRING, number=227560217,) class InsertNetworkRequest(proto.Message): @@ -35661,10 +33254,8 @@ class InsertNetworkRequest(proto.Message): """ network_resource = proto.Field(proto.MESSAGE, number=122105599, message="Network",) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class ListNetworksRequest(proto.Message): @@ -35732,17 +33323,12 @@ class ListNetworksRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 ListPeeringRoutesNetworksRequest(proto.Message): @@ -35824,28 +33410,21 @@ class ListPeeringRoutesNetworksRequest(proto.Message): class Direction(proto.Enum): r"""The direction of the exchanged routes.""" UNDEFINED_DIRECTION = 0 - INCOMING = 70117414 - OUTGOING = 39002988 + INCOMING = 338552870 + OUTGOING = 307438444 - direction = proto.Field(proto.ENUM, number=111150975, enum=Direction,) - - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - network = proto.Field(proto.STRING, number=232872494) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - peering_name = proto.Field(proto.STRING, number=249571370) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + direction = proto.Field( + proto.ENUM, number=111150975, optional=True, enum=Direction, + ) + filter = proto.Field(proto.STRING, number=336120696, optional=True,) + max_results = proto.Field(proto.UINT32, number=54715419, optional=True,) + network = proto.Field(proto.STRING, number=232872494,) + order_by = proto.Field(proto.STRING, number=160562920, optional=True,) + page_token = proto.Field(proto.STRING, number=19994697, optional=True,) + peering_name = proto.Field(proto.STRING, number=249571370, optional=True,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292, optional=True,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class PatchNetworkRequest(proto.Message): @@ -35877,13 +33456,10 @@ class PatchNetworkRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - network = proto.Field(proto.STRING, number=232872494) - + network = proto.Field(proto.STRING, number=232872494,) network_resource = proto.Field(proto.MESSAGE, number=122105599, message="Network",) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class RemovePeeringNetworkRequest(proto.Message): @@ -35916,15 +33492,12 @@ class RemovePeeringNetworkRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - network = proto.Field(proto.STRING, number=232872494) - + network = proto.Field(proto.STRING, number=232872494,) networks_remove_peering_request_resource = proto.Field( - proto.MESSAGE, number=152727038, message="NetworksRemovePeeringRequest", + proto.MESSAGE, number=421162494, message="NetworksRemovePeeringRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class SwitchToCustomModeNetworkRequest(proto.Message): @@ -35954,11 +33527,9 @@ class SwitchToCustomModeNetworkRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - network = proto.Field(proto.STRING, number=232872494) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + network = proto.Field(proto.STRING, number=232872494,) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class UpdatePeeringNetworkRequest(proto.Message): @@ -35991,15 +33562,12 @@ class UpdatePeeringNetworkRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - network = proto.Field(proto.STRING, number=232872494) - + network = proto.Field(proto.STRING, number=232872494,) networks_update_peering_request_resource = proto.Field( proto.MESSAGE, number=224433497, message="NetworksUpdatePeeringRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class AddNodesNodeGroupRequest(proto.Message): @@ -36033,17 +33601,13 @@ class AddNodesNodeGroupRequest(proto.Message): The name of the zone for this request. """ - node_group = proto.Field(proto.STRING, number=201522690) - + node_group = proto.Field(proto.STRING, number=469958146,) node_groups_add_nodes_request_resource = proto.Field( proto.MESSAGE, number=131263288, message="NodeGroupsAddNodesRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 AggregatedListNodeGroupsRequest(proto.Message): @@ -36122,19 +33686,13 @@ class AggregatedListNodeGroupsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 DeleteNodeGroupRequest(proto.Message): @@ -36166,13 +33724,10 @@ class DeleteNodeGroupRequest(proto.Message): The name of the zone for this request. """ - node_group = proto.Field(proto.STRING, number=201522690) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + node_group = proto.Field(proto.STRING, number=469958146,) + 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 DeleteNodesNodeGroupRequest(proto.Message): @@ -36207,17 +33762,13 @@ class DeleteNodesNodeGroupRequest(proto.Message): The name of the zone for this request. """ - node_group = proto.Field(proto.STRING, number=201522690) - + node_group = proto.Field(proto.STRING, number=469958146,) node_groups_delete_nodes_request_resource = proto.Field( proto.MESSAGE, number=183298962, message="NodeGroupsDeleteNodesRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 GetNodeGroupRequest(proto.Message): @@ -36233,11 +33784,9 @@ class GetNodeGroupRequest(proto.Message): The name of the zone for this request. """ - node_group = proto.Field(proto.STRING, number=201522690) - - project = proto.Field(proto.STRING, number=227560217) - - zone = proto.Field(proto.STRING, number=3744684) + node_group = proto.Field(proto.STRING, number=469958146,) + project = proto.Field(proto.STRING, number=227560217,) + zone = proto.Field(proto.STRING, number=3744684,) class GetIamPolicyNodeGroupRequest(proto.Message): @@ -36255,13 +33804,12 @@ class GetIamPolicyNodeGroupRequest(proto.Message): The name of the zone for this request. """ - options_requested_policy_version = proto.Field(proto.INT32, number=230784573) - - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) - - zone = proto.Field(proto.STRING, number=3744684) + options_requested_policy_version = proto.Field( + proto.INT32, number=499220029, optional=True, + ) + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) + zone = proto.Field(proto.STRING, number=3744684,) class InsertNodeGroupRequest(proto.Message): @@ -36295,17 +33843,13 @@ class InsertNodeGroupRequest(proto.Message): The name of the zone for this request. """ - initial_node_count = proto.Field(proto.INT32, number=71951469) - + initial_node_count = proto.Field(proto.INT32, number=71951469,) node_group_resource = proto.Field( - proto.MESSAGE, number=236886443, message="NodeGroup", + proto.MESSAGE, number=505321899, message="NodeGroup", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 ListNodeGroupsRequest(proto.Message): @@ -36375,19 +33919,13 @@ class ListNodeGroupsRequest(proto.Message): The name of the zone for this request. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) - - zone = proto.Field(proto.STRING, number=3744684) + 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,) + zone = proto.Field(proto.STRING, number=3744684,) class ListNodesNodeGroupsRequest(proto.Message): @@ -36460,21 +33998,14 @@ class ListNodesNodeGroupsRequest(proto.Message): The name of the zone for this request. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - node_group = proto.Field(proto.STRING, number=201522690) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) - - zone = proto.Field(proto.STRING, number=3744684) + filter = proto.Field(proto.STRING, number=336120696, optional=True,) + max_results = proto.Field(proto.UINT32, number=54715419, optional=True,) + node_group = proto.Field(proto.STRING, number=469958146,) + 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,) + zone = proto.Field(proto.STRING, number=3744684,) class PatchNodeGroupRequest(proto.Message): @@ -36508,17 +34039,13 @@ class PatchNodeGroupRequest(proto.Message): The name of the zone for this request. """ - node_group = proto.Field(proto.STRING, number=201522690) - + node_group = proto.Field(proto.STRING, number=469958146,) node_group_resource = proto.Field( - proto.MESSAGE, number=236886443, message="NodeGroup", + proto.MESSAGE, number=505321899, message="NodeGroup", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 SetIamPolicyNodeGroupRequest(proto.Message): @@ -36536,14 +34063,11 @@ class SetIamPolicyNodeGroupRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) - - zone = proto.Field(proto.STRING, number=3744684) - + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) + zone = proto.Field(proto.STRING, number=3744684,) zone_set_policy_request_resource = proto.Field( - proto.MESSAGE, number=113646651, message="ZoneSetPolicyRequest", + proto.MESSAGE, number=382082107, message="ZoneSetPolicyRequest", ) @@ -36578,17 +34102,13 @@ class SetNodeTemplateNodeGroupRequest(proto.Message): The name of the zone for this request. """ - node_group = proto.Field(proto.STRING, number=201522690) - + node_group = proto.Field(proto.STRING, number=469958146,) node_groups_set_node_template_request_resource = proto.Field( proto.MESSAGE, number=117382321, message="NodeGroupsSetNodeTemplateRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - zone = proto.Field(proto.STRING, number=3744684) + 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 TestIamPermissionsNodeGroupRequest(proto.Message): @@ -36606,15 +34126,12 @@ class TestIamPermissionsNodeGroupRequest(proto.Message): The name of the zone for this request. """ - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) - + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) test_permissions_request_resource = proto.Field( - proto.MESSAGE, number=170779302, message="TestPermissionsRequest", + proto.MESSAGE, number=439214758, message="TestPermissionsRequest", ) - - zone = proto.Field(proto.STRING, number=3744684) + zone = proto.Field(proto.STRING, number=3744684,) class AggregatedListNodeTemplatesRequest(proto.Message): @@ -36693,19 +34210,13 @@ class AggregatedListNodeTemplatesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 DeleteNodeTemplateRequest(proto.Message): @@ -36737,13 +34248,10 @@ class DeleteNodeTemplateRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - node_template = proto.Field(proto.STRING, number=54718999) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + node_template = proto.Field(proto.STRING, number=323154455,) + 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 GetNodeTemplateRequest(proto.Message): @@ -36759,11 +34267,9 @@ class GetNodeTemplateRequest(proto.Message): The name of the region for this request. """ - node_template = proto.Field(proto.STRING, number=54718999) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) + node_template = proto.Field(proto.STRING, number=323154455,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) class GetIamPolicyNodeTemplateRequest(proto.Message): @@ -36781,13 +34287,12 @@ class GetIamPolicyNodeTemplateRequest(proto.Message): Name or id of the resource for this request. """ - options_requested_policy_version = proto.Field(proto.INT32, number=230784573) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - resource = proto.Field(proto.STRING, number=195806222) + options_requested_policy_version = proto.Field( + proto.INT32, number=499220029, optional=True, + ) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + resource = proto.Field(proto.STRING, number=195806222,) class InsertNodeTemplateRequest(proto.Message): @@ -36822,12 +34327,9 @@ class InsertNodeTemplateRequest(proto.Message): node_template_resource = proto.Field( proto.MESSAGE, number=127364406, message="NodeTemplate", ) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + 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 ListNodeTemplatesRequest(proto.Message): @@ -36897,19 +34399,13 @@ class ListNodeTemplatesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class SetIamPolicyNodeTemplateRequest(proto.Message): @@ -36927,15 +34423,12 @@ class SetIamPolicyNodeTemplateRequest(proto.Message): Name or id of the resource for this request. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) region_set_policy_request_resource = proto.Field( - proto.MESSAGE, number=8053635, message="RegionSetPolicyRequest", + proto.MESSAGE, number=276489091, message="RegionSetPolicyRequest", ) - - resource = proto.Field(proto.STRING, number=195806222) + resource = proto.Field(proto.STRING, number=195806222,) class TestIamPermissionsNodeTemplateRequest(proto.Message): @@ -36953,14 +34446,11 @@ class TestIamPermissionsNodeTemplateRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - resource = proto.Field(proto.STRING, number=195806222) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + resource = proto.Field(proto.STRING, number=195806222,) test_permissions_request_resource = proto.Field( - proto.MESSAGE, number=170779302, message="TestPermissionsRequest", + proto.MESSAGE, number=439214758, message="TestPermissionsRequest", ) @@ -37040,19 +34530,13 @@ class AggregatedListNodeTypesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 GetNodeTypeRequest(proto.Message): @@ -37068,11 +34552,9 @@ class GetNodeTypeRequest(proto.Message): The name of the zone for this request. """ - node_type = proto.Field(proto.STRING, number=197397335) - - project = proto.Field(proto.STRING, number=227560217) - - zone = proto.Field(proto.STRING, number=3744684) + node_type = proto.Field(proto.STRING, number=465832791,) + project = proto.Field(proto.STRING, number=227560217,) + zone = proto.Field(proto.STRING, number=3744684,) class ListNodeTypesRequest(proto.Message): @@ -37142,19 +34624,13 @@ class ListNodeTypesRequest(proto.Message): The name of the zone for this request. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) - - zone = proto.Field(proto.STRING, number=3744684) + 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,) + zone = proto.Field(proto.STRING, number=3744684,) class AggregatedListPacketMirroringsRequest(proto.Message): @@ -37233,19 +34709,13 @@ class AggregatedListPacketMirroringsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 DeletePacketMirroringRequest(proto.Message): @@ -37278,13 +34748,10 @@ class DeletePacketMirroringRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - packet_mirroring = proto.Field(proto.STRING, number=22305996) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + packet_mirroring = proto.Field(proto.STRING, number=22305996,) + 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 GetPacketMirroringRequest(proto.Message): @@ -37301,11 +34768,9 @@ class GetPacketMirroringRequest(proto.Message): Name of the region for this request. """ - packet_mirroring = proto.Field(proto.STRING, number=22305996) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) + packet_mirroring = proto.Field(proto.STRING, number=22305996,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) class InsertPacketMirroringRequest(proto.Message): @@ -37338,14 +34803,11 @@ class InsertPacketMirroringRequest(proto.Message): """ packet_mirroring_resource = proto.Field( - proto.MESSAGE, number=225066529, message="PacketMirroring", + proto.MESSAGE, number=493501985, message="PacketMirroring", ) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + 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 ListPacketMirroringsRequest(proto.Message): @@ -37415,19 +34877,13 @@ class ListPacketMirroringsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class PatchPacketMirroringRequest(proto.Message): @@ -37462,17 +34918,13 @@ class PatchPacketMirroringRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - packet_mirroring = proto.Field(proto.STRING, number=22305996) - + packet_mirroring = proto.Field(proto.STRING, number=22305996,) packet_mirroring_resource = proto.Field( - proto.MESSAGE, number=225066529, message="PacketMirroring", + proto.MESSAGE, number=493501985, message="PacketMirroring", ) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + 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 TestIamPermissionsPacketMirroringRequest(proto.Message): @@ -37490,14 +34942,11 @@ class TestIamPermissionsPacketMirroringRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - resource = proto.Field(proto.STRING, number=195806222) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + resource = proto.Field(proto.STRING, number=195806222,) test_permissions_request_resource = proto.Field( - proto.MESSAGE, number=170779302, message="TestPermissionsRequest", + proto.MESSAGE, number=439214758, message="TestPermissionsRequest", ) @@ -37526,9 +34975,8 @@ class DisableXpnHostProjectRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class DisableXpnResourceProjectRequest(proto.Message): @@ -37558,13 +35006,11 @@ class DisableXpnResourceProjectRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - project = proto.Field(proto.STRING, number=227560217) - + project = proto.Field(proto.STRING, number=227560217,) projects_disable_xpn_resource_request_resource = proto.Field( proto.MESSAGE, number=209136170, message="ProjectsDisableXpnResourceRequest", ) - - request_id = proto.Field(proto.STRING, number=37109963) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class EnableXpnHostProjectRequest(proto.Message): @@ -37592,9 +35038,8 @@ class EnableXpnHostProjectRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class EnableXpnResourceProjectRequest(proto.Message): @@ -37624,13 +35069,11 @@ class EnableXpnResourceProjectRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - project = proto.Field(proto.STRING, number=227560217) - + project = proto.Field(proto.STRING, number=227560217,) projects_enable_xpn_resource_request_resource = proto.Field( - proto.MESSAGE, number=153544751, message="ProjectsEnableXpnResourceRequest", + proto.MESSAGE, number=421980207, message="ProjectsEnableXpnResourceRequest", ) - - request_id = proto.Field(proto.STRING, number=37109963) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class GetProjectRequest(proto.Message): @@ -37642,7 +35085,7 @@ class GetProjectRequest(proto.Message): Project ID for this request. """ - project = proto.Field(proto.STRING, number=227560217) + project = proto.Field(proto.STRING, number=227560217,) class GetXpnHostProjectRequest(proto.Message): @@ -37654,7 +35097,7 @@ class GetXpnHostProjectRequest(proto.Message): Project ID for this request. """ - project = proto.Field(proto.STRING, number=227560217) + project = proto.Field(proto.STRING, number=227560217,) class GetXpnResourcesProjectsRequest(proto.Message): @@ -37722,17 +35165,12 @@ class GetXpnResourcesProjectsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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): @@ -37802,21 +35240,15 @@ class ListXpnHostsProjectsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - + 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=248762934) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class MoveDiskProjectRequest(proto.Message): @@ -37847,12 +35279,10 @@ class MoveDiskProjectRequest(proto.Message): """ disk_move_request_resource = proto.Field( - proto.MESSAGE, number=44573002, message="DiskMoveRequest", + proto.MESSAGE, number=313008458, message="DiskMoveRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class MoveInstanceProjectRequest(proto.Message): @@ -37883,12 +35313,10 @@ class MoveInstanceProjectRequest(proto.Message): """ instance_move_request_resource = proto.Field( - proto.MESSAGE, number=43228738, message="InstanceMoveRequest", + proto.MESSAGE, number=311664194, message="InstanceMoveRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class SetCommonInstanceMetadataProjectRequest(proto.Message): @@ -37918,11 +35346,11 @@ class SetCommonInstanceMetadataProjectRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - metadata_resource = proto.Field(proto.MESSAGE, number=22650654, message="Metadata",) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) + 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): @@ -37952,13 +35380,11 @@ class SetDefaultNetworkTierProjectRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - project = proto.Field(proto.STRING, number=227560217) - + 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) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class SetUsageExportBucketProjectRequest(proto.Message): @@ -37988,10 +35414,8 @@ class SetUsageExportBucketProjectRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - + 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", ) @@ -38026,13 +35450,10 @@ class DeleteRegionAutoscalerRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - autoscaler = proto.Field(proto.STRING, number=248823511) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + autoscaler = proto.Field(proto.STRING, number=517258967,) + 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 GetRegionAutoscalerRequest(proto.Message): @@ -38048,11 +35469,9 @@ class GetRegionAutoscalerRequest(proto.Message): Name of the region scoping this request. """ - autoscaler = proto.Field(proto.STRING, number=248823511) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) + autoscaler = proto.Field(proto.STRING, number=517258967,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) class InsertRegionAutoscalerRequest(proto.Message): @@ -38087,12 +35506,9 @@ class InsertRegionAutoscalerRequest(proto.Message): autoscaler_resource = proto.Field( proto.MESSAGE, number=207616118, message="Autoscaler", ) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + 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 ListRegionAutoscalersRequest(proto.Message): @@ -38162,19 +35578,13 @@ class ListRegionAutoscalersRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class PatchRegionAutoscalerRequest(proto.Message): @@ -38208,17 +35618,13 @@ class PatchRegionAutoscalerRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - autoscaler = proto.Field(proto.STRING, number=248823511) - + autoscaler = proto.Field(proto.STRING, number=517258967, optional=True,) autoscaler_resource = proto.Field( proto.MESSAGE, number=207616118, message="Autoscaler", ) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + 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 UpdateRegionAutoscalerRequest(proto.Message): @@ -38252,17 +35658,13 @@ class UpdateRegionAutoscalerRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - autoscaler = proto.Field(proto.STRING, number=248823511) - + autoscaler = proto.Field(proto.STRING, number=517258967, optional=True,) autoscaler_resource = proto.Field( proto.MESSAGE, number=207616118, message="Autoscaler", ) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + 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 DeleteRegionBackendServiceRequest(proto.Message): @@ -38295,13 +35697,10 @@ class DeleteRegionBackendServiceRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - backend_service = proto.Field(proto.STRING, number=38510602) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + backend_service = proto.Field(proto.STRING, number=306946058,) + 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 GetRegionBackendServiceRequest(proto.Message): @@ -38318,11 +35717,9 @@ class GetRegionBackendServiceRequest(proto.Message): Name of the region scoping this request. """ - backend_service = proto.Field(proto.STRING, number=38510602) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) + backend_service = proto.Field(proto.STRING, number=306946058,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) class GetHealthRegionBackendServiceRequest(proto.Message): @@ -38341,12 +35738,9 @@ class GetHealthRegionBackendServiceRequest(proto.Message): The body resource for this request """ - backend_service = proto.Field(proto.STRING, number=38510602) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - + backend_service = proto.Field(proto.STRING, number=306946058,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) resource_group_reference_resource = proto.Field( proto.MESSAGE, number=112951123, message="ResourceGroupReference", ) @@ -38382,14 +35776,11 @@ class InsertRegionBackendServiceRequest(proto.Message): """ backend_service_resource = proto.Field( - proto.MESSAGE, number=79151267, message="BackendService", + proto.MESSAGE, number=347586723, message="BackendService", ) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + 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 ListRegionBackendServicesRequest(proto.Message): @@ -38459,19 +35850,13 @@ class ListRegionBackendServicesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class PatchRegionBackendServiceRequest(proto.Message): @@ -38505,17 +35890,13 @@ class PatchRegionBackendServiceRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - backend_service = proto.Field(proto.STRING, number=38510602) - + backend_service = proto.Field(proto.STRING, number=306946058,) backend_service_resource = proto.Field( - proto.MESSAGE, number=79151267, message="BackendService", + proto.MESSAGE, number=347586723, message="BackendService", ) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + 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 UpdateRegionBackendServiceRequest(proto.Message): @@ -38550,17 +35931,13 @@ class UpdateRegionBackendServiceRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - backend_service = proto.Field(proto.STRING, number=38510602) - + backend_service = proto.Field(proto.STRING, number=306946058,) backend_service_resource = proto.Field( - proto.MESSAGE, number=79151267, message="BackendService", + proto.MESSAGE, number=347586723, message="BackendService", ) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + 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 AggregatedListRegionCommitmentsRequest(proto.Message): @@ -38639,19 +36016,13 @@ class AggregatedListRegionCommitmentsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 GetRegionCommitmentRequest(proto.Message): @@ -38667,11 +36038,9 @@ class GetRegionCommitmentRequest(proto.Message): Name of the region for this request. """ - commitment = proto.Field(proto.STRING, number=213699349) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) + commitment = proto.Field(proto.STRING, number=482134805,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) class InsertRegionCommitmentRequest(proto.Message): @@ -38706,12 +36075,9 @@ class InsertRegionCommitmentRequest(proto.Message): commitment_resource = proto.Field( proto.MESSAGE, number=244240888, message="Commitment", ) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + 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 ListRegionCommitmentsRequest(proto.Message): @@ -38781,19 +36147,13 @@ class ListRegionCommitmentsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class GetRegionDiskTypeRequest(proto.Message): @@ -38809,11 +36169,9 @@ class GetRegionDiskTypeRequest(proto.Message): The name of the region for this request. """ - disk_type = proto.Field(proto.STRING, number=93009052) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) + disk_type = proto.Field(proto.STRING, number=93009052,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) class ListRegionDiskTypesRequest(proto.Message): @@ -38883,19 +36241,13 @@ class ListRegionDiskTypesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class AddResourcePoliciesRegionDiskRequest(proto.Message): @@ -38929,17 +36281,15 @@ class AddResourcePoliciesRegionDiskRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - disk = proto.Field(proto.STRING, number=3083677) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - + disk = proto.Field(proto.STRING, number=3083677,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) region_disks_add_resource_policies_request_resource = proto.Field( - proto.MESSAGE, number=15761294, message="RegionDisksAddResourcePoliciesRequest", + proto.MESSAGE, + number=284196750, + message="RegionDisksAddResourcePoliciesRequest", ) - - request_id = proto.Field(proto.STRING, number=37109963) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class CreateSnapshotRegionDiskRequest(proto.Message): @@ -38974,16 +36324,12 @@ class CreateSnapshotRegionDiskRequest(proto.Message): The body resource for this request """ - disk = proto.Field(proto.STRING, number=3083677) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - + disk = proto.Field(proto.STRING, number=3083677,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) snapshot_resource = proto.Field( - proto.MESSAGE, number=212884521, message="Snapshot", + proto.MESSAGE, number=481319977, message="Snapshot", ) @@ -39017,13 +36363,10 @@ class DeleteRegionDiskRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - disk = proto.Field(proto.STRING, number=3083677) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + disk = proto.Field(proto.STRING, number=3083677,) + 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 GetRegionDiskRequest(proto.Message): @@ -39040,11 +36383,9 @@ class GetRegionDiskRequest(proto.Message): Name of the region for this request. """ - disk = proto.Field(proto.STRING, number=3083677) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) + disk = proto.Field(proto.STRING, number=3083677,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) class GetIamPolicyRegionDiskRequest(proto.Message): @@ -39062,13 +36403,12 @@ class GetIamPolicyRegionDiskRequest(proto.Message): Name or id of the resource for this request. """ - options_requested_policy_version = proto.Field(proto.INT32, number=230784573) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - resource = proto.Field(proto.STRING, number=195806222) + options_requested_policy_version = proto.Field( + proto.INT32, number=499220029, optional=True, + ) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + resource = proto.Field(proto.STRING, number=195806222,) class InsertRegionDiskRequest(proto.Message): @@ -39104,14 +36444,10 @@ class InsertRegionDiskRequest(proto.Message): """ disk_resource = proto.Field(proto.MESSAGE, number=25880688, message="Disk",) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - - source_image = proto.Field(proto.STRING, number=50443319) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + source_image = proto.Field(proto.STRING, number=50443319, optional=True,) class ListRegionDisksRequest(proto.Message): @@ -39181,19 +36517,13 @@ class ListRegionDisksRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class RemoveResourcePoliciesRegionDiskRequest(proto.Message): @@ -39227,19 +36557,15 @@ class RemoveResourcePoliciesRegionDiskRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - disk = proto.Field(proto.STRING, number=3083677) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - + disk = proto.Field(proto.STRING, number=3083677,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) region_disks_remove_resource_policies_request_resource = proto.Field( proto.MESSAGE, number=8741283, message="RegionDisksRemoveResourcePoliciesRequest", ) - - request_id = proto.Field(proto.STRING, number=37109963) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class ResizeRegionDiskRequest(proto.Message): @@ -39273,17 +36599,13 @@ class ResizeRegionDiskRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - disk = proto.Field(proto.STRING, number=3083677) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - + disk = proto.Field(proto.STRING, number=3083677,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) region_disks_resize_request_resource = proto.Field( - proto.MESSAGE, number=178197781, message="RegionDisksResizeRequest", + proto.MESSAGE, number=446633237, message="RegionDisksResizeRequest", ) - - request_id = proto.Field(proto.STRING, number=37109963) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class SetIamPolicyRegionDiskRequest(proto.Message): @@ -39301,15 +36623,12 @@ class SetIamPolicyRegionDiskRequest(proto.Message): Name or id of the resource for this request. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) region_set_policy_request_resource = proto.Field( - proto.MESSAGE, number=8053635, message="RegionSetPolicyRequest", + proto.MESSAGE, number=276489091, message="RegionSetPolicyRequest", ) - - resource = proto.Field(proto.STRING, number=195806222) + resource = proto.Field(proto.STRING, number=195806222,) class SetLabelsRegionDiskRequest(proto.Message): @@ -39343,17 +36662,13 @@ class SetLabelsRegionDiskRequest(proto.Message): Name or id of the resource for this request. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - + 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) - - resource = proto.Field(proto.STRING, number=195806222) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + resource = proto.Field(proto.STRING, number=195806222,) class TestIamPermissionsRegionDiskRequest(proto.Message): @@ -39371,14 +36686,11 @@ class TestIamPermissionsRegionDiskRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - resource = proto.Field(proto.STRING, number=195806222) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + resource = proto.Field(proto.STRING, number=195806222,) test_permissions_request_resource = proto.Field( - proto.MESSAGE, number=170779302, message="TestPermissionsRequest", + proto.MESSAGE, number=439214758, message="TestPermissionsRequest", ) @@ -39413,13 +36725,10 @@ class DeleteRegionHealthCheckServiceRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - health_check_service = proto.Field(proto.STRING, number=139939291) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + health_check_service = proto.Field(proto.STRING, number=408374747,) + 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 GetRegionHealthCheckServiceRequest(proto.Message): @@ -39437,11 +36746,9 @@ class GetRegionHealthCheckServiceRequest(proto.Message): Name of the region scoping this request. """ - health_check_service = proto.Field(proto.STRING, number=139939291) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) + health_check_service = proto.Field(proto.STRING, number=408374747,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) class InsertRegionHealthCheckServiceRequest(proto.Message): @@ -39474,14 +36781,11 @@ class InsertRegionHealthCheckServiceRequest(proto.Message): """ health_check_service_resource = proto.Field( - proto.MESSAGE, number=208932338, message="HealthCheckService", + proto.MESSAGE, number=477367794, message="HealthCheckService", ) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + 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 ListRegionHealthCheckServicesRequest(proto.Message): @@ -39551,19 +36855,13 @@ class ListRegionHealthCheckServicesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class PatchRegionHealthCheckServiceRequest(proto.Message): @@ -39599,17 +36897,13 @@ class PatchRegionHealthCheckServiceRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - health_check_service = proto.Field(proto.STRING, number=139939291) - + health_check_service = proto.Field(proto.STRING, number=408374747,) health_check_service_resource = proto.Field( - proto.MESSAGE, number=208932338, message="HealthCheckService", + proto.MESSAGE, number=477367794, message="HealthCheckService", ) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + 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 DeleteRegionHealthCheckRequest(proto.Message): @@ -39641,13 +36935,10 @@ class DeleteRegionHealthCheckRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - health_check = proto.Field(proto.STRING, number=40441189) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + health_check = proto.Field(proto.STRING, number=308876645,) + 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 GetRegionHealthCheckRequest(proto.Message): @@ -39663,11 +36954,9 @@ class GetRegionHealthCheckRequest(proto.Message): Name of the region scoping this request. """ - health_check = proto.Field(proto.STRING, number=40441189) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) + health_check = proto.Field(proto.STRING, number=308876645,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) class InsertRegionHealthCheckRequest(proto.Message): @@ -39702,12 +36991,9 @@ class InsertRegionHealthCheckRequest(proto.Message): health_check_resource = proto.Field( proto.MESSAGE, number=201925032, message="HealthCheck", ) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + 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 ListRegionHealthChecksRequest(proto.Message): @@ -39777,19 +37063,13 @@ class ListRegionHealthChecksRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class PatchRegionHealthCheckRequest(proto.Message): @@ -39823,17 +37103,13 @@ class PatchRegionHealthCheckRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - health_check = proto.Field(proto.STRING, number=40441189) - + health_check = proto.Field(proto.STRING, number=308876645,) health_check_resource = proto.Field( proto.MESSAGE, number=201925032, message="HealthCheck", ) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + 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 UpdateRegionHealthCheckRequest(proto.Message): @@ -39867,17 +37143,13 @@ class UpdateRegionHealthCheckRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - health_check = proto.Field(proto.STRING, number=40441189) - + health_check = proto.Field(proto.STRING, number=308876645,) health_check_resource = proto.Field( proto.MESSAGE, number=201925032, message="HealthCheck", ) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + 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 AbandonInstancesRegionInstanceGroupManagerRequest(proto.Message): @@ -39912,19 +37184,15 @@ class AbandonInstancesRegionInstanceGroupManagerRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - instance_group_manager = proto.Field(proto.STRING, number=249363395) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - + instance_group_manager = proto.Field(proto.STRING, number=249363395,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) region_instance_group_managers_abandon_instances_request_resource = proto.Field( proto.MESSAGE, - number=220064035, + number=488499491, message="RegionInstanceGroupManagersAbandonInstancesRequest", ) - - request_id = proto.Field(proto.STRING, number=37109963) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class ApplyUpdatesToInstancesRegionInstanceGroupManagerRequest(proto.Message): @@ -39945,12 +37213,9 @@ class ApplyUpdatesToInstancesRegionInstanceGroupManagerRequest(proto.Message): The body resource for this request """ - instance_group_manager = proto.Field(proto.STRING, number=249363395) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - + instance_group_manager = proto.Field(proto.STRING, number=249363395,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) region_instance_group_managers_apply_updates_request_resource = proto.Field( proto.MESSAGE, number=76248318, @@ -39992,19 +37257,15 @@ class CreateInstancesRegionInstanceGroupManagerRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - instance_group_manager = proto.Field(proto.STRING, number=249363395) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - + instance_group_manager = proto.Field(proto.STRING, number=249363395,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) region_instance_group_managers_create_instances_request_resource = proto.Field( proto.MESSAGE, - number=90578824, + number=359014280, message="RegionInstanceGroupManagersCreateInstancesRequest", ) - - request_id = proto.Field(proto.STRING, number=37109963) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class DeleteRegionInstanceGroupManagerRequest(proto.Message): @@ -40036,13 +37297,10 @@ class DeleteRegionInstanceGroupManagerRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - instance_group_manager = proto.Field(proto.STRING, number=249363395) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + instance_group_manager = proto.Field(proto.STRING, number=249363395,) + 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 DeleteInstancesRegionInstanceGroupManagerRequest(proto.Message): @@ -40077,19 +37335,15 @@ class DeleteInstancesRegionInstanceGroupManagerRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - instance_group_manager = proto.Field(proto.STRING, number=249363395) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - + instance_group_manager = proto.Field(proto.STRING, number=249363395,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) region_instance_group_managers_delete_instances_request_resource = proto.Field( proto.MESSAGE, - number=232441209, + number=500876665, message="RegionInstanceGroupManagersDeleteInstancesRequest", ) - - request_id = proto.Field(proto.STRING, number=37109963) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class DeletePerInstanceConfigsRegionInstanceGroupManagerRequest(proto.Message): @@ -40110,12 +37364,9 @@ class DeletePerInstanceConfigsRegionInstanceGroupManagerRequest(proto.Message): The body resource for this request """ - instance_group_manager = proto.Field(proto.STRING, number=249363395) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - + instance_group_manager = proto.Field(proto.STRING, number=249363395,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) region_instance_group_manager_delete_instance_config_req_resource = proto.Field( proto.MESSAGE, number=740741, @@ -40136,11 +37387,9 @@ class GetRegionInstanceGroupManagerRequest(proto.Message): Name of the region scoping this request. """ - instance_group_manager = proto.Field(proto.STRING, number=249363395) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) + instance_group_manager = proto.Field(proto.STRING, number=249363395,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) class InsertRegionInstanceGroupManagerRequest(proto.Message): @@ -40175,12 +37424,9 @@ class InsertRegionInstanceGroupManagerRequest(proto.Message): instance_group_manager_resource = proto.Field( proto.MESSAGE, number=261063946, message="InstanceGroupManager", ) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + 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 ListRegionInstanceGroupManagersRequest(proto.Message): @@ -40250,19 +37496,13 @@ class ListRegionInstanceGroupManagersRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class ListErrorsRegionInstanceGroupManagersRequest(proto.Message): @@ -40338,21 +37578,14 @@ class ListErrorsRegionInstanceGroupManagersRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - instance_group_manager = proto.Field(proto.STRING, number=249363395) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + filter = proto.Field(proto.STRING, number=336120696, optional=True,) + instance_group_manager = proto.Field(proto.STRING, number=249363395,) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class ListManagedInstancesRegionInstanceGroupManagersRequest(proto.Message): @@ -40425,21 +37658,14 @@ class ListManagedInstancesRegionInstanceGroupManagersRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - instance_group_manager = proto.Field(proto.STRING, number=249363395) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + filter = proto.Field(proto.STRING, number=336120696, optional=True,) + instance_group_manager = proto.Field(proto.STRING, number=249363395,) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class ListPerInstanceConfigsRegionInstanceGroupManagersRequest(proto.Message): @@ -40514,21 +37740,14 @@ class ListPerInstanceConfigsRegionInstanceGroupManagersRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - instance_group_manager = proto.Field(proto.STRING, number=249363395) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + filter = proto.Field(proto.STRING, number=336120696, optional=True,) + instance_group_manager = proto.Field(proto.STRING, number=249363395,) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class PatchRegionInstanceGroupManagerRequest(proto.Message): @@ -40562,17 +37781,13 @@ class PatchRegionInstanceGroupManagerRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - instance_group_manager = proto.Field(proto.STRING, number=249363395) - + instance_group_manager = proto.Field(proto.STRING, number=249363395,) instance_group_manager_resource = proto.Field( proto.MESSAGE, number=261063946, message="InstanceGroupManager", ) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + 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 PatchPerInstanceConfigsRegionInstanceGroupManagerRequest(proto.Message): @@ -40609,19 +37824,15 @@ class PatchPerInstanceConfigsRegionInstanceGroupManagerRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - instance_group_manager = proto.Field(proto.STRING, number=249363395) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - + instance_group_manager = proto.Field(proto.STRING, number=249363395,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) region_instance_group_manager_patch_instance_config_req_resource = proto.Field( proto.MESSAGE, number=197682890, message="RegionInstanceGroupManagerPatchInstanceConfigReq", ) - - request_id = proto.Field(proto.STRING, number=37109963) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class RecreateInstancesRegionInstanceGroupManagerRequest(proto.Message): @@ -40656,19 +37867,15 @@ class RecreateInstancesRegionInstanceGroupManagerRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - instance_group_manager = proto.Field(proto.STRING, number=249363395) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - + instance_group_manager = proto.Field(proto.STRING, number=249363395,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) region_instance_group_managers_recreate_request_resource = proto.Field( proto.MESSAGE, number=170999316, message="RegionInstanceGroupManagersRecreateRequest", ) - - request_id = proto.Field(proto.STRING, number=37109963) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class ResizeRegionInstanceGroupManagerRequest(proto.Message): @@ -40703,15 +37910,11 @@ class ResizeRegionInstanceGroupManagerRequest(proto.Message): instance group manager. """ - instance_group_manager = proto.Field(proto.STRING, number=249363395) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - - size = proto.Field(proto.INT32, number=3530753) + instance_group_manager = proto.Field(proto.STRING, number=249363395,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + size = proto.Field(proto.INT32, number=3530753,) class SetInstanceTemplateRegionInstanceGroupManagerRequest(proto.Message): @@ -40746,19 +37949,15 @@ class SetInstanceTemplateRegionInstanceGroupManagerRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - instance_group_manager = proto.Field(proto.STRING, number=249363395) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - + instance_group_manager = proto.Field(proto.STRING, number=249363395,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) region_instance_group_managers_set_template_request_resource = proto.Field( proto.MESSAGE, number=187310412, message="RegionInstanceGroupManagersSetTemplateRequest", ) - - request_id = proto.Field(proto.STRING, number=37109963) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class SetTargetPoolsRegionInstanceGroupManagerRequest(proto.Message): @@ -40793,19 +37992,15 @@ class SetTargetPoolsRegionInstanceGroupManagerRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - instance_group_manager = proto.Field(proto.STRING, number=249363395) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - + instance_group_manager = proto.Field(proto.STRING, number=249363395,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) region_instance_group_managers_set_target_pools_request_resource = proto.Field( proto.MESSAGE, number=78734717, message="RegionInstanceGroupManagersSetTargetPoolsRequest", ) - - request_id = proto.Field(proto.STRING, number=37109963) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class UpdatePerInstanceConfigsRegionInstanceGroupManagerRequest(proto.Message): @@ -40842,19 +38037,15 @@ class UpdatePerInstanceConfigsRegionInstanceGroupManagerRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - instance_group_manager = proto.Field(proto.STRING, number=249363395) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - + instance_group_manager = proto.Field(proto.STRING, number=249363395,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) region_instance_group_manager_update_instance_config_req_resource = proto.Field( proto.MESSAGE, number=89036583, message="RegionInstanceGroupManagerUpdateInstanceConfigReq", ) - - request_id = proto.Field(proto.STRING, number=37109963) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class GetRegionInstanceGroupRequest(proto.Message): @@ -40871,11 +38062,9 @@ class GetRegionInstanceGroupRequest(proto.Message): Name of the region scoping this request. """ - instance_group = proto.Field(proto.STRING, number=81095253) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) + instance_group = proto.Field(proto.STRING, number=81095253,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) class ListRegionInstanceGroupsRequest(proto.Message): @@ -40945,19 +38134,13 @@ class ListRegionInstanceGroupsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class ListInstancesRegionInstanceGroupsRequest(proto.Message): @@ -41032,27 +38215,19 @@ class ListInstancesRegionInstanceGroupsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - instance_group = proto.Field(proto.STRING, number=81095253) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - + filter = proto.Field(proto.STRING, number=336120696, optional=True,) + instance_group = proto.Field(proto.STRING, number=81095253,) + 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,) + region = proto.Field(proto.STRING, number=138946292,) region_instance_groups_list_instances_request_resource = proto.Field( proto.MESSAGE, number=48239828, message="RegionInstanceGroupsListInstancesRequest", ) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class SetNamedPortsRegionInstanceGroupRequest(proto.Message): @@ -41087,19 +38262,15 @@ class SetNamedPortsRegionInstanceGroupRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - instance_group = proto.Field(proto.STRING, number=81095253) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - + instance_group = proto.Field(proto.STRING, number=81095253,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) region_instance_groups_set_named_ports_request_resource = proto.Field( proto.MESSAGE, number=1574938, message="RegionInstanceGroupsSetNamedPortsRequest", ) - - request_id = proto.Field(proto.STRING, number=37109963) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) class DeleteRegionNetworkEndpointGroupRequest(proto.Message): @@ -41134,13 +38305,10 @@ class DeleteRegionNetworkEndpointGroupRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - network_endpoint_group = proto.Field(proto.STRING, number=165471622) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + network_endpoint_group = proto.Field(proto.STRING, number=433907078,) + 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 GetRegionNetworkEndpointGroupRequest(proto.Message): @@ -41159,11 +38327,9 @@ class GetRegionNetworkEndpointGroupRequest(proto.Message): RFC1035. """ - network_endpoint_group = proto.Field(proto.STRING, number=165471622) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) + network_endpoint_group = proto.Field(proto.STRING, number=433907078,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) class InsertRegionNetworkEndpointGroupRequest(proto.Message): @@ -41198,14 +38364,11 @@ class InsertRegionNetworkEndpointGroupRequest(proto.Message): """ network_endpoint_group_resource = proto.Field( - proto.MESSAGE, number=257353383, message="NetworkEndpointGroup", + proto.MESSAGE, number=525788839, message="NetworkEndpointGroup", ) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + 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 ListRegionNetworkEndpointGroupsRequest(proto.Message): @@ -41277,19 +38440,13 @@ class ListRegionNetworkEndpointGroupsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class DeleteRegionNotificationEndpointRequest(proto.Message): @@ -41322,13 +38479,10 @@ class DeleteRegionNotificationEndpointRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - notification_endpoint = proto.Field(proto.STRING, number=108371561) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + notification_endpoint = proto.Field(proto.STRING, number=376807017,) + 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 GetRegionNotificationEndpointRequest(proto.Message): @@ -41345,11 +38499,9 @@ class GetRegionNotificationEndpointRequest(proto.Message): Name of the region scoping this request. """ - notification_endpoint = proto.Field(proto.STRING, number=108371561) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) + notification_endpoint = proto.Field(proto.STRING, number=376807017,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) class InsertRegionNotificationEndpointRequest(proto.Message): @@ -41382,14 +38534,11 @@ class InsertRegionNotificationEndpointRequest(proto.Message): """ notification_endpoint_resource = proto.Field( - proto.MESSAGE, number=70024484, message="NotificationEndpoint", + proto.MESSAGE, number=338459940, message="NotificationEndpoint", ) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) + 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 ListRegionNotificationEndpointsRequest(proto.Message): @@ -41459,19 +38608,13 @@ class ListRegionNotificationEndpointsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class DeleteRegionOperationRequest(proto.Message): @@ -41487,17 +38630,15 @@ class DeleteRegionOperationRequest(proto.Message): Name of the region for this request. """ - operation = proto.Field(proto.STRING, number=52090215) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) + operation = proto.Field(proto.STRING, number=52090215,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) class DeleteRegionOperationResponse(proto.Message): r"""A response message for RegionOperations.Delete. See the method description for details. - """ + """ class GetRegionOperationRequest(proto.Message): @@ -41513,11 +38654,9 @@ class GetRegionOperationRequest(proto.Message): Name of the region for this request. """ - operation = proto.Field(proto.STRING, number=52090215) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) + operation = proto.Field(proto.STRING, number=52090215,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) class ListRegionOperationsRequest(proto.Message): @@ -41587,19 +38726,13 @@ class ListRegionOperationsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class WaitRegionOperationRequest(proto.Message): @@ -41615,11 +38748,9 @@ class WaitRegionOperationRequest(proto.Message): Name of the region for this request. """ - operation = proto.Field(proto.STRING, number=52090215) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) + operation = proto.Field(proto.STRING, number=52090215,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) class DeleteRegionSslCertificateRequest(proto.Message): @@ -41652,13 +38783,10 @@ class DeleteRegionSslCertificateRequest(proto.Message): delete. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - - ssl_certificate = proto.Field(proto.STRING, number=46443492) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + ssl_certificate = proto.Field(proto.STRING, number=46443492,) class GetRegionSslCertificateRequest(proto.Message): @@ -41675,11 +38803,9 @@ class GetRegionSslCertificateRequest(proto.Message): return. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - ssl_certificate = proto.Field(proto.STRING, number=46443492) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + ssl_certificate = proto.Field(proto.STRING, number=46443492,) class InsertRegionSslCertificateRequest(proto.Message): @@ -41711,12 +38837,9 @@ class InsertRegionSslCertificateRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) ssl_certificate_resource = proto.Field( proto.MESSAGE, number=180709897, message="SslCertificate", ) @@ -41789,19 +38912,13 @@ class ListRegionSslCertificatesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class DeleteRegionTargetHttpProxyRequest(proto.Message): @@ -41834,13 +38951,10 @@ class DeleteRegionTargetHttpProxyRequest(proto.Message): delete. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - - target_http_proxy = proto.Field(proto.STRING, number=206872421) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + target_http_proxy = proto.Field(proto.STRING, number=206872421,) class GetRegionTargetHttpProxyRequest(proto.Message): @@ -41857,11 +38971,9 @@ class GetRegionTargetHttpProxyRequest(proto.Message): return. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - target_http_proxy = proto.Field(proto.STRING, number=206872421) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + target_http_proxy = proto.Field(proto.STRING, number=206872421,) class InsertRegionTargetHttpProxyRequest(proto.Message): @@ -41893,12 +39005,9 @@ class InsertRegionTargetHttpProxyRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) target_http_proxy_resource = proto.Field( proto.MESSAGE, number=24696744, message="TargetHttpProxy", ) @@ -41971,19 +39080,13 @@ class ListRegionTargetHttpProxiesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class SetUrlMapRegionTargetHttpProxyRequest(proto.Message): @@ -42018,16 +39121,12 @@ class SetUrlMapRegionTargetHttpProxyRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - - target_http_proxy = proto.Field(proto.STRING, number=206872421) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + target_http_proxy = proto.Field(proto.STRING, number=206872421,) url_map_reference_resource = proto.Field( - proto.MESSAGE, number=130265877, message="UrlMapReference", + proto.MESSAGE, number=398701333, message="UrlMapReference", ) @@ -42061,13 +39160,10 @@ class DeleteRegionTargetHttpsProxyRequest(proto.Message): delete. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - - target_https_proxy = proto.Field(proto.STRING, number=52336748) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + target_https_proxy = proto.Field(proto.STRING, number=52336748,) class GetRegionTargetHttpsProxyRequest(proto.Message): @@ -42084,11 +39180,9 @@ class GetRegionTargetHttpsProxyRequest(proto.Message): return. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - target_https_proxy = proto.Field(proto.STRING, number=52336748) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + target_https_proxy = proto.Field(proto.STRING, number=52336748,) class InsertRegionTargetHttpsProxyRequest(proto.Message): @@ -42120,14 +39214,11 @@ class InsertRegionTargetHttpsProxyRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) target_https_proxy_resource = proto.Field( - proto.MESSAGE, number=165222017, message="TargetHttpsProxy", + proto.MESSAGE, number=433657473, message="TargetHttpsProxy", ) @@ -42198,19 +39289,13 @@ class ListRegionTargetHttpsProxiesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class SetSslCertificatesRegionTargetHttpsProxyRequest(proto.Message): @@ -42246,19 +39331,15 @@ class SetSslCertificatesRegionTargetHttpsProxyRequest(proto.Message): an SslCertificates resource for. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) region_target_https_proxies_set_ssl_certificates_request_resource = proto.Field( proto.MESSAGE, - number=122257927, + number=390693383, message="RegionTargetHttpsProxiesSetSslCertificatesRequest", ) - - request_id = proto.Field(proto.STRING, number=37109963) - - target_https_proxy = proto.Field(proto.STRING, number=52336748) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + target_https_proxy = proto.Field(proto.STRING, number=52336748,) class SetUrlMapRegionTargetHttpsProxyRequest(proto.Message): @@ -42293,16 +39374,12 @@ class SetUrlMapRegionTargetHttpsProxyRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - - target_https_proxy = proto.Field(proto.STRING, number=52336748) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + target_https_proxy = proto.Field(proto.STRING, number=52336748,) url_map_reference_resource = proto.Field( - proto.MESSAGE, number=130265877, message="UrlMapReference", + proto.MESSAGE, number=398701333, message="UrlMapReference", ) @@ -42322,13 +39399,10 @@ class DeleteRegionUrlMapRequest(proto.Message): Name of the UrlMap resource to delete. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - - url_map = proto.Field(proto.STRING, number=98585228) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + url_map = proto.Field(proto.STRING, number=367020684,) class GetRegionUrlMapRequest(proto.Message): @@ -42344,11 +39418,9 @@ class GetRegionUrlMapRequest(proto.Message): Name of the UrlMap resource to return. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - url_map = proto.Field(proto.STRING, number=98585228) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + url_map = proto.Field(proto.STRING, number=367020684,) class InsertRegionUrlMapRequest(proto.Message): @@ -42367,12 +39439,9 @@ class InsertRegionUrlMapRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) url_map_resource = proto.Field(proto.MESSAGE, number=168675425, message="UrlMap",) @@ -42443,19 +39512,13 @@ class ListRegionUrlMapsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class PatchRegionUrlMapRequest(proto.Message): @@ -42476,14 +39539,10 @@ class PatchRegionUrlMapRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - - url_map = proto.Field(proto.STRING, number=98585228) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + url_map = proto.Field(proto.STRING, number=367020684,) url_map_resource = proto.Field(proto.MESSAGE, number=168675425, message="UrlMap",) @@ -42505,14 +39564,10 @@ class UpdateRegionUrlMapRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - - url_map = proto.Field(proto.STRING, number=98585228) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + url_map = proto.Field(proto.STRING, number=367020684,) url_map_resource = proto.Field(proto.MESSAGE, number=168675425, message="UrlMap",) @@ -42532,15 +39587,12 @@ class ValidateRegionUrlMapRequest(proto.Message): as. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) region_url_maps_validate_request_resource = proto.Field( proto.MESSAGE, number=56632858, message="RegionUrlMapsValidateRequest", ) - - url_map = proto.Field(proto.STRING, number=98585228) + url_map = proto.Field(proto.STRING, number=367020684,) class GetRegionRequest(proto.Message): @@ -42554,9 +39606,8 @@ class GetRegionRequest(proto.Message): Name of the region resource to return. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) class ListRegionsRequest(proto.Message): @@ -42624,17 +39675,12 @@ class ListRegionsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 AggregatedListReservationsRequest(proto.Message): @@ -42713,19 +39759,13 @@ class AggregatedListReservationsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 DeleteReservationRequest(proto.Message): @@ -42757,13 +39797,10 @@ class DeleteReservationRequest(proto.Message): Name of the zone for this request. """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - reservation = proto.Field(proto.STRING, number=47530956) - - zone = proto.Field(proto.STRING, number=3744684) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + reservation = proto.Field(proto.STRING, number=47530956,) + zone = proto.Field(proto.STRING, number=3744684,) class GetReservationRequest(proto.Message): @@ -42779,11 +39816,9 @@ class GetReservationRequest(proto.Message): Name of the zone for this request. """ - project = proto.Field(proto.STRING, number=227560217) - - reservation = proto.Field(proto.STRING, number=47530956) - - zone = proto.Field(proto.STRING, number=3744684) + project = proto.Field(proto.STRING, number=227560217,) + reservation = proto.Field(proto.STRING, number=47530956,) + zone = proto.Field(proto.STRING, number=3744684,) class GetIamPolicyReservationRequest(proto.Message): @@ -42801,13 +39836,12 @@ class GetIamPolicyReservationRequest(proto.Message): The name of the zone for this request. """ - options_requested_policy_version = proto.Field(proto.INT32, number=230784573) - - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) - - zone = proto.Field(proto.STRING, number=3744684) + options_requested_policy_version = proto.Field( + proto.INT32, number=499220029, optional=True, + ) + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) + zone = proto.Field(proto.STRING, number=3744684,) class InsertReservationRequest(proto.Message): @@ -42839,15 +39873,12 @@ class InsertReservationRequest(proto.Message): Name of the zone for this request. """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) reservation_resource = proto.Field( - proto.MESSAGE, number=16594721, message="Reservation", + proto.MESSAGE, number=285030177, message="Reservation", ) - - zone = proto.Field(proto.STRING, number=3744684) + zone = proto.Field(proto.STRING, number=3744684,) class ListReservationsRequest(proto.Message): @@ -42917,19 +39948,13 @@ class ListReservationsRequest(proto.Message): Name of the zone for this request. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) - - zone = proto.Field(proto.STRING, number=3744684) + 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,) + zone = proto.Field(proto.STRING, number=3744684,) class ResizeReservationRequest(proto.Message): @@ -42963,17 +39988,13 @@ class ResizeReservationRequest(proto.Message): Name of the zone for this request. """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - reservation = proto.Field(proto.STRING, number=47530956) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + reservation = proto.Field(proto.STRING, number=47530956,) reservations_resize_request_resource = proto.Field( - proto.MESSAGE, number=120827345, message="ReservationsResizeRequest", + proto.MESSAGE, number=389262801, message="ReservationsResizeRequest", ) - - zone = proto.Field(proto.STRING, number=3744684) + zone = proto.Field(proto.STRING, number=3744684,) class SetIamPolicyReservationRequest(proto.Message): @@ -42991,14 +40012,11 @@ class SetIamPolicyReservationRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) - - zone = proto.Field(proto.STRING, number=3744684) - + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) + zone = proto.Field(proto.STRING, number=3744684,) zone_set_policy_request_resource = proto.Field( - proto.MESSAGE, number=113646651, message="ZoneSetPolicyRequest", + proto.MESSAGE, number=382082107, message="ZoneSetPolicyRequest", ) @@ -43017,15 +40035,12 @@ class TestIamPermissionsReservationRequest(proto.Message): The name of the zone for this request. """ - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) - + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) test_permissions_request_resource = proto.Field( - proto.MESSAGE, number=170779302, message="TestPermissionsRequest", + proto.MESSAGE, number=439214758, message="TestPermissionsRequest", ) - - zone = proto.Field(proto.STRING, number=3744684) + zone = proto.Field(proto.STRING, number=3744684,) class AggregatedListResourcePoliciesRequest(proto.Message): @@ -43104,19 +40119,13 @@ class AggregatedListResourcePoliciesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 DeleteResourcePolicyRequest(proto.Message): @@ -43148,13 +40157,10 @@ class DeleteResourcePolicyRequest(proto.Message): Name of the resource policy to delete. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - - resource_policy = proto.Field(proto.STRING, number=159240835) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + resource_policy = proto.Field(proto.STRING, number=159240835,) class GetResourcePolicyRequest(proto.Message): @@ -43170,11 +40176,9 @@ class GetResourcePolicyRequest(proto.Message): Name of the resource policy to retrieve. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - resource_policy = proto.Field(proto.STRING, number=159240835) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + resource_policy = proto.Field(proto.STRING, number=159240835,) class GetIamPolicyResourcePolicyRequest(proto.Message): @@ -43192,13 +40196,12 @@ class GetIamPolicyResourcePolicyRequest(proto.Message): Name or id of the resource for this request. """ - options_requested_policy_version = proto.Field(proto.INT32, number=230784573) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - resource = proto.Field(proto.STRING, number=195806222) + options_requested_policy_version = proto.Field( + proto.INT32, number=499220029, optional=True, + ) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + resource = proto.Field(proto.STRING, number=195806222,) class InsertResourcePolicyRequest(proto.Message): @@ -43230,12 +40233,9 @@ class InsertResourcePolicyRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) resource_policy_resource = proto.Field( proto.MESSAGE, number=76826186, message="ResourcePolicy", ) @@ -43308,19 +40308,13 @@ class ListResourcePoliciesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class SetIamPolicyResourcePolicyRequest(proto.Message): @@ -43338,15 +40332,12 @@ class SetIamPolicyResourcePolicyRequest(proto.Message): Name or id of the resource for this request. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) region_set_policy_request_resource = proto.Field( - proto.MESSAGE, number=8053635, message="RegionSetPolicyRequest", + proto.MESSAGE, number=276489091, message="RegionSetPolicyRequest", ) - - resource = proto.Field(proto.STRING, number=195806222) + resource = proto.Field(proto.STRING, number=195806222,) class TestIamPermissionsResourcePolicyRequest(proto.Message): @@ -43364,14 +40355,11 @@ class TestIamPermissionsResourcePolicyRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - resource = proto.Field(proto.STRING, number=195806222) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + resource = proto.Field(proto.STRING, number=195806222,) test_permissions_request_resource = proto.Field( - proto.MESSAGE, number=170779302, message="TestPermissionsRequest", + proto.MESSAGE, number=439214758, message="TestPermissionsRequest", ) @@ -43451,19 +40439,13 @@ class AggregatedListRoutersRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 DeleteRouterRequest(proto.Message): @@ -43495,13 +40477,10 @@ class DeleteRouterRequest(proto.Message): Name of the Router resource to delete. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - - router = proto.Field(proto.STRING, number=148608841) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + router = proto.Field(proto.STRING, number=148608841,) class GetRouterRequest(proto.Message): @@ -43517,11 +40496,9 @@ class GetRouterRequest(proto.Message): Name of the Router resource to return. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - router = proto.Field(proto.STRING, number=148608841) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + router = proto.Field(proto.STRING, number=148608841,) class GetNatMappingInfoRoutersRequest(proto.Message): @@ -43594,21 +40571,14 @@ class GetNatMappingInfoRoutersRequest(proto.Message): Mapping information of VM endpoints. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) - - router = proto.Field(proto.STRING, number=148608841) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) + router = proto.Field(proto.STRING, number=148608841,) class GetRouterStatusRouterRequest(proto.Message): @@ -43624,11 +40594,9 @@ class GetRouterStatusRouterRequest(proto.Message): Name of the Router resource to query. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - router = proto.Field(proto.STRING, number=148608841) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + router = proto.Field(proto.STRING, number=148608841,) class InsertRouterRequest(proto.Message): @@ -43660,12 +40628,9 @@ class InsertRouterRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) router_resource = proto.Field(proto.MESSAGE, number=155222084, message="Router",) @@ -43736,19 +40701,13 @@ class ListRoutersRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class PatchRouterRequest(proto.Message): @@ -43782,14 +40741,10 @@ class PatchRouterRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - - router = proto.Field(proto.STRING, number=148608841) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + router = proto.Field(proto.STRING, number=148608841,) router_resource = proto.Field(proto.MESSAGE, number=155222084, message="Router",) @@ -43808,12 +40763,9 @@ class PreviewRouterRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - router = proto.Field(proto.STRING, number=148608841) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + router = proto.Field(proto.STRING, number=148608841,) router_resource = proto.Field(proto.MESSAGE, number=155222084, message="Router",) @@ -43848,14 +40800,10 @@ class UpdateRouterRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - - router = proto.Field(proto.STRING, number=148608841) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + router = proto.Field(proto.STRING, number=148608841,) router_resource = proto.Field(proto.MESSAGE, number=155222084, message="Router",) @@ -43886,11 +40834,9 @@ class DeleteRouteRequest(proto.Message): Name of the Route resource to delete. """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - route = proto.Field(proto.STRING, number=108704329) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + route = proto.Field(proto.STRING, number=108704329,) class GetRouteRequest(proto.Message): @@ -43904,9 +40850,8 @@ class GetRouteRequest(proto.Message): Name of the Route resource to return. """ - project = proto.Field(proto.STRING, number=227560217) - - route = proto.Field(proto.STRING, number=108704329) + project = proto.Field(proto.STRING, number=227560217,) + route = proto.Field(proto.STRING, number=108704329,) class InsertRouteRequest(proto.Message): @@ -43936,10 +40881,8 @@ class InsertRouteRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) route_resource = proto.Field(proto.MESSAGE, number=225428804, message="Route",) @@ -44008,17 +40951,12 @@ class ListRoutesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 AddRuleSecurityPolicyRequest(proto.Message): @@ -44034,12 +40972,10 @@ class AddRuleSecurityPolicyRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - security_policy = proto.Field(proto.STRING, number=171082513) - + project = proto.Field(proto.STRING, number=227560217,) + security_policy = proto.Field(proto.STRING, number=171082513,) security_policy_rule_resource = proto.Field( - proto.MESSAGE, number=134257987, message="SecurityPolicyRule", + proto.MESSAGE, number=402693443, message="SecurityPolicyRule", ) @@ -44070,11 +41006,9 @@ class DeleteSecurityPolicyRequest(proto.Message): Name of the security policy to delete. """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - security_policy = proto.Field(proto.STRING, number=171082513) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + security_policy = proto.Field(proto.STRING, number=171082513,) class GetSecurityPolicyRequest(proto.Message): @@ -44088,9 +41022,8 @@ class GetSecurityPolicyRequest(proto.Message): Name of the security policy to get. """ - project = proto.Field(proto.STRING, number=227560217) - - security_policy = proto.Field(proto.STRING, number=171082513) + project = proto.Field(proto.STRING, number=227560217,) + security_policy = proto.Field(proto.STRING, number=171082513,) class GetRuleSecurityPolicyRequest(proto.Message): @@ -44108,11 +41041,9 @@ class GetRuleSecurityPolicyRequest(proto.Message): queried rule belongs. """ - priority = proto.Field(proto.INT32, number=176716196) - - project = proto.Field(proto.STRING, number=227560217) - - security_policy = proto.Field(proto.STRING, number=171082513) + priority = proto.Field(proto.INT32, number=445151652, optional=True,) + project = proto.Field(proto.STRING, number=227560217,) + security_policy = proto.Field(proto.STRING, number=171082513,) class InsertSecurityPolicyRequest(proto.Message): @@ -44142,10 +41073,8 @@ class InsertSecurityPolicyRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) security_policy_resource = proto.Field( proto.MESSAGE, number=216159612, message="SecurityPolicy", ) @@ -44216,17 +41145,12 @@ class ListSecurityPoliciesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 ListPreconfiguredExpressionSetsSecurityPoliciesRequest(proto.Message): @@ -44295,17 +41219,12 @@ class ListPreconfiguredExpressionSetsSecurityPoliciesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 PatchSecurityPolicyRequest(proto.Message): @@ -44337,12 +41256,9 @@ class PatchSecurityPolicyRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - security_policy = proto.Field(proto.STRING, number=171082513) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + security_policy = proto.Field(proto.STRING, number=171082513,) security_policy_resource = proto.Field( proto.MESSAGE, number=216159612, message="SecurityPolicy", ) @@ -44363,14 +41279,11 @@ class PatchRuleSecurityPolicyRequest(proto.Message): The body resource for this request """ - priority = proto.Field(proto.INT32, number=176716196) - - project = proto.Field(proto.STRING, number=227560217) - - security_policy = proto.Field(proto.STRING, number=171082513) - + priority = proto.Field(proto.INT32, number=445151652, optional=True,) + project = proto.Field(proto.STRING, number=227560217,) + security_policy = proto.Field(proto.STRING, number=171082513,) security_policy_rule_resource = proto.Field( - proto.MESSAGE, number=134257987, message="SecurityPolicyRule", + proto.MESSAGE, number=402693443, message="SecurityPolicyRule", ) @@ -44388,11 +41301,9 @@ class RemoveRuleSecurityPolicyRequest(proto.Message): Name of the security policy to update. """ - priority = proto.Field(proto.INT32, number=176716196) - - project = proto.Field(proto.STRING, number=227560217) - - security_policy = proto.Field(proto.STRING, number=171082513) + priority = proto.Field(proto.INT32, number=445151652, optional=True,) + project = proto.Field(proto.STRING, number=227560217,) + security_policy = proto.Field(proto.STRING, number=171082513,) class DeleteSnapshotRequest(proto.Message): @@ -44422,11 +41333,9 @@ class DeleteSnapshotRequest(proto.Message): Name of the Snapshot resource to delete. """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - snapshot = proto.Field(proto.STRING, number=16438724) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + snapshot = proto.Field(proto.STRING, number=284874180,) class GetSnapshotRequest(proto.Message): @@ -44440,9 +41349,8 @@ class GetSnapshotRequest(proto.Message): Name of the Snapshot resource to return. """ - project = proto.Field(proto.STRING, number=227560217) - - snapshot = proto.Field(proto.STRING, number=16438724) + project = proto.Field(proto.STRING, number=227560217,) + snapshot = proto.Field(proto.STRING, number=284874180,) class GetIamPolicySnapshotRequest(proto.Message): @@ -44458,11 +41366,11 @@ class GetIamPolicySnapshotRequest(proto.Message): Name or id of the resource for this request. """ - options_requested_policy_version = proto.Field(proto.INT32, number=230784573) - - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) + options_requested_policy_version = proto.Field( + proto.INT32, number=499220029, optional=True, + ) + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) class ListSnapshotsRequest(proto.Message): @@ -44530,17 +41438,12 @@ class ListSnapshotsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 SetIamPolicySnapshotRequest(proto.Message): @@ -44557,12 +41460,10 @@ class SetIamPolicySnapshotRequest(proto.Message): """ global_set_policy_request_resource = proto.Field( - proto.MESSAGE, number=68613042, message="GlobalSetPolicyRequest", + proto.MESSAGE, number=337048498, message="GlobalSetPolicyRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) class SetLabelsSnapshotRequest(proto.Message): @@ -44579,12 +41480,10 @@ class SetLabelsSnapshotRequest(proto.Message): """ global_set_labels_request_resource = proto.Field( - proto.MESSAGE, number=51481733, message="GlobalSetLabelsRequest", + proto.MESSAGE, number=319917189, message="GlobalSetLabelsRequest", ) - - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) class TestIamPermissionsSnapshotRequest(proto.Message): @@ -44600,12 +41499,10 @@ class TestIamPermissionsSnapshotRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - resource = proto.Field(proto.STRING, number=195806222) - + project = proto.Field(proto.STRING, number=227560217,) + resource = proto.Field(proto.STRING, number=195806222,) test_permissions_request_resource = proto.Field( - proto.MESSAGE, number=170779302, message="TestPermissionsRequest", + proto.MESSAGE, number=439214758, message="TestPermissionsRequest", ) @@ -44685,19 +41582,13 @@ class AggregatedListSslCertificatesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 DeleteSslCertificateRequest(proto.Message): @@ -44728,11 +41619,9 @@ class DeleteSslCertificateRequest(proto.Message): delete. """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - ssl_certificate = proto.Field(proto.STRING, number=46443492) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + ssl_certificate = proto.Field(proto.STRING, number=46443492,) class GetSslCertificateRequest(proto.Message): @@ -44747,9 +41636,8 @@ class GetSslCertificateRequest(proto.Message): return. """ - project = proto.Field(proto.STRING, number=227560217) - - ssl_certificate = proto.Field(proto.STRING, number=46443492) + project = proto.Field(proto.STRING, number=227560217,) + ssl_certificate = proto.Field(proto.STRING, number=46443492,) class InsertSslCertificateRequest(proto.Message): @@ -44779,10 +41667,8 @@ class InsertSslCertificateRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) ssl_certificate_resource = proto.Field( proto.MESSAGE, number=180709897, message="SslCertificate", ) @@ -44853,17 +41739,12 @@ class ListSslCertificatesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 DeleteSslPolicyRequest(proto.Message): @@ -44895,11 +41776,9 @@ class DeleteSslPolicyRequest(proto.Message): RFC1035. """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - ssl_policy = proto.Field(proto.STRING, number=26754757) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + ssl_policy = proto.Field(proto.STRING, number=295190213,) class GetSslPolicyRequest(proto.Message): @@ -44915,9 +41794,8 @@ class GetSslPolicyRequest(proto.Message): RFC1035. """ - project = proto.Field(proto.STRING, number=227560217) - - ssl_policy = proto.Field(proto.STRING, number=26754757) + project = proto.Field(proto.STRING, number=227560217,) + ssl_policy = proto.Field(proto.STRING, number=295190213,) class InsertSslPolicyRequest(proto.Message): @@ -44947,12 +41825,10 @@ class InsertSslPolicyRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) ssl_policy_resource = proto.Field( - proto.MESSAGE, number=6456392, message="SslPolicy", + proto.MESSAGE, number=274891848, message="SslPolicy", ) @@ -45021,17 +41897,12 @@ class ListSslPoliciesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 ListAvailableFeaturesSslPoliciesRequest(proto.Message): @@ -45099,17 +41970,12 @@ class ListAvailableFeaturesSslPoliciesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 PatchSslPolicyRequest(proto.Message): @@ -45143,14 +42009,11 @@ class PatchSslPolicyRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - ssl_policy = proto.Field(proto.STRING, number=26754757) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + ssl_policy = proto.Field(proto.STRING, number=295190213,) ssl_policy_resource = proto.Field( - proto.MESSAGE, number=6456392, message="SslPolicy", + proto.MESSAGE, number=274891848, message="SslPolicy", ) @@ -45230,19 +42093,13 @@ class AggregatedListSubnetworksRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 DeleteSubnetworkRequest(proto.Message): @@ -45274,13 +42131,10 @@ class DeleteSubnetworkRequest(proto.Message): Name of the Subnetwork resource to delete. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - - subnetwork = proto.Field(proto.STRING, number=39392238) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + subnetwork = proto.Field(proto.STRING, number=307827694,) class ExpandIpCidrRangeSubnetworkRequest(proto.Message): @@ -45314,16 +42168,12 @@ class ExpandIpCidrRangeSubnetworkRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - - subnetwork = proto.Field(proto.STRING, number=39392238) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + subnetwork = proto.Field(proto.STRING, number=307827694,) subnetworks_expand_ip_cidr_range_request_resource = proto.Field( - proto.MESSAGE, number=208578654, message="SubnetworksExpandIpCidrRangeRequest", + proto.MESSAGE, number=477014110, message="SubnetworksExpandIpCidrRangeRequest", ) @@ -45340,11 +42190,9 @@ class GetSubnetworkRequest(proto.Message): Name of the Subnetwork resource to return. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - subnetwork = proto.Field(proto.STRING, number=39392238) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + subnetwork = proto.Field(proto.STRING, number=307827694,) class GetIamPolicySubnetworkRequest(proto.Message): @@ -45362,13 +42210,12 @@ class GetIamPolicySubnetworkRequest(proto.Message): Name or id of the resource for this request. """ - options_requested_policy_version = proto.Field(proto.INT32, number=230784573) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - resource = proto.Field(proto.STRING, number=195806222) + options_requested_policy_version = proto.Field( + proto.INT32, number=499220029, optional=True, + ) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + resource = proto.Field(proto.STRING, number=195806222,) class InsertSubnetworkRequest(proto.Message): @@ -45400,12 +42247,9 @@ class InsertSubnetworkRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) subnetwork_resource = proto.Field( proto.MESSAGE, number=42233151, message="Subnetwork", ) @@ -45478,19 +42322,13 @@ class ListSubnetworksRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class ListUsableSubnetworksRequest(proto.Message): @@ -45558,17 +42396,12 @@ class ListUsableSubnetworksRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 PatchSubnetworkRequest(proto.Message): @@ -45613,16 +42446,11 @@ class PatchSubnetworkRequest(proto.Message): The body resource for this request """ - drain_timeout_seconds = proto.Field(proto.INT32, number=89271642) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - - subnetwork = proto.Field(proto.STRING, number=39392238) - + drain_timeout_seconds = proto.Field(proto.INT32, number=357707098, optional=True,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + subnetwork = proto.Field(proto.STRING, number=307827694,) subnetwork_resource = proto.Field( proto.MESSAGE, number=42233151, message="Subnetwork", ) @@ -45643,15 +42471,12 @@ class SetIamPolicySubnetworkRequest(proto.Message): Name or id of the resource for this request. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) region_set_policy_request_resource = proto.Field( - proto.MESSAGE, number=8053635, message="RegionSetPolicyRequest", + proto.MESSAGE, number=276489091, message="RegionSetPolicyRequest", ) - - resource = proto.Field(proto.STRING, number=195806222) + resource = proto.Field(proto.STRING, number=195806222,) class SetPrivateIpGoogleAccessSubnetworkRequest(proto.Message): @@ -45685,17 +42510,13 @@ class SetPrivateIpGoogleAccessSubnetworkRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - - subnetwork = proto.Field(proto.STRING, number=39392238) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + subnetwork = proto.Field(proto.STRING, number=307827694,) subnetworks_set_private_ip_google_access_request_resource = proto.Field( proto.MESSAGE, - number=485240, + number=268920696, message="SubnetworksSetPrivateIpGoogleAccessRequest", ) @@ -45715,14 +42536,11 @@ class TestIamPermissionsSubnetworkRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - resource = proto.Field(proto.STRING, number=195806222) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + resource = proto.Field(proto.STRING, number=195806222,) test_permissions_request_resource = proto.Field( - proto.MESSAGE, number=170779302, message="TestPermissionsRequest", + proto.MESSAGE, number=439214758, message="TestPermissionsRequest", ) @@ -45754,11 +42572,9 @@ class DeleteTargetGrpcProxyRequest(proto.Message): delete. """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - target_grpc_proxy = proto.Field(proto.STRING, number=5020283) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + target_grpc_proxy = proto.Field(proto.STRING, number=5020283,) class GetTargetGrpcProxyRequest(proto.Message): @@ -45773,9 +42589,8 @@ class GetTargetGrpcProxyRequest(proto.Message): return. """ - project = proto.Field(proto.STRING, number=227560217) - - target_grpc_proxy = proto.Field(proto.STRING, number=5020283) + project = proto.Field(proto.STRING, number=227560217,) + target_grpc_proxy = proto.Field(proto.STRING, number=5020283,) class InsertTargetGrpcProxyRequest(proto.Message): @@ -45805,12 +42620,10 @@ class InsertTargetGrpcProxyRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) target_grpc_proxy_resource = proto.Field( - proto.MESSAGE, number=60486994, message="TargetGrpcProxy", + proto.MESSAGE, number=328922450, message="TargetGrpcProxy", ) @@ -45879,17 +42692,12 @@ class ListTargetGrpcProxiesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 PatchTargetGrpcProxyRequest(proto.Message): @@ -45922,14 +42730,11 @@ class PatchTargetGrpcProxyRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - target_grpc_proxy = proto.Field(proto.STRING, number=5020283) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + target_grpc_proxy = proto.Field(proto.STRING, number=5020283,) target_grpc_proxy_resource = proto.Field( - proto.MESSAGE, number=60486994, message="TargetGrpcProxy", + proto.MESSAGE, number=328922450, message="TargetGrpcProxy", ) @@ -46009,19 +42814,13 @@ class AggregatedListTargetHttpProxiesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 DeleteTargetHttpProxyRequest(proto.Message): @@ -46052,11 +42851,9 @@ class DeleteTargetHttpProxyRequest(proto.Message): delete. """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - target_http_proxy = proto.Field(proto.STRING, number=206872421) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + target_http_proxy = proto.Field(proto.STRING, number=206872421,) class GetTargetHttpProxyRequest(proto.Message): @@ -46071,9 +42868,8 @@ class GetTargetHttpProxyRequest(proto.Message): return. """ - project = proto.Field(proto.STRING, number=227560217) - - target_http_proxy = proto.Field(proto.STRING, number=206872421) + project = proto.Field(proto.STRING, number=227560217,) + target_http_proxy = proto.Field(proto.STRING, number=206872421,) class InsertTargetHttpProxyRequest(proto.Message): @@ -46103,10 +42899,8 @@ class InsertTargetHttpProxyRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) target_http_proxy_resource = proto.Field( proto.MESSAGE, number=24696744, message="TargetHttpProxy", ) @@ -46177,17 +42971,12 @@ class ListTargetHttpProxiesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 PatchTargetHttpProxyRequest(proto.Message): @@ -46220,12 +43009,9 @@ class PatchTargetHttpProxyRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - target_http_proxy = proto.Field(proto.STRING, number=206872421) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + target_http_proxy = proto.Field(proto.STRING, number=206872421,) target_http_proxy_resource = proto.Field( proto.MESSAGE, number=24696744, message="TargetHttpProxy", ) @@ -46261,14 +43047,11 @@ class SetUrlMapTargetHttpProxyRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - target_http_proxy = proto.Field(proto.STRING, number=206872421) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + target_http_proxy = proto.Field(proto.STRING, number=206872421,) url_map_reference_resource = proto.Field( - proto.MESSAGE, number=130265877, message="UrlMapReference", + proto.MESSAGE, number=398701333, message="UrlMapReference", ) @@ -46348,19 +43131,13 @@ class AggregatedListTargetHttpsProxiesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 DeleteTargetHttpsProxyRequest(proto.Message): @@ -46391,11 +43168,9 @@ class DeleteTargetHttpsProxyRequest(proto.Message): delete. """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - target_https_proxy = proto.Field(proto.STRING, number=52336748) + 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,) class GetTargetHttpsProxyRequest(proto.Message): @@ -46410,9 +43185,8 @@ class GetTargetHttpsProxyRequest(proto.Message): return. """ - project = proto.Field(proto.STRING, number=227560217) - - target_https_proxy = proto.Field(proto.STRING, number=52336748) + project = proto.Field(proto.STRING, number=227560217,) + target_https_proxy = proto.Field(proto.STRING, number=52336748,) class InsertTargetHttpsProxyRequest(proto.Message): @@ -46442,12 +43216,10 @@ class InsertTargetHttpsProxyRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) target_https_proxy_resource = proto.Field( - proto.MESSAGE, number=165222017, message="TargetHttpsProxy", + proto.MESSAGE, number=433657473, message="TargetHttpsProxy", ) @@ -46516,17 +43288,12 @@ class ListTargetHttpsProxiesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 SetQuicOverrideTargetHttpsProxyRequest(proto.Message): @@ -46560,17 +43327,14 @@ class SetQuicOverrideTargetHttpsProxyRequest(proto.Message): conform to RFC1035. """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) target_https_proxies_set_quic_override_request_resource = proto.Field( proto.MESSAGE, number=72940258, message="TargetHttpsProxiesSetQuicOverrideRequest", ) - - target_https_proxy = proto.Field(proto.STRING, number=52336748) + target_https_proxy = proto.Field(proto.STRING, number=52336748,) class SetSslCertificatesTargetHttpsProxyRequest(proto.Message): @@ -46603,17 +43367,14 @@ class SetSslCertificatesTargetHttpsProxyRequest(proto.Message): an SslCertificates resource for. """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) target_https_proxies_set_ssl_certificates_request_resource = proto.Field( proto.MESSAGE, number=223122908, message="TargetHttpsProxiesSetSslCertificatesRequest", ) - - target_https_proxy = proto.Field(proto.STRING, number=52336748) + target_https_proxy = proto.Field(proto.STRING, number=52336748,) class SetSslPolicyTargetHttpsProxyRequest(proto.Message): @@ -46647,15 +43408,12 @@ class SetSslPolicyTargetHttpsProxyRequest(proto.Message): characters long, and comply with RFC1035. """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) ssl_policy_reference_resource = proto.Field( proto.MESSAGE, number=235403836, message="SslPolicyReference", ) - - target_https_proxy = proto.Field(proto.STRING, number=52336748) + target_https_proxy = proto.Field(proto.STRING, number=52336748,) class SetUrlMapTargetHttpsProxyRequest(proto.Message): @@ -46688,14 +43446,11 @@ class SetUrlMapTargetHttpsProxyRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - target_https_proxy = proto.Field(proto.STRING, number=52336748) - + 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,) url_map_reference_resource = proto.Field( - proto.MESSAGE, number=130265877, message="UrlMapReference", + proto.MESSAGE, number=398701333, message="UrlMapReference", ) @@ -46775,19 +43530,13 @@ class AggregatedListTargetInstancesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 DeleteTargetInstanceRequest(proto.Message): @@ -46820,13 +43569,10 @@ class DeleteTargetInstanceRequest(proto.Message): Name of the zone scoping this request. """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - target_instance = proto.Field(proto.STRING, number=21333891) - - zone = proto.Field(proto.STRING, number=3744684) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + target_instance = proto.Field(proto.STRING, number=289769347,) + zone = proto.Field(proto.STRING, number=3744684,) class GetTargetInstanceRequest(proto.Message): @@ -46843,11 +43589,9 @@ class GetTargetInstanceRequest(proto.Message): Name of the zone scoping this request. """ - project = proto.Field(proto.STRING, number=227560217) - - target_instance = proto.Field(proto.STRING, number=21333891) - - zone = proto.Field(proto.STRING, number=3744684) + project = proto.Field(proto.STRING, number=227560217,) + target_instance = proto.Field(proto.STRING, number=289769347,) + zone = proto.Field(proto.STRING, number=3744684,) class InsertTargetInstanceRequest(proto.Message): @@ -46879,15 +43623,12 @@ class InsertTargetInstanceRequest(proto.Message): Name of the zone scoping this request. """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) target_instance_resource = proto.Field( - proto.MESSAGE, number=162017610, message="TargetInstance", + proto.MESSAGE, number=430453066, message="TargetInstance", ) - - zone = proto.Field(proto.STRING, number=3744684) + zone = proto.Field(proto.STRING, number=3744684,) class ListTargetInstancesRequest(proto.Message): @@ -46957,19 +43698,13 @@ class ListTargetInstancesRequest(proto.Message): Name of the zone scoping this request. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) - - zone = proto.Field(proto.STRING, number=3744684) + 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,) + zone = proto.Field(proto.STRING, number=3744684,) class AddHealthCheckTargetPoolRequest(proto.Message): @@ -47004,16 +43739,12 @@ class AddHealthCheckTargetPoolRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - - target_pool = proto.Field(proto.STRING, number=62796298) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + target_pool = proto.Field(proto.STRING, number=62796298,) target_pools_add_health_check_request_resource = proto.Field( - proto.MESSAGE, number=1137956, message="TargetPoolsAddHealthCheckRequest", + proto.MESSAGE, number=269573412, message="TargetPoolsAddHealthCheckRequest", ) @@ -47049,16 +43780,12 @@ class AddInstanceTargetPoolRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - - target_pool = proto.Field(proto.STRING, number=62796298) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + target_pool = proto.Field(proto.STRING, number=62796298,) target_pools_add_instance_request_resource = proto.Field( - proto.MESSAGE, number=160360948, message="TargetPoolsAddInstanceRequest", + proto.MESSAGE, number=428796404, message="TargetPoolsAddInstanceRequest", ) @@ -47138,19 +43865,13 @@ class AggregatedListTargetPoolsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 DeleteTargetPoolRequest(proto.Message): @@ -47182,13 +43903,10 @@ class DeleteTargetPoolRequest(proto.Message): Name of the TargetPool resource to delete. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - - target_pool = proto.Field(proto.STRING, number=62796298) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + target_pool = proto.Field(proto.STRING, number=62796298,) class GetTargetPoolRequest(proto.Message): @@ -47204,11 +43922,9 @@ class GetTargetPoolRequest(proto.Message): Name of the TargetPool resource to return. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - target_pool = proto.Field(proto.STRING, number=62796298) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + target_pool = proto.Field(proto.STRING, number=62796298,) class GetHealthTargetPoolRequest(proto.Message): @@ -47228,14 +43944,11 @@ class GetHealthTargetPoolRequest(proto.Message): """ instance_reference_resource = proto.Field( - proto.MESSAGE, number=24490604, message="InstanceReference", + proto.MESSAGE, number=292926060, message="InstanceReference", ) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - target_pool = proto.Field(proto.STRING, number=62796298) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + target_pool = proto.Field(proto.STRING, number=62796298,) class InsertTargetPoolRequest(proto.Message): @@ -47267,12 +43980,9 @@ class InsertTargetPoolRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) target_pool_resource = proto.Field( proto.MESSAGE, number=101281443, message="TargetPool", ) @@ -47345,19 +44055,13 @@ class ListTargetPoolsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class RemoveHealthCheckTargetPoolRequest(proto.Message): @@ -47392,16 +44096,12 @@ class RemoveHealthCheckTargetPoolRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - - target_pool = proto.Field(proto.STRING, number=62796298) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + target_pool = proto.Field(proto.STRING, number=62796298,) target_pools_remove_health_check_request_resource = proto.Field( - proto.MESSAGE, number=36549555, message="TargetPoolsRemoveHealthCheckRequest", + proto.MESSAGE, number=304985011, message="TargetPoolsRemoveHealthCheckRequest", ) @@ -47437,14 +44137,10 @@ class RemoveInstanceTargetPoolRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - - target_pool = proto.Field(proto.STRING, number=62796298) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + target_pool = proto.Field(proto.STRING, number=62796298,) target_pools_remove_instance_request_resource = proto.Field( proto.MESSAGE, number=29548547, message="TargetPoolsRemoveInstanceRequest", ) @@ -47484,18 +44180,13 @@ class SetBackupTargetPoolRequest(proto.Message): The body resource for this request """ - failover_ratio = proto.Field(proto.FLOAT, number=212667006) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - - target_pool = proto.Field(proto.STRING, number=62796298) - + failover_ratio = proto.Field(proto.FLOAT, number=212667006, optional=True,) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + target_pool = proto.Field(proto.STRING, number=62796298,) target_reference_resource = proto.Field( - proto.MESSAGE, number=255286256, message="TargetReference", + proto.MESSAGE, number=523721712, message="TargetReference", ) @@ -47527,11 +44218,9 @@ class DeleteTargetSslProxyRequest(proto.Message): delete. """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - target_ssl_proxy = proto.Field(proto.STRING, number=70360397) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + target_ssl_proxy = proto.Field(proto.STRING, number=338795853,) class GetTargetSslProxyRequest(proto.Message): @@ -47546,9 +44235,8 @@ class GetTargetSslProxyRequest(proto.Message): return. """ - project = proto.Field(proto.STRING, number=227560217) - - target_ssl_proxy = proto.Field(proto.STRING, number=70360397) + project = proto.Field(proto.STRING, number=227560217,) + target_ssl_proxy = proto.Field(proto.STRING, number=338795853,) class InsertTargetSslProxyRequest(proto.Message): @@ -47578,10 +44266,8 @@ class InsertTargetSslProxyRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) target_ssl_proxy_resource = proto.Field( proto.MESSAGE, number=142016192, message="TargetSslProxy", ) @@ -47652,17 +44338,12 @@ class ListTargetSslProxiesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 SetBackendServiceTargetSslProxyRequest(proto.Message): @@ -47695,17 +44376,14 @@ class SetBackendServiceTargetSslProxyRequest(proto.Message): BackendService resource is to be set. """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) target_ssl_proxies_set_backend_service_request_resource = proto.Field( proto.MESSAGE, number=139080868, message="TargetSslProxiesSetBackendServiceRequest", ) - - target_ssl_proxy = proto.Field(proto.STRING, number=70360397) + target_ssl_proxy = proto.Field(proto.STRING, number=338795853,) class SetProxyHeaderTargetSslProxyRequest(proto.Message): @@ -47738,17 +44416,14 @@ class SetProxyHeaderTargetSslProxyRequest(proto.Message): ProxyHeader is to be set. """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) target_ssl_proxies_set_proxy_header_request_resource = proto.Field( proto.MESSAGE, number=205284526, message="TargetSslProxiesSetProxyHeaderRequest", ) - - target_ssl_proxy = proto.Field(proto.STRING, number=70360397) + target_ssl_proxy = proto.Field(proto.STRING, number=338795853,) class SetSslCertificatesTargetSslProxyRequest(proto.Message): @@ -47781,17 +44456,14 @@ class SetSslCertificatesTargetSslProxyRequest(proto.Message): SslCertificate resource is to be set. """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) target_ssl_proxies_set_ssl_certificates_request_resource = proto.Field( proto.MESSAGE, number=147940797, message="TargetSslProxiesSetSslCertificatesRequest", ) - - target_ssl_proxy = proto.Field(proto.STRING, number=70360397) + target_ssl_proxy = proto.Field(proto.STRING, number=338795853,) class SetSslPolicyTargetSslProxyRequest(proto.Message): @@ -47825,15 +44497,12 @@ class SetSslPolicyTargetSslProxyRequest(proto.Message): characters long, and comply with RFC1035. """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) ssl_policy_reference_resource = proto.Field( proto.MESSAGE, number=235403836, message="SslPolicyReference", ) - - target_ssl_proxy = proto.Field(proto.STRING, number=70360397) + target_ssl_proxy = proto.Field(proto.STRING, number=338795853,) class DeleteTargetTcpProxyRequest(proto.Message): @@ -47864,11 +44533,9 @@ class DeleteTargetTcpProxyRequest(proto.Message): delete. """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - target_tcp_proxy = proto.Field(proto.STRING, number=234629986) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + target_tcp_proxy = proto.Field(proto.STRING, number=503065442,) class GetTargetTcpProxyRequest(proto.Message): @@ -47883,9 +44550,8 @@ class GetTargetTcpProxyRequest(proto.Message): return. """ - project = proto.Field(proto.STRING, number=227560217) - - target_tcp_proxy = proto.Field(proto.STRING, number=234629986) + project = proto.Field(proto.STRING, number=227560217,) + target_tcp_proxy = proto.Field(proto.STRING, number=503065442,) class InsertTargetTcpProxyRequest(proto.Message): @@ -47915,10 +44581,8 @@ class InsertTargetTcpProxyRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) target_tcp_proxy_resource = proto.Field( proto.MESSAGE, number=145913931, message="TargetTcpProxy", ) @@ -47989,17 +44653,12 @@ class ListTargetTcpProxiesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 SetBackendServiceTargetTcpProxyRequest(proto.Message): @@ -48032,17 +44691,14 @@ class SetBackendServiceTargetTcpProxyRequest(proto.Message): BackendService resource is to be set. """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) target_tcp_proxies_set_backend_service_request_resource = proto.Field( proto.MESSAGE, - number=5286127, + number=273721583, message="TargetTcpProxiesSetBackendServiceRequest", ) - - target_tcp_proxy = proto.Field(proto.STRING, number=234629986) + target_tcp_proxy = proto.Field(proto.STRING, number=503065442,) class SetProxyHeaderTargetTcpProxyRequest(proto.Message): @@ -48075,17 +44731,14 @@ class SetProxyHeaderTargetTcpProxyRequest(proto.Message): ProxyHeader is to be set. """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) target_tcp_proxies_set_proxy_header_request_resource = proto.Field( proto.MESSAGE, number=219958339, message="TargetTcpProxiesSetProxyHeaderRequest", ) - - target_tcp_proxy = proto.Field(proto.STRING, number=234629986) + target_tcp_proxy = proto.Field(proto.STRING, number=503065442,) class AggregatedListTargetVpnGatewaysRequest(proto.Message): @@ -48164,19 +44817,13 @@ class AggregatedListTargetVpnGatewaysRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 DeleteTargetVpnGatewayRequest(proto.Message): @@ -48208,13 +44855,10 @@ class DeleteTargetVpnGatewayRequest(proto.Message): Name of the target VPN gateway to delete. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - - target_vpn_gateway = proto.Field(proto.STRING, number=264077387) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + target_vpn_gateway = proto.Field(proto.STRING, number=532512843,) class GetTargetVpnGatewayRequest(proto.Message): @@ -48230,11 +44874,9 @@ class GetTargetVpnGatewayRequest(proto.Message): Name of the target VPN gateway to return. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - target_vpn_gateway = proto.Field(proto.STRING, number=264077387) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + target_vpn_gateway = proto.Field(proto.STRING, number=532512843,) class InsertTargetVpnGatewayRequest(proto.Message): @@ -48266,12 +44908,9 @@ class InsertTargetVpnGatewayRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) target_vpn_gateway_resource = proto.Field( proto.MESSAGE, number=498050, message="TargetVpnGateway", ) @@ -48344,19 +44983,13 @@ class ListTargetVpnGatewaysRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class AggregatedListUrlMapsRequest(proto.Message): @@ -48435,19 +45068,13 @@ class AggregatedListUrlMapsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 DeleteUrlMapRequest(proto.Message): @@ -48477,11 +45104,9 @@ class DeleteUrlMapRequest(proto.Message): Name of the UrlMap resource to delete. """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - url_map = proto.Field(proto.STRING, number=98585228) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + url_map = proto.Field(proto.STRING, number=367020684,) class GetUrlMapRequest(proto.Message): @@ -48495,9 +45120,8 @@ class GetUrlMapRequest(proto.Message): Name of the UrlMap resource to return. """ - project = proto.Field(proto.STRING, number=227560217) - - url_map = proto.Field(proto.STRING, number=98585228) + project = proto.Field(proto.STRING, number=227560217,) + url_map = proto.Field(proto.STRING, number=367020684,) class InsertUrlMapRequest(proto.Message): @@ -48527,10 +45151,8 @@ class InsertUrlMapRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) url_map_resource = proto.Field(proto.MESSAGE, number=168675425, message="UrlMap",) @@ -48564,14 +45186,11 @@ class InvalidateCacheUrlMapRequest(proto.Message): """ cache_invalidation_rule_resource = proto.Field( - proto.MESSAGE, number=44360109, message="CacheInvalidationRule", + proto.MESSAGE, number=312795565, message="CacheInvalidationRule", ) - - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - url_map = proto.Field(proto.STRING, number=98585228) + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + url_map = proto.Field(proto.STRING, number=367020684,) class ListUrlMapsRequest(proto.Message): @@ -48639,17 +45258,12 @@ class ListUrlMapsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 PatchUrlMapRequest(proto.Message): @@ -48681,12 +45295,9 @@ class PatchUrlMapRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - url_map = proto.Field(proto.STRING, number=98585228) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + url_map = proto.Field(proto.STRING, number=367020684,) url_map_resource = proto.Field(proto.MESSAGE, number=168675425, message="UrlMap",) @@ -48719,12 +45330,9 @@ class UpdateUrlMapRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - request_id = proto.Field(proto.STRING, number=37109963) - - url_map = proto.Field(proto.STRING, number=98585228) - + project = proto.Field(proto.STRING, number=227560217,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + url_map = proto.Field(proto.STRING, number=367020684,) url_map_resource = proto.Field(proto.MESSAGE, number=168675425, message="UrlMap",) @@ -48742,12 +45350,10 @@ class ValidateUrlMapRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - url_map = proto.Field(proto.STRING, number=98585228) - + project = proto.Field(proto.STRING, number=227560217,) + url_map = proto.Field(proto.STRING, number=367020684,) url_maps_validate_request_resource = proto.Field( - proto.MESSAGE, number=127477999, message="UrlMapsValidateRequest", + proto.MESSAGE, number=395913455, message="UrlMapsValidateRequest", ) @@ -48827,19 +45433,13 @@ class AggregatedListVpnGatewaysRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 DeleteVpnGatewayRequest(proto.Message): @@ -48871,13 +45471,10 @@ class DeleteVpnGatewayRequest(proto.Message): Name of the VPN gateway to delete. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - - vpn_gateway = proto.Field(proto.STRING, number=138248697) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + vpn_gateway = proto.Field(proto.STRING, number=406684153,) class GetVpnGatewayRequest(proto.Message): @@ -48893,11 +45490,9 @@ class GetVpnGatewayRequest(proto.Message): Name of the VPN gateway to return. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - vpn_gateway = proto.Field(proto.STRING, number=138248697) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + vpn_gateway = proto.Field(proto.STRING, number=406684153,) class GetStatusVpnGatewayRequest(proto.Message): @@ -48913,11 +45508,9 @@ class GetStatusVpnGatewayRequest(proto.Message): Name of the VPN gateway to return. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - vpn_gateway = proto.Field(proto.STRING, number=138248697) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + vpn_gateway = proto.Field(proto.STRING, number=406684153,) class InsertVpnGatewayRequest(proto.Message): @@ -48949,12 +45542,9 @@ class InsertVpnGatewayRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) vpn_gateway_resource = proto.Field( proto.MESSAGE, number=182688660, message="VpnGateway", ) @@ -49027,19 +45617,13 @@ class ListVpnGatewaysRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class SetLabelsVpnGatewayRequest(proto.Message): @@ -49073,17 +45657,13 @@ class SetLabelsVpnGatewayRequest(proto.Message): Name or id of the resource for this request. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - + 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) - - resource = proto.Field(proto.STRING, number=195806222) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + resource = proto.Field(proto.STRING, number=195806222,) class TestIamPermissionsVpnGatewayRequest(proto.Message): @@ -49101,14 +45681,11 @@ class TestIamPermissionsVpnGatewayRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - resource = proto.Field(proto.STRING, number=195806222) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + resource = proto.Field(proto.STRING, number=195806222,) test_permissions_request_resource = proto.Field( - proto.MESSAGE, number=170779302, message="TestPermissionsRequest", + proto.MESSAGE, number=439214758, message="TestPermissionsRequest", ) @@ -49188,19 +45765,13 @@ class AggregatedListVpnTunnelsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - include_all_scopes = proto.Field(proto.BOOL, number=122892532) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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 DeleteVpnTunnelRequest(proto.Message): @@ -49232,13 +45803,10 @@ class DeleteVpnTunnelRequest(proto.Message): Name of the VpnTunnel resource to delete. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - - vpn_tunnel = proto.Field(proto.STRING, number=143821331) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) + vpn_tunnel = proto.Field(proto.STRING, number=143821331,) class GetVpnTunnelRequest(proto.Message): @@ -49254,11 +45822,9 @@ class GetVpnTunnelRequest(proto.Message): Name of the VpnTunnel resource to return. """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - vpn_tunnel = proto.Field(proto.STRING, number=143821331) + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + vpn_tunnel = proto.Field(proto.STRING, number=143821331,) class InsertVpnTunnelRequest(proto.Message): @@ -49290,12 +45856,9 @@ class InsertVpnTunnelRequest(proto.Message): The body resource for this request """ - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - request_id = proto.Field(proto.STRING, number=37109963) - + project = proto.Field(proto.STRING, number=227560217,) + region = proto.Field(proto.STRING, number=138946292,) + request_id = proto.Field(proto.STRING, number=37109963, optional=True,) vpn_tunnel_resource = proto.Field( proto.MESSAGE, number=86839482, message="VpnTunnel", ) @@ -49368,19 +45931,13 @@ class ListVpnTunnelsRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - region = proto.Field(proto.STRING, number=138946292) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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,) + region = proto.Field(proto.STRING, number=138946292,) + return_partial_success = proto.Field(proto.BOOL, number=517198390, optional=True,) class DeleteZoneOperationRequest(proto.Message): @@ -49396,17 +45953,15 @@ class DeleteZoneOperationRequest(proto.Message): Name of the zone for this request. """ - operation = proto.Field(proto.STRING, number=52090215) - - project = proto.Field(proto.STRING, number=227560217) - - zone = proto.Field(proto.STRING, number=3744684) + operation = proto.Field(proto.STRING, number=52090215,) + project = proto.Field(proto.STRING, number=227560217,) + zone = proto.Field(proto.STRING, number=3744684,) class DeleteZoneOperationResponse(proto.Message): r"""A response message for ZoneOperations.Delete. See the method description for details. - """ + """ class GetZoneOperationRequest(proto.Message): @@ -49422,11 +45977,9 @@ class GetZoneOperationRequest(proto.Message): Name of the zone for this request. """ - operation = proto.Field(proto.STRING, number=52090215) - - project = proto.Field(proto.STRING, number=227560217) - - zone = proto.Field(proto.STRING, number=3744684) + operation = proto.Field(proto.STRING, number=52090215,) + project = proto.Field(proto.STRING, number=227560217,) + zone = proto.Field(proto.STRING, number=3744684,) class ListZoneOperationsRequest(proto.Message): @@ -49496,19 +46049,13 @@ class ListZoneOperationsRequest(proto.Message): Name of the zone for request. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) - - zone = proto.Field(proto.STRING, number=3744684) + 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,) + zone = proto.Field(proto.STRING, number=3744684,) class WaitZoneOperationRequest(proto.Message): @@ -49524,11 +46071,9 @@ class WaitZoneOperationRequest(proto.Message): Name of the zone for this request. """ - operation = proto.Field(proto.STRING, number=52090215) - - project = proto.Field(proto.STRING, number=227560217) - - zone = proto.Field(proto.STRING, number=3744684) + operation = proto.Field(proto.STRING, number=52090215,) + project = proto.Field(proto.STRING, number=227560217,) + zone = proto.Field(proto.STRING, number=3744684,) class GetZoneRequest(proto.Message): @@ -49542,9 +46087,8 @@ class GetZoneRequest(proto.Message): Name of the zone resource to return. """ - project = proto.Field(proto.STRING, number=227560217) - - zone = proto.Field(proto.STRING, number=3744684) + project = proto.Field(proto.STRING, number=227560217,) + zone = proto.Field(proto.STRING, number=3744684,) class ListZonesRequest(proto.Message): @@ -49612,17 +46156,12 @@ class ListZonesRequest(proto.Message): as today. """ - filter = proto.Field(proto.STRING, number=67685240) - - max_results = proto.Field(proto.UINT32, number=54715419) - - order_by = proto.Field(proto.STRING, number=160562920) - - page_token = proto.Field(proto.STRING, number=19994697) - - project = proto.Field(proto.STRING, number=227560217) - - return_partial_success = proto.Field(proto.BOOL, number=248762934) + 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,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/noxfile.py b/noxfile.py index 0f27c1ff8..ae624edf3 100644 --- a/noxfile.py +++ b/noxfile.py @@ -62,16 +62,9 @@ def lint(session): session.run("flake8", "google", "tests") -@nox.session(python="3.6") +@nox.session(python=DEFAULT_PYTHON_VERSION) def blacken(session): - """Run black. - - Format code to uniform standard. - - This currently uses Python 3.6 due to the automated Kokoro run of synthtool. - That run uses an image that doesn't have 3.6 installed. Before updating this - check the state of the `gcp_ubuntu_config` we use for that Kokoro run. - """ + """Run black. Format code to uniform standard.""" session.install(BLACK_VERSION) session.run( "black", *BLACK_PATHS, @@ -131,9 +124,6 @@ def system(session): # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": session.skip("RUN_SYSTEM_TESTS is set to false, skipping") - # Sanity check: Only run tests if the environment variable is set. - if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", ""): - session.skip("Credentials must be set via environment variable") # Install pyopenssl for mTLS testing. if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true": session.install("pyopenssl") @@ -179,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=99") + session.run("coverage", "report", "--show-missing", "--fail-under=97") session.run("coverage", "erase") diff --git a/renovate.json b/renovate.json index f08bc22c9..c04895563 100644 --- a/renovate.json +++ b/renovate.json @@ -2,5 +2,8 @@ "extends": [ "config:base", ":preserveSemverRanges" ], - "ignorePaths": [".pre-commit-config.yaml"] + "ignorePaths": [".pre-commit-config.yaml"], + "pip_requirements": { + "fileMatch": ["requirements-test.txt", "samples/[\\S/]*constraints.txt", "samples/[\\S/]*constraints-test.txt"] + } } diff --git a/synth.metadata b/synth.metadata index 35613b55c..e05652630 100644 --- a/synth.metadata +++ b/synth.metadata @@ -4,28 +4,14 @@ "git": { "name": ".", "remote": "https://github.com/googleapis/python-compute.git", - "sha": "e3fee838e409a68d3208135f75a8c48900752a7d" + "sha": "4c139541aefe65545f278795470d02c3fcd0e673" } }, { "git": { "name": "googleapis-discovery", "remote": "https://github.com/googleapis/googleapis-discovery.git", - "sha": "7b9ceee340b80538579c33155dd4da0d191c4b90" - } - }, - { - "git": { - "name": "synthtool", - "remote": "https://github.com/googleapis/synthtool.git", - "sha": "5b5bf6d519b2d658d9f2e483d9f6f3d0ba8ee6bc" - } - }, - { - "git": { - "name": "synthtool", - "remote": "https://github.com/googleapis/synthtool.git", - "sha": "5b5bf6d519b2d658d9f2e483d9f6f3d0ba8ee6bc" + "sha": "8f48e81408f5582f8bf17d0b959711d955988bb9" } } ], @@ -179,6 +165,7 @@ "google/cloud/compute/__init__.py", "google/cloud/compute/py.typed", "google/cloud/compute_v1/__init__.py", + "google/cloud/compute_v1/gapic_metadata.json", "google/cloud/compute_v1/py.typed", "google/cloud/compute_v1/services/__init__.py", "google/cloud/compute_v1/services/accelerator_types/__init__.py", @@ -632,6 +619,9 @@ "scripts/readme-gen/templates/install_portaudio.tmpl.rst", "setup.cfg", "testing/.gitignore", + "tests/__init__.py", + "tests/unit/__init__.py", + "tests/unit/gapic/__init__.py", "tests/unit/gapic/compute_v1/__init__.py", "tests/unit/gapic/compute_v1/test_accelerator_types.py", "tests/unit/gapic/compute_v1/test_addresses.py", diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 000000000..4de65971c --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1,15 @@ +# -*- 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. +# diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py new file mode 100644 index 000000000..4de65971c --- /dev/null +++ b/tests/unit/__init__.py @@ -0,0 +1,15 @@ +# -*- 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. +# diff --git a/tests/unit/gapic/__init__.py b/tests/unit/gapic/__init__.py new file mode 100644 index 000000000..4de65971c --- /dev/null +++ b/tests/unit/gapic/__init__.py @@ -0,0 +1,15 @@ +# -*- 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. +# diff --git a/tests/unit/gapic/compute_v1/__init__.py b/tests/unit/gapic/compute_v1/__init__.py index 42ffdf2bc..4de65971c 100644 --- a/tests/unit/gapic/compute_v1/__init__.py +++ b/tests/unit/gapic/compute_v1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/unit/gapic/compute_v1/test_accelerator_types.py b/tests/unit/gapic/compute_v1/test_accelerator_types.py index 201d80a57..f017384fb 100644 --- a/tests/unit/gapic/compute_v1/test_accelerator_types.py +++ b/tests/unit/gapic/compute_v1/test_accelerator_types.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -88,7 +117,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [AcceleratorTypesClient,]) def test_accelerator_types_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -103,7 +132,7 @@ def test_accelerator_types_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [AcceleratorTypesClient,]) def test_accelerator_types_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -144,7 +173,7 @@ def test_accelerator_types_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(AcceleratorTypesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -392,7 +421,7 @@ def test_aggregated_list_rest( transport: str = "rest", request_type=compute.AggregatedListAcceleratorTypesRequest ): client = AcceleratorTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -419,17 +448,16 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.AcceleratorTypeAggregatedList.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 == { @@ -451,7 +479,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = AcceleratorTypesClient(credentials=credentials.AnonymousCredentials(),) + client = AcceleratorTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -474,12 +502,11 @@ def test_aggregated_list_rest_flattened(): 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 = AcceleratorTypesClient(credentials=credentials.AnonymousCredentials(),) + client = AcceleratorTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -490,12 +517,11 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = AcceleratorTypesClient(credentials=credentials.AnonymousCredentials(),) + client = AcceleratorTypesClient(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.AcceleratorTypeAggregatedList( items={ @@ -517,7 +543,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -541,7 +566,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -562,7 +586,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetAcceleratorTypeRequest ): client = AcceleratorTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -583,17 +607,16 @@ def test_get_rest( self_link="self_link_value", zone="zone_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.AcceleratorType.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.AcceleratorType) assert response.creation_timestamp == "creation_timestamp_value" assert response.deprecated == compute.DeprecationStatus(deleted="deleted_value") @@ -611,7 +634,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = AcceleratorTypesClient(credentials=credentials.AnonymousCredentials(),) + client = AcceleratorTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -638,16 +661,13 @@ def test_get_rest_flattened(): 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 "accelerator_type_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = AcceleratorTypesClient(credentials=credentials.AnonymousCredentials(),) + client = AcceleratorTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -664,7 +684,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListAcceleratorTypesRequest ): client = AcceleratorTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -684,17 +704,16 @@ def test_list_rest( 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.AcceleratorTypeList.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 == [ @@ -711,7 +730,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = AcceleratorTypesClient(credentials=credentials.AnonymousCredentials(),) + client = AcceleratorTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -736,14 +755,12 @@ def test_list_rest_flattened(): 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) def test_list_rest_flattened_error(): - client = AcceleratorTypesClient(credentials=credentials.AnonymousCredentials(),) + client = AcceleratorTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -756,12 +773,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = AcceleratorTypesClient(credentials=credentials.AnonymousCredentials(),) + client = AcceleratorTypesClient(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.AcceleratorTypeList( items=[ @@ -779,7 +795,6 @@ def test_list_pager(): items=[compute.AcceleratorType(), compute.AcceleratorType(),], ), ) - # Two responses for two calls response = response + response @@ -798,7 +813,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.AcceleratorType) for i in results) pages = list(client.list(request={}).pages) @@ -809,16 +823,16 @@ def test_list_pager(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.AcceleratorTypesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AcceleratorTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.AcceleratorTypesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AcceleratorTypesClient( @@ -828,7 +842,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.AcceleratorTypesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AcceleratorTypesClient( @@ -839,7 +853,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.AcceleratorTypesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = AcceleratorTypesClient(transport=transport) assert client.transport is transport @@ -848,17 +862,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.AcceleratorTypesRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_accelerator_types_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.AcceleratorTypesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -870,7 +884,7 @@ def test_accelerator_types_base_transport(): ) as Transport: Transport.return_value = None transport = transports.AcceleratorTypesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -885,15 +899,41 @@ def test_accelerator_types_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_accelerator_types_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.accelerator_types.transports.AcceleratorTypesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AcceleratorTypesTransport( + 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.readonly", + "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_accelerator_types_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.accelerator_types.transports.AcceleratorTypesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AcceleratorTypesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -910,19 +950,37 @@ def test_accelerator_types_base_transport_with_credentials_file(): def test_accelerator_types_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.accelerator_types.transports.AcceleratorTypesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AcceleratorTypesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_accelerator_types_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AcceleratorTypesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/compute.readonly", + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_accelerator_types_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) AcceleratorTypesClient() adc.assert_called_once_with( scopes=( @@ -935,7 +993,7 @@ def test_accelerator_types_auth_adc(): def test_accelerator_types_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -947,7 +1005,7 @@ def test_accelerator_types_http_transport_client_cert_source_for_mtls(): def test_accelerator_types_host_no_port(): client = AcceleratorTypesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -957,7 +1015,7 @@ def test_accelerator_types_host_no_port(): def test_accelerator_types_host_with_port(): client = AcceleratorTypesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -967,7 +1025,6 @@ def test_accelerator_types_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -988,7 +1045,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = AcceleratorTypesClient.common_folder_path(folder) assert expected == actual @@ -1007,7 +1063,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = AcceleratorTypesClient.common_organization_path(organization) assert expected == actual @@ -1026,7 +1081,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = AcceleratorTypesClient.common_project_path(project) assert expected == actual @@ -1046,7 +1100,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1073,7 +1126,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.AcceleratorTypesTransport, "_prep_wrapped_messages" ) as prep: client = AcceleratorTypesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1082,6 +1135,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = AcceleratorTypesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_addresses.py b/tests/unit/gapic/compute_v1/test_addresses.py index ab273cc7d..952efccff 100644 --- a/tests/unit/gapic/compute_v1/test_addresses.py +++ b/tests/unit/gapic/compute_v1/test_addresses.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,59 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -82,7 +109,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [AddressesClient,]) def test_addresses_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -97,7 +124,7 @@ def test_addresses_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [AddressesClient,]) def test_addresses_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -134,7 +161,7 @@ def test_addresses_client_get_transport_class(): def test_addresses_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(AddressesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -370,7 +397,7 @@ def test_aggregated_list_rest( transport: str = "rest", request_type=compute.AggregatedListAddressesRequest ): client = AddressesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -393,17 +420,16 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.AddressAggregatedList.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 == { @@ -423,7 +449,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = AddressesClient(credentials=credentials.AnonymousCredentials(),) + client = AddressesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -446,12 +472,11 @@ def test_aggregated_list_rest_flattened(): 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 = AddressesClient(credentials=credentials.AnonymousCredentials(),) + client = AddressesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -462,12 +487,11 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = AddressesClient(credentials=credentials.AnonymousCredentials(),) + client = AddressesClient(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.AddressAggregatedList( items={ @@ -488,7 +512,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -510,7 +533,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -528,7 +550,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteAddressRequest ): client = AddressesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -563,17 +585,16 @@ def test_delete_rest( 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" @@ -607,7 +628,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = AddressesClient(credentials=credentials.AnonymousCredentials(),) + client = AddressesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -632,16 +653,13 @@ def test_delete_rest_flattened(): 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 "address_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = AddressesClient(credentials=credentials.AnonymousCredentials(),) + client = AddressesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -656,7 +674,7 @@ def test_delete_rest_flattened_error(): def test_get_rest(transport: str = "rest", request_type=compute.GetAddressRequest): client = AddressesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -685,17 +703,16 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetAddressReques subnetwork="subnetwork_value", users=["users_value"], ) + # Wrap the value into a proper Response obj json_return_value = compute.Address.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.Address) assert response.address == "address_value" assert response.address_type == compute.Address.AddressType.EXTERNAL @@ -721,7 +738,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = AddressesClient(credentials=credentials.AnonymousCredentials(),) + client = AddressesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -746,16 +763,13 @@ def test_get_rest_flattened(): 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 "address_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = AddressesClient(credentials=credentials.AnonymousCredentials(),) + client = AddressesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -772,7 +786,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertAddressRequest ): client = AddressesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -807,17 +821,16 @@ def test_insert_rest( 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" @@ -851,7 +864,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = AddressesClient(credentials=credentials.AnonymousCredentials(),) + client = AddressesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -868,7 +881,6 @@ def test_insert_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. address_resource = compute.Address(address="address_value") - client.insert( project="project_value", region="region_value", @@ -880,11 +892,8 @@ def test_insert_rest_flattened(): 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.Address.to_json( address_resource, including_default_value_fields=False, @@ -893,7 +902,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = AddressesClient(credentials=credentials.AnonymousCredentials(),) + client = AddressesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -908,7 +917,7 @@ def test_insert_rest_flattened_error(): def test_list_rest(transport: str = "rest", request_type=compute.ListAddressesRequest): client = AddressesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -926,17 +935,16 @@ def test_list_rest(transport: str = "rest", request_type=compute.ListAddressesRe 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.AddressList.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.Address(address="address_value")] @@ -951,7 +959,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = AddressesClient(credentials=credentials.AnonymousCredentials(),) + client = AddressesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -976,14 +984,12 @@ def test_list_rest_flattened(): 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 = AddressesClient(credentials=credentials.AnonymousCredentials(),) + client = AddressesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -996,12 +1002,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = AddressesClient(credentials=credentials.AnonymousCredentials(),) + client = AddressesClient(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.AddressList( items=[compute.Address(), compute.Address(), compute.Address(),], @@ -1011,7 +1016,6 @@ def test_list_pager(): compute.AddressList(items=[compute.Address(),], next_page_token="ghi",), compute.AddressList(items=[compute.Address(), compute.Address(),],), ) - # Two responses for two calls response = response + response @@ -1030,7 +1034,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.Address) for i in results) pages = list(client.list(request={}).pages) @@ -1041,16 +1044,16 @@ def test_list_pager(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.AddressesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AddressesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.AddressesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AddressesClient( @@ -1060,7 +1063,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.AddressesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AddressesClient( @@ -1071,7 +1074,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.AddressesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = AddressesClient(transport=transport) assert client.transport is transport @@ -1080,17 +1083,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.AddressesRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_addresses_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.AddressesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1102,7 +1105,7 @@ def test_addresses_base_transport(): ) as Transport: Transport.return_value = None transport = transports.AddressesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1119,15 +1122,40 @@ def test_addresses_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_addresses_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.addresses.transports.AddressesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AddressesTransport( + 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_addresses_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.addresses.transports.AddressesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AddressesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1143,19 +1171,36 @@ def test_addresses_base_transport_with_credentials_file(): def test_addresses_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.addresses.transports.AddressesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AddressesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_addresses_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AddressesClient() + 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_addresses_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) AddressesClient() adc.assert_called_once_with( scopes=( @@ -1167,7 +1212,7 @@ def test_addresses_auth_adc(): def test_addresses_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1179,7 +1224,7 @@ def test_addresses_http_transport_client_cert_source_for_mtls(): def test_addresses_host_no_port(): client = AddressesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1189,7 +1234,7 @@ def test_addresses_host_no_port(): def test_addresses_host_with_port(): client = AddressesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1199,7 +1244,6 @@ def test_addresses_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1220,7 +1264,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = AddressesClient.common_folder_path(folder) assert expected == actual @@ -1239,7 +1282,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = AddressesClient.common_organization_path(organization) assert expected == actual @@ -1258,7 +1300,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = AddressesClient.common_project_path(project) assert expected == actual @@ -1278,7 +1319,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1305,7 +1345,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.AddressesTransport, "_prep_wrapped_messages" ) as prep: client = AddressesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1314,6 +1354,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = AddressesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_autoscalers.py b/tests/unit/gapic/compute_v1/test_autoscalers.py index 3b96aa863..17c97bcc7 100644 --- a/tests/unit/gapic/compute_v1/test_autoscalers.py +++ b/tests/unit/gapic/compute_v1/test_autoscalers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -84,7 +113,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [AutoscalersClient,]) def test_autoscalers_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -99,7 +128,7 @@ def test_autoscalers_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [AutoscalersClient,]) def test_autoscalers_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -138,7 +167,7 @@ def test_autoscalers_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(AutoscalersClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -374,7 +403,7 @@ def test_aggregated_list_rest( transport: str = "rest", request_type=compute.AggregatedListAutoscalersRequest ): client = AutoscalersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -403,17 +432,16 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.AutoscalerAggregatedList.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 == { @@ -439,7 +467,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = AutoscalersClient(credentials=credentials.AnonymousCredentials(),) + client = AutoscalersClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -462,12 +490,11 @@ def test_aggregated_list_rest_flattened(): 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 = AutoscalersClient(credentials=credentials.AnonymousCredentials(),) + client = AutoscalersClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -478,12 +505,11 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = AutoscalersClient(credentials=credentials.AnonymousCredentials(),) + client = AutoscalersClient(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.AutoscalerAggregatedList( items={ @@ -504,7 +530,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -526,7 +551,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -547,7 +571,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteAutoscalerRequest ): client = AutoscalersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -582,17 +606,16 @@ def test_delete_rest( 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" @@ -626,7 +649,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = AutoscalersClient(credentials=credentials.AnonymousCredentials(),) + client = AutoscalersClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -651,16 +674,13 @@ def test_delete_rest_flattened(): 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 "autoscaler_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = AutoscalersClient(credentials=credentials.AnonymousCredentials(),) + client = AutoscalersClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -675,7 +695,7 @@ def test_delete_rest_flattened_error(): def test_get_rest(transport: str = "rest", request_type=compute.GetAutoscalerRequest): client = AutoscalersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -700,17 +720,16 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetAutoscalerReq target="target_value", zone="zone_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.Autoscaler.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.Autoscaler) assert response.autoscaling_policy == compute.AutoscalingPolicy( cool_down_period_sec=2112 @@ -736,7 +755,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = AutoscalersClient(credentials=credentials.AnonymousCredentials(),) + client = AutoscalersClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -761,16 +780,13 @@ def test_get_rest_flattened(): 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 "autoscaler_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = AutoscalersClient(credentials=credentials.AnonymousCredentials(),) + client = AutoscalersClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -787,7 +803,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertAutoscalerRequest ): client = AutoscalersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -822,17 +838,16 @@ def test_insert_rest( 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" @@ -866,7 +881,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = AutoscalersClient(credentials=credentials.AnonymousCredentials(),) + client = AutoscalersClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -885,7 +900,6 @@ def test_insert_rest_flattened(): autoscaler_resource = compute.Autoscaler( autoscaling_policy=compute.AutoscalingPolicy(cool_down_period_sec=2112) ) - client.insert( project="project_value", zone="zone_value", @@ -897,11 +911,8 @@ def test_insert_rest_flattened(): 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.Autoscaler.to_json( autoscaler_resource, including_default_value_fields=False, @@ -910,7 +921,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = AutoscalersClient(credentials=credentials.AnonymousCredentials(),) + client = AutoscalersClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -929,7 +940,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListAutoscalersRequest ): client = AutoscalersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -953,17 +964,16 @@ def test_list_rest( 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.AutoscalerList.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 == [ @@ -982,7 +992,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = AutoscalersClient(credentials=credentials.AnonymousCredentials(),) + client = AutoscalersClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1007,14 +1017,12 @@ def test_list_rest_flattened(): 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) def test_list_rest_flattened_error(): - client = AutoscalersClient(credentials=credentials.AnonymousCredentials(),) + client = AutoscalersClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1027,12 +1035,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = AutoscalersClient(credentials=credentials.AnonymousCredentials(),) + client = AutoscalersClient(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.AutoscalerList( items=[ @@ -1050,7 +1057,6 @@ def test_list_pager(): items=[compute.Autoscaler(), compute.Autoscaler(),], ), ) - # Two responses for two calls response = response + response @@ -1069,7 +1075,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.Autoscaler) for i in results) pages = list(client.list(request={}).pages) @@ -1081,7 +1086,7 @@ def test_patch_rest( transport: str = "rest", request_type=compute.PatchAutoscalerRequest ): client = AutoscalersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1116,17 +1121,16 @@ def test_patch_rest( 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" @@ -1160,7 +1164,7 @@ def test_patch_rest_from_dict(): def test_patch_rest_flattened(): - client = AutoscalersClient(credentials=credentials.AnonymousCredentials(),) + client = AutoscalersClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1179,7 +1183,6 @@ def test_patch_rest_flattened(): autoscaler_resource = compute.Autoscaler( autoscaling_policy=compute.AutoscalingPolicy(cool_down_period_sec=2112) ) - client.patch( project="project_value", zone="zone_value", @@ -1191,11 +1194,8 @@ def test_patch_rest_flattened(): 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.Autoscaler.to_json( autoscaler_resource, including_default_value_fields=False, @@ -1204,7 +1204,7 @@ def test_patch_rest_flattened(): def test_patch_rest_flattened_error(): - client = AutoscalersClient(credentials=credentials.AnonymousCredentials(),) + client = AutoscalersClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1223,7 +1223,7 @@ def test_update_rest( transport: str = "rest", request_type=compute.UpdateAutoscalerRequest ): client = AutoscalersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1258,17 +1258,16 @@ def test_update_rest( 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.update(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" @@ -1302,7 +1301,7 @@ def test_update_rest_from_dict(): def test_update_rest_flattened(): - client = AutoscalersClient(credentials=credentials.AnonymousCredentials(),) + client = AutoscalersClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1321,7 +1320,6 @@ def test_update_rest_flattened(): autoscaler_resource = compute.Autoscaler( autoscaling_policy=compute.AutoscalingPolicy(cool_down_period_sec=2112) ) - client.update( project="project_value", zone="zone_value", @@ -1333,11 +1331,8 @@ def test_update_rest_flattened(): 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.Autoscaler.to_json( autoscaler_resource, including_default_value_fields=False, @@ -1346,7 +1341,7 @@ def test_update_rest_flattened(): def test_update_rest_flattened_error(): - client = AutoscalersClient(credentials=credentials.AnonymousCredentials(),) + client = AutoscalersClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1364,16 +1359,16 @@ def test_update_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.AutoscalersRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AutoscalersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.AutoscalersRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AutoscalersClient( @@ -1383,7 +1378,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.AutoscalersRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AutoscalersClient( @@ -1394,7 +1389,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.AutoscalersRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = AutoscalersClient(transport=transport) assert client.transport is transport @@ -1403,17 +1398,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.AutoscalersRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_autoscalers_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.AutoscalersTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1425,7 +1420,7 @@ def test_autoscalers_base_transport(): ) as Transport: Transport.return_value = None transport = transports.AutoscalersTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1444,15 +1439,40 @@ def test_autoscalers_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_autoscalers_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.autoscalers.transports.AutoscalersTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AutoscalersTransport( + 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_autoscalers_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.autoscalers.transports.AutoscalersTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AutoscalersTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1468,19 +1488,36 @@ def test_autoscalers_base_transport_with_credentials_file(): def test_autoscalers_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.autoscalers.transports.AutoscalersTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AutoscalersTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_autoscalers_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AutoscalersClient() + 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_autoscalers_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) AutoscalersClient() adc.assert_called_once_with( scopes=( @@ -1492,7 +1529,7 @@ def test_autoscalers_auth_adc(): def test_autoscalers_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1504,7 +1541,7 @@ def test_autoscalers_http_transport_client_cert_source_for_mtls(): def test_autoscalers_host_no_port(): client = AutoscalersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1514,7 +1551,7 @@ def test_autoscalers_host_no_port(): def test_autoscalers_host_with_port(): client = AutoscalersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1524,7 +1561,6 @@ def test_autoscalers_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1545,7 +1581,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = AutoscalersClient.common_folder_path(folder) assert expected == actual @@ -1564,7 +1599,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = AutoscalersClient.common_organization_path(organization) assert expected == actual @@ -1583,7 +1617,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = AutoscalersClient.common_project_path(project) assert expected == actual @@ -1603,7 +1636,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1630,7 +1662,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.AutoscalersTransport, "_prep_wrapped_messages" ) as prep: client = AutoscalersClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1639,6 +1671,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = AutoscalersClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_backend_buckets.py b/tests/unit/gapic/compute_v1/test_backend_buckets.py index 7faad5b08..efa7e1032 100644 --- a/tests/unit/gapic/compute_v1/test_backend_buckets.py +++ b/tests/unit/gapic/compute_v1/test_backend_buckets.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -87,7 +116,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [BackendBucketsClient,]) def test_backend_buckets_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -102,7 +131,7 @@ def test_backend_buckets_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [BackendBucketsClient,]) def test_backend_buckets_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -143,7 +172,7 @@ def test_backend_buckets_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(BackendBucketsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -381,7 +410,7 @@ def test_add_signed_url_key_rest( transport: str = "rest", request_type=compute.AddSignedUrlKeyBackendBucketRequest ): client = BackendBucketsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -416,17 +445,16 @@ def test_add_signed_url_key_rest( 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_signed_url_key(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" @@ -460,7 +488,7 @@ def test_add_signed_url_key_rest_from_dict(): def test_add_signed_url_key_rest_flattened(): - client = BackendBucketsClient(credentials=credentials.AnonymousCredentials(),) + client = BackendBucketsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -477,7 +505,6 @@ def test_add_signed_url_key_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. signed_url_key_resource = compute.SignedUrlKey(key_name="key_name_value") - client.add_signed_url_key( project="project_value", backend_bucket="backend_bucket_value", @@ -489,11 +516,8 @@ def test_add_signed_url_key_rest_flattened(): 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 "backend_bucket_value" in http_call[1] + str(body) - assert compute.SignedUrlKey.to_json( signed_url_key_resource, including_default_value_fields=False, @@ -502,7 +526,7 @@ def test_add_signed_url_key_rest_flattened(): def test_add_signed_url_key_rest_flattened_error(): - client = BackendBucketsClient(credentials=credentials.AnonymousCredentials(),) + client = BackendBucketsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -519,7 +543,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteBackendBucketRequest ): client = BackendBucketsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -554,17 +578,16 @@ def test_delete_rest( 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" @@ -598,7 +621,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = BackendBucketsClient(credentials=credentials.AnonymousCredentials(),) + client = BackendBucketsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -623,14 +646,12 @@ def test_delete_rest_flattened(): 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 "backend_bucket_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = BackendBucketsClient(credentials=credentials.AnonymousCredentials(),) + client = BackendBucketsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -646,7 +667,7 @@ def test_delete_signed_url_key_rest( transport: str = "rest", request_type=compute.DeleteSignedUrlKeyBackendBucketRequest ): client = BackendBucketsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -681,17 +702,16 @@ def test_delete_signed_url_key_rest( 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_signed_url_key(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" @@ -725,7 +745,7 @@ def test_delete_signed_url_key_rest_from_dict(): def test_delete_signed_url_key_rest_flattened(): - client = BackendBucketsClient(credentials=credentials.AnonymousCredentials(),) + client = BackendBucketsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -752,16 +772,13 @@ def test_delete_signed_url_key_rest_flattened(): 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 "backend_bucket_value" in http_call[1] + str(body) - assert "key_name_value" in http_call[1] + str(body) def test_delete_signed_url_key_rest_flattened_error(): - client = BackendBucketsClient(credentials=credentials.AnonymousCredentials(),) + client = BackendBucketsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -778,7 +795,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetBackendBucketRequest ): client = BackendBucketsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -802,17 +819,16 @@ def test_get_rest( name="name_value", self_link="self_link_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.BackendBucket.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.BackendBucket) assert response.bucket_name == "bucket_name_value" assert response.cdn_policy == compute.BackendBucketCdnPolicy( @@ -821,7 +837,6 @@ def test_get_rest( assert response.creation_timestamp == "creation_timestamp_value" assert response.custom_response_headers == ["custom_response_headers_value"] assert response.description == "description_value" - assert response.enable_cdn is True assert response.id == "id_value" assert response.kind == "kind_value" @@ -834,7 +849,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = BackendBucketsClient(credentials=credentials.AnonymousCredentials(),) + client = BackendBucketsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -859,14 +874,12 @@ def test_get_rest_flattened(): 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 "backend_bucket_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = BackendBucketsClient(credentials=credentials.AnonymousCredentials(),) + client = BackendBucketsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -882,7 +895,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertBackendBucketRequest ): client = BackendBucketsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -917,17 +930,16 @@ def test_insert_rest( 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" @@ -961,7 +973,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = BackendBucketsClient(credentials=credentials.AnonymousCredentials(),) + client = BackendBucketsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -978,7 +990,6 @@ def test_insert_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. backend_bucket_resource = compute.BackendBucket(bucket_name="bucket_name_value") - client.insert( project="project_value", backend_bucket_resource=backend_bucket_resource, ) @@ -988,9 +999,7 @@ def test_insert_rest_flattened(): 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.BackendBucket.to_json( backend_bucket_resource, including_default_value_fields=False, @@ -999,7 +1008,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = BackendBucketsClient(credentials=credentials.AnonymousCredentials(),) + client = BackendBucketsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1017,7 +1026,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListBackendBucketsRequest ): client = BackendBucketsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1035,17 +1044,16 @@ def test_list_rest( 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.BackendBucketList.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.BackendBucket(bucket_name="bucket_name_value")] @@ -1060,7 +1068,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = BackendBucketsClient(credentials=credentials.AnonymousCredentials(),) + client = BackendBucketsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1083,12 +1091,11 @@ def test_list_rest_flattened(): 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 = BackendBucketsClient(credentials=credentials.AnonymousCredentials(),) + client = BackendBucketsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1099,12 +1106,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = BackendBucketsClient(credentials=credentials.AnonymousCredentials(),) + client = BackendBucketsClient(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.BackendBucketList( items=[ @@ -1122,7 +1128,6 @@ def test_list_pager(): items=[compute.BackendBucket(), compute.BackendBucket(),], ), ) - # Two responses for two calls response = response + response @@ -1141,7 +1146,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.BackendBucket) for i in results) pages = list(client.list(request={}).pages) @@ -1153,7 +1157,7 @@ def test_patch_rest( transport: str = "rest", request_type=compute.PatchBackendBucketRequest ): client = BackendBucketsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1188,17 +1192,16 @@ def test_patch_rest( 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" @@ -1232,7 +1235,7 @@ def test_patch_rest_from_dict(): def test_patch_rest_flattened(): - client = BackendBucketsClient(credentials=credentials.AnonymousCredentials(),) + client = BackendBucketsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1249,7 +1252,6 @@ def test_patch_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. backend_bucket_resource = compute.BackendBucket(bucket_name="bucket_name_value") - client.patch( project="project_value", backend_bucket="backend_bucket_value", @@ -1261,11 +1263,8 @@ def test_patch_rest_flattened(): 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 "backend_bucket_value" in http_call[1] + str(body) - assert compute.BackendBucket.to_json( backend_bucket_resource, including_default_value_fields=False, @@ -1274,7 +1273,7 @@ def test_patch_rest_flattened(): def test_patch_rest_flattened_error(): - client = BackendBucketsClient(credentials=credentials.AnonymousCredentials(),) + client = BackendBucketsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1293,7 +1292,7 @@ def test_update_rest( transport: str = "rest", request_type=compute.UpdateBackendBucketRequest ): client = BackendBucketsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1328,17 +1327,16 @@ def test_update_rest( 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.update(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" @@ -1372,7 +1370,7 @@ def test_update_rest_from_dict(): def test_update_rest_flattened(): - client = BackendBucketsClient(credentials=credentials.AnonymousCredentials(),) + client = BackendBucketsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1389,7 +1387,6 @@ def test_update_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. backend_bucket_resource = compute.BackendBucket(bucket_name="bucket_name_value") - client.update( project="project_value", backend_bucket="backend_bucket_value", @@ -1401,11 +1398,8 @@ def test_update_rest_flattened(): 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 "backend_bucket_value" in http_call[1] + str(body) - assert compute.BackendBucket.to_json( backend_bucket_resource, including_default_value_fields=False, @@ -1414,7 +1408,7 @@ def test_update_rest_flattened(): def test_update_rest_flattened_error(): - client = BackendBucketsClient(credentials=credentials.AnonymousCredentials(),) + client = BackendBucketsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1432,16 +1426,16 @@ def test_update_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.BackendBucketsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = BackendBucketsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.BackendBucketsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = BackendBucketsClient( @@ -1451,7 +1445,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.BackendBucketsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = BackendBucketsClient( @@ -1462,7 +1456,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.BackendBucketsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = BackendBucketsClient(transport=transport) assert client.transport is transport @@ -1471,17 +1465,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.BackendBucketsRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_backend_buckets_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.BackendBucketsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1493,7 +1487,7 @@ def test_backend_buckets_base_transport(): ) as Transport: Transport.return_value = None transport = transports.BackendBucketsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1513,15 +1507,40 @@ def test_backend_buckets_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_backend_buckets_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.backend_buckets.transports.BackendBucketsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.BackendBucketsTransport( + 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_backend_buckets_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.backend_buckets.transports.BackendBucketsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.BackendBucketsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1537,19 +1556,36 @@ def test_backend_buckets_base_transport_with_credentials_file(): def test_backend_buckets_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.backend_buckets.transports.BackendBucketsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.BackendBucketsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_backend_buckets_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + BackendBucketsClient() + 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_backend_buckets_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) BackendBucketsClient() adc.assert_called_once_with( scopes=( @@ -1561,7 +1597,7 @@ def test_backend_buckets_auth_adc(): def test_backend_buckets_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1573,7 +1609,7 @@ def test_backend_buckets_http_transport_client_cert_source_for_mtls(): def test_backend_buckets_host_no_port(): client = BackendBucketsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1583,7 +1619,7 @@ def test_backend_buckets_host_no_port(): def test_backend_buckets_host_with_port(): client = BackendBucketsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1593,7 +1629,6 @@ def test_backend_buckets_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1614,7 +1649,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = BackendBucketsClient.common_folder_path(folder) assert expected == actual @@ -1633,7 +1667,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = BackendBucketsClient.common_organization_path(organization) assert expected == actual @@ -1652,7 +1685,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = BackendBucketsClient.common_project_path(project) assert expected == actual @@ -1672,7 +1704,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1699,7 +1730,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.BackendBucketsTransport, "_prep_wrapped_messages" ) as prep: client = BackendBucketsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1708,6 +1739,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = BackendBucketsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_backend_services.py b/tests/unit/gapic/compute_v1/test_backend_services.py index 59ec11d23..228775ab2 100644 --- a/tests/unit/gapic/compute_v1/test_backend_services.py +++ b/tests/unit/gapic/compute_v1/test_backend_services.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -87,7 +116,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [BackendServicesClient,]) def test_backend_services_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -102,7 +131,7 @@ def test_backend_services_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [BackendServicesClient,]) def test_backend_services_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -143,7 +172,7 @@ def test_backend_services_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(BackendServicesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -391,7 +420,7 @@ def test_add_signed_url_key_rest( transport: str = "rest", request_type=compute.AddSignedUrlKeyBackendServiceRequest ): client = BackendServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -426,17 +455,16 @@ def test_add_signed_url_key_rest( 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_signed_url_key(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" @@ -470,7 +498,7 @@ def test_add_signed_url_key_rest_from_dict(): def test_add_signed_url_key_rest_flattened(): - client = BackendServicesClient(credentials=credentials.AnonymousCredentials(),) + client = BackendServicesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -487,7 +515,6 @@ def test_add_signed_url_key_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. signed_url_key_resource = compute.SignedUrlKey(key_name="key_name_value") - client.add_signed_url_key( project="project_value", backend_service="backend_service_value", @@ -499,11 +526,8 @@ def test_add_signed_url_key_rest_flattened(): 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 "backend_service_value" in http_call[1] + str(body) - assert compute.SignedUrlKey.to_json( signed_url_key_resource, including_default_value_fields=False, @@ -512,7 +536,7 @@ def test_add_signed_url_key_rest_flattened(): def test_add_signed_url_key_rest_flattened_error(): - client = BackendServicesClient(credentials=credentials.AnonymousCredentials(),) + client = BackendServicesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -529,7 +553,7 @@ def test_aggregated_list_rest( transport: str = "rest", request_type=compute.AggregatedListBackendServicesRequest ): client = BackendServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -554,17 +578,16 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.BackendServiceAggregatedList.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 == { @@ -584,7 +607,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = BackendServicesClient(credentials=credentials.AnonymousCredentials(),) + client = BackendServicesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -607,12 +630,11 @@ def test_aggregated_list_rest_flattened(): 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 = BackendServicesClient(credentials=credentials.AnonymousCredentials(),) + client = BackendServicesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -623,12 +645,11 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = BackendServicesClient(credentials=credentials.AnonymousCredentials(),) + client = BackendServicesClient(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.BackendServiceAggregatedList( items={ @@ -650,7 +671,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -674,7 +694,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -695,7 +714,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteBackendServiceRequest ): client = BackendServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -730,17 +749,16 @@ def test_delete_rest( 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" @@ -774,7 +792,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = BackendServicesClient(credentials=credentials.AnonymousCredentials(),) + client = BackendServicesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -799,14 +817,12 @@ def test_delete_rest_flattened(): 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 "backend_service_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = BackendServicesClient(credentials=credentials.AnonymousCredentials(),) + client = BackendServicesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -823,7 +839,7 @@ def test_delete_signed_url_key_rest( request_type=compute.DeleteSignedUrlKeyBackendServiceRequest, ): client = BackendServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -858,17 +874,16 @@ def test_delete_signed_url_key_rest( 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_signed_url_key(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" @@ -902,7 +917,7 @@ def test_delete_signed_url_key_rest_from_dict(): def test_delete_signed_url_key_rest_flattened(): - client = BackendServicesClient(credentials=credentials.AnonymousCredentials(),) + client = BackendServicesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -929,16 +944,13 @@ def test_delete_signed_url_key_rest_flattened(): 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 "backend_service_value" in http_call[1] + str(body) - assert "key_name_value" in http_call[1] + str(body) def test_delete_signed_url_key_rest_flattened_error(): - client = BackendServicesClient(credentials=credentials.AnonymousCredentials(),) + client = BackendServicesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -955,7 +967,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetBackendServiceRequest ): client = BackendServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1013,17 +1025,16 @@ def test_get_rest( session_affinity=compute.BackendService.SessionAffinity.CLIENT_IP, timeout_sec=1185, ) + # Wrap the value into a proper Response obj json_return_value = compute.BackendService.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.BackendService) assert response.affinity_cookie_ttl_sec == 2432 assert response.backends == [ @@ -1045,7 +1056,6 @@ def test_get_rest( assert response.custom_request_headers == ["custom_request_headers_value"] assert response.custom_response_headers == ["custom_response_headers_value"] assert response.description == "description_value" - assert response.enable_c_d_n is True assert response.failover_policy == compute.BackendServiceFailoverPolicy( disable_connection_drain_on_failover=True @@ -1087,7 +1097,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = BackendServicesClient(credentials=credentials.AnonymousCredentials(),) + client = BackendServicesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1112,14 +1122,12 @@ def test_get_rest_flattened(): 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 "backend_service_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = BackendServicesClient(credentials=credentials.AnonymousCredentials(),) + client = BackendServicesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1135,7 +1143,7 @@ def test_get_health_rest( transport: str = "rest", request_type=compute.GetHealthBackendServiceRequest ): client = BackendServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1152,17 +1160,16 @@ def test_get_health_rest( ], kind="kind_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.BackendServiceGroupHealth.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_health(request) # Establish that the response is the type that we expect. - assert isinstance(response, compute.BackendServiceGroupHealth) assert response.annotations == {"key_value": "value_value"} assert response.health_status == [ @@ -1176,7 +1183,7 @@ def test_get_health_rest_from_dict(): def test_get_health_rest_flattened(): - client = BackendServicesClient(credentials=credentials.AnonymousCredentials(),) + client = BackendServicesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1195,7 +1202,6 @@ def test_get_health_rest_flattened(): resource_group_reference_resource = compute.ResourceGroupReference( group="group_value" ) - client.get_health( project="project_value", backend_service="backend_service_value", @@ -1207,11 +1213,8 @@ def test_get_health_rest_flattened(): 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 "backend_service_value" in http_call[1] + str(body) - assert compute.ResourceGroupReference.to_json( resource_group_reference_resource, including_default_value_fields=False, @@ -1220,7 +1223,7 @@ def test_get_health_rest_flattened(): def test_get_health_rest_flattened_error(): - client = BackendServicesClient(credentials=credentials.AnonymousCredentials(),) + client = BackendServicesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1239,7 +1242,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertBackendServiceRequest ): client = BackendServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1274,17 +1277,16 @@ def test_insert_rest( 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" @@ -1318,7 +1320,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = BackendServicesClient(credentials=credentials.AnonymousCredentials(),) + client = BackendServicesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1335,7 +1337,6 @@ def test_insert_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. backend_service_resource = compute.BackendService(affinity_cookie_ttl_sec=2432) - client.insert( project="project_value", backend_service_resource=backend_service_resource, ) @@ -1345,9 +1346,7 @@ def test_insert_rest_flattened(): 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.BackendService.to_json( backend_service_resource, including_default_value_fields=False, @@ -1356,7 +1355,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = BackendServicesClient(credentials=credentials.AnonymousCredentials(),) + client = BackendServicesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1374,7 +1373,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListBackendServicesRequest ): client = BackendServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1392,17 +1391,16 @@ def test_list_rest( 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.BackendServiceList.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.BackendService(affinity_cookie_ttl_sec=2432)] @@ -1417,7 +1415,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = BackendServicesClient(credentials=credentials.AnonymousCredentials(),) + client = BackendServicesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1440,12 +1438,11 @@ def test_list_rest_flattened(): 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 = BackendServicesClient(credentials=credentials.AnonymousCredentials(),) + client = BackendServicesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1456,12 +1453,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = BackendServicesClient(credentials=credentials.AnonymousCredentials(),) + client = BackendServicesClient(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.BackendServiceList( items=[ @@ -1479,7 +1475,6 @@ def test_list_pager(): items=[compute.BackendService(), compute.BackendService(),], ), ) - # Two responses for two calls response = response + response @@ -1498,7 +1493,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.BackendService) for i in results) pages = list(client.list(request={}).pages) @@ -1510,7 +1504,7 @@ def test_patch_rest( transport: str = "rest", request_type=compute.PatchBackendServiceRequest ): client = BackendServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1545,17 +1539,16 @@ def test_patch_rest( 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" @@ -1589,7 +1582,7 @@ def test_patch_rest_from_dict(): def test_patch_rest_flattened(): - client = BackendServicesClient(credentials=credentials.AnonymousCredentials(),) + client = BackendServicesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1606,7 +1599,6 @@ def test_patch_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. backend_service_resource = compute.BackendService(affinity_cookie_ttl_sec=2432) - client.patch( project="project_value", backend_service="backend_service_value", @@ -1618,11 +1610,8 @@ def test_patch_rest_flattened(): 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 "backend_service_value" in http_call[1] + str(body) - assert compute.BackendService.to_json( backend_service_resource, including_default_value_fields=False, @@ -1631,7 +1620,7 @@ def test_patch_rest_flattened(): def test_patch_rest_flattened_error(): - client = BackendServicesClient(credentials=credentials.AnonymousCredentials(),) + client = BackendServicesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1650,7 +1639,7 @@ def test_set_security_policy_rest( transport: str = "rest", request_type=compute.SetSecurityPolicyBackendServiceRequest ): client = BackendServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1685,17 +1674,16 @@ def test_set_security_policy_rest( 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_security_policy(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" @@ -1729,7 +1717,7 @@ def test_set_security_policy_rest_from_dict(): def test_set_security_policy_rest_flattened(): - client = BackendServicesClient(credentials=credentials.AnonymousCredentials(),) + client = BackendServicesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1748,7 +1736,6 @@ def test_set_security_policy_rest_flattened(): security_policy_reference_resource = compute.SecurityPolicyReference( security_policy="security_policy_value" ) - client.set_security_policy( project="project_value", backend_service="backend_service_value", @@ -1760,11 +1747,8 @@ def test_set_security_policy_rest_flattened(): 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 "backend_service_value" in http_call[1] + str(body) - assert compute.SecurityPolicyReference.to_json( security_policy_reference_resource, including_default_value_fields=False, @@ -1773,7 +1757,7 @@ def test_set_security_policy_rest_flattened(): def test_set_security_policy_rest_flattened_error(): - client = BackendServicesClient(credentials=credentials.AnonymousCredentials(),) + client = BackendServicesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1792,7 +1776,7 @@ def test_update_rest( transport: str = "rest", request_type=compute.UpdateBackendServiceRequest ): client = BackendServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1827,17 +1811,16 @@ def test_update_rest( 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.update(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" @@ -1871,7 +1854,7 @@ def test_update_rest_from_dict(): def test_update_rest_flattened(): - client = BackendServicesClient(credentials=credentials.AnonymousCredentials(),) + client = BackendServicesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1888,7 +1871,6 @@ def test_update_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. backend_service_resource = compute.BackendService(affinity_cookie_ttl_sec=2432) - client.update( project="project_value", backend_service="backend_service_value", @@ -1900,11 +1882,8 @@ def test_update_rest_flattened(): 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 "backend_service_value" in http_call[1] + str(body) - assert compute.BackendService.to_json( backend_service_resource, including_default_value_fields=False, @@ -1913,7 +1892,7 @@ def test_update_rest_flattened(): def test_update_rest_flattened_error(): - client = BackendServicesClient(credentials=credentials.AnonymousCredentials(),) + client = BackendServicesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1931,16 +1910,16 @@ def test_update_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.BackendServicesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = BackendServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.BackendServicesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = BackendServicesClient( @@ -1950,7 +1929,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.BackendServicesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = BackendServicesClient( @@ -1961,7 +1940,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.BackendServicesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = BackendServicesClient(transport=transport) assert client.transport is transport @@ -1970,17 +1949,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.BackendServicesRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_backend_services_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.BackendServicesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1992,7 +1971,7 @@ def test_backend_services_base_transport(): ) as Transport: Transport.return_value = None transport = transports.BackendServicesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2015,15 +1994,40 @@ def test_backend_services_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_backend_services_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.backend_services.transports.BackendServicesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.BackendServicesTransport( + 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_backend_services_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.backend_services.transports.BackendServicesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.BackendServicesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2039,19 +2043,36 @@ def test_backend_services_base_transport_with_credentials_file(): def test_backend_services_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.backend_services.transports.BackendServicesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.BackendServicesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_backend_services_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + BackendServicesClient() + 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_backend_services_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) BackendServicesClient() adc.assert_called_once_with( scopes=( @@ -2063,7 +2084,7 @@ def test_backend_services_auth_adc(): def test_backend_services_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -2075,7 +2096,7 @@ def test_backend_services_http_transport_client_cert_source_for_mtls(): def test_backend_services_host_no_port(): client = BackendServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -2085,7 +2106,7 @@ def test_backend_services_host_no_port(): def test_backend_services_host_with_port(): client = BackendServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -2095,7 +2116,6 @@ def test_backend_services_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2116,7 +2136,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = BackendServicesClient.common_folder_path(folder) assert expected == actual @@ -2135,7 +2154,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = BackendServicesClient.common_organization_path(organization) assert expected == actual @@ -2154,7 +2172,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = BackendServicesClient.common_project_path(project) assert expected == actual @@ -2174,7 +2191,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2201,7 +2217,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.BackendServicesTransport, "_prep_wrapped_messages" ) as prep: client = BackendServicesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2210,6 +2226,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = BackendServicesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_disk_types.py b/tests/unit/gapic/compute_v1/test_disk_types.py index 5139ae814..04a81be73 100644 --- a/tests/unit/gapic/compute_v1/test_disk_types.py +++ b/tests/unit/gapic/compute_v1/test_disk_types.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -82,7 +111,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [DiskTypesClient,]) def test_disk_types_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -97,7 +126,7 @@ def test_disk_types_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [DiskTypesClient,]) def test_disk_types_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -136,7 +165,7 @@ def test_disk_types_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(DiskTypesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -372,7 +401,7 @@ def test_aggregated_list_rest( transport: str = "rest", request_type=compute.AggregatedListDiskTypesRequest ): client = DiskTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -397,17 +426,16 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.DiskTypeAggregatedList.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 == { @@ -427,7 +455,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = DiskTypesClient(credentials=credentials.AnonymousCredentials(),) + client = DiskTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -450,12 +478,11 @@ def test_aggregated_list_rest_flattened(): 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 = DiskTypesClient(credentials=credentials.AnonymousCredentials(),) + client = DiskTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -466,12 +493,11 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = DiskTypesClient(credentials=credentials.AnonymousCredentials(),) + client = DiskTypesClient(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.DiskTypeAggregatedList( items={ @@ -492,7 +518,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -514,7 +539,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -530,7 +554,7 @@ def test_aggregated_list_pager(): def test_get_rest(transport: str = "rest", request_type=compute.GetDiskTypeRequest): client = DiskTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -553,17 +577,16 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetDiskTypeReque valid_disk_size="valid_disk_size_value", zone="zone_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.DiskType.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.DiskType) assert response.creation_timestamp == "creation_timestamp_value" assert response.default_disk_size_gb == "default_disk_size_gb_value" @@ -583,7 +606,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = DiskTypesClient(credentials=credentials.AnonymousCredentials(),) + client = DiskTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -608,16 +631,13 @@ def test_get_rest_flattened(): 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 "disk_type_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = DiskTypesClient(credentials=credentials.AnonymousCredentials(),) + client = DiskTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -632,7 +652,7 @@ def test_get_rest_flattened_error(): def test_list_rest(transport: str = "rest", request_type=compute.ListDiskTypesRequest): client = DiskTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -650,17 +670,16 @@ def test_list_rest(transport: str = "rest", request_type=compute.ListDiskTypesRe 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.DiskTypeList.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 == [ @@ -677,7 +696,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = DiskTypesClient(credentials=credentials.AnonymousCredentials(),) + client = DiskTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -702,14 +721,12 @@ def test_list_rest_flattened(): 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) def test_list_rest_flattened_error(): - client = DiskTypesClient(credentials=credentials.AnonymousCredentials(),) + client = DiskTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -720,12 +737,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = DiskTypesClient(credentials=credentials.AnonymousCredentials(),) + client = DiskTypesClient(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.DiskTypeList( items=[compute.DiskType(), compute.DiskType(), compute.DiskType(),], @@ -735,7 +751,6 @@ def test_list_pager(): compute.DiskTypeList(items=[compute.DiskType(),], next_page_token="ghi",), compute.DiskTypeList(items=[compute.DiskType(), compute.DiskType(),],), ) - # Two responses for two calls response = response + response @@ -754,7 +769,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.DiskType) for i in results) pages = list(client.list(request={}).pages) @@ -765,16 +779,16 @@ def test_list_pager(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.DiskTypesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = DiskTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.DiskTypesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = DiskTypesClient( @@ -784,7 +798,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.DiskTypesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = DiskTypesClient( @@ -795,7 +809,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.DiskTypesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = DiskTypesClient(transport=transport) assert client.transport is transport @@ -804,17 +818,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.DiskTypesRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_disk_types_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.DiskTypesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -826,7 +840,7 @@ def test_disk_types_base_transport(): ) as Transport: Transport.return_value = None transport = transports.DiskTypesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -841,15 +855,41 @@ def test_disk_types_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_disk_types_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.disk_types.transports.DiskTypesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DiskTypesTransport( + 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.readonly", + "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_disk_types_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.disk_types.transports.DiskTypesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.DiskTypesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -866,19 +906,37 @@ def test_disk_types_base_transport_with_credentials_file(): def test_disk_types_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.disk_types.transports.DiskTypesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.DiskTypesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_disk_types_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + DiskTypesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/compute.readonly", + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_disk_types_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) DiskTypesClient() adc.assert_called_once_with( scopes=( @@ -891,7 +949,7 @@ def test_disk_types_auth_adc(): def test_disk_types_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -903,7 +961,7 @@ def test_disk_types_http_transport_client_cert_source_for_mtls(): def test_disk_types_host_no_port(): client = DiskTypesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -913,7 +971,7 @@ def test_disk_types_host_no_port(): def test_disk_types_host_with_port(): client = DiskTypesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -923,7 +981,6 @@ def test_disk_types_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -944,7 +1001,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = DiskTypesClient.common_folder_path(folder) assert expected == actual @@ -963,7 +1019,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = DiskTypesClient.common_organization_path(organization) assert expected == actual @@ -982,7 +1037,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = DiskTypesClient.common_project_path(project) assert expected == actual @@ -1002,7 +1056,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1029,7 +1082,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.DiskTypesTransport, "_prep_wrapped_messages" ) as prep: client = DiskTypesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1038,6 +1091,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = DiskTypesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_disks.py b/tests/unit/gapic/compute_v1/test_disks.py index c9709e1a6..9c92cd913 100644 --- a/tests/unit/gapic/compute_v1/test_disks.py +++ b/tests/unit/gapic/compute_v1/test_disks.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,57 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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 +# - 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", +) + +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(): @@ -81,7 +106,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [DisksClient,]) def test_disks_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -96,7 +121,7 @@ def test_disks_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [DisksClient,]) def test_disks_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -133,7 +158,7 @@ def test_disks_client_get_transport_class(): def test_disks_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(DisksClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -369,7 +394,7 @@ def test_add_resource_policies_rest( transport: str = "rest", request_type=compute.AddResourcePoliciesDiskRequest ): client = DisksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -404,17 +429,16 @@ def test_add_resource_policies_rest( 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_resource_policies(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" @@ -448,7 +472,7 @@ def test_add_resource_policies_rest_from_dict(): def test_add_resource_policies_rest_flattened(): - client = DisksClient(credentials=credentials.AnonymousCredentials(),) + client = DisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -467,7 +491,6 @@ def test_add_resource_policies_rest_flattened(): disks_add_resource_policies_request_resource = compute.DisksAddResourcePoliciesRequest( resource_policies=["resource_policies_value"] ) - client.add_resource_policies( project="project_value", zone="zone_value", @@ -480,13 +503,9 @@ def test_add_resource_policies_rest_flattened(): 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 "disk_value" in http_call[1] + str(body) - assert compute.DisksAddResourcePoliciesRequest.to_json( disks_add_resource_policies_request_resource, including_default_value_fields=False, @@ -495,7 +514,7 @@ def test_add_resource_policies_rest_flattened(): def test_add_resource_policies_rest_flattened_error(): - client = DisksClient(credentials=credentials.AnonymousCredentials(),) + client = DisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -515,7 +534,7 @@ def test_aggregated_list_rest( transport: str = "rest", request_type=compute.AggregatedListDisksRequest ): client = DisksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -538,17 +557,16 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.DiskAggregatedList.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 == { @@ -568,7 +586,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = DisksClient(credentials=credentials.AnonymousCredentials(),) + client = DisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -591,12 +609,11 @@ def test_aggregated_list_rest_flattened(): 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 = DisksClient(credentials=credentials.AnonymousCredentials(),) + client = DisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -607,12 +624,11 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = DisksClient(credentials=credentials.AnonymousCredentials(),) + client = DisksClient(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.DiskAggregatedList( items={ @@ -630,7 +646,6 @@ def test_aggregated_list_pager(): items={"h": compute.DisksScopedList(), "i": compute.DisksScopedList(),}, ), ) - # Two responses for two calls response = response + response @@ -652,7 +667,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -670,7 +684,7 @@ def test_create_snapshot_rest( transport: str = "rest", request_type=compute.CreateSnapshotDiskRequest ): client = DisksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -705,17 +719,16 @@ def test_create_snapshot_rest( 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.create_snapshot(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" @@ -749,7 +762,7 @@ def test_create_snapshot_rest_from_dict(): def test_create_snapshot_rest_flattened(): - client = DisksClient(credentials=credentials.AnonymousCredentials(),) + client = DisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -766,7 +779,6 @@ def test_create_snapshot_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. snapshot_resource = compute.Snapshot(auto_created=True) - client.create_snapshot( project="project_value", zone="zone_value", @@ -779,13 +791,9 @@ def test_create_snapshot_rest_flattened(): 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 "disk_value" in http_call[1] + str(body) - assert compute.Snapshot.to_json( snapshot_resource, including_default_value_fields=False, @@ -794,7 +802,7 @@ def test_create_snapshot_rest_flattened(): def test_create_snapshot_rest_flattened_error(): - client = DisksClient(credentials=credentials.AnonymousCredentials(),) + client = DisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -810,7 +818,7 @@ def test_create_snapshot_rest_flattened_error(): def test_delete_rest(transport: str = "rest", request_type=compute.DeleteDiskRequest): client = DisksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -845,17 +853,16 @@ def test_delete_rest(transport: str = "rest", request_type=compute.DeleteDiskReq 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" @@ -889,7 +896,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = DisksClient(credentials=credentials.AnonymousCredentials(),) + client = DisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -914,16 +921,13 @@ def test_delete_rest_flattened(): 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 "disk_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = DisksClient(credentials=credentials.AnonymousCredentials(),) + client = DisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -938,7 +942,7 @@ def test_delete_rest_flattened_error(): def test_get_rest(transport: str = "rest", request_type=compute.GetDiskRequest): client = DisksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -992,17 +996,16 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetDiskRequest): users=["users_value"], zone="zone_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.Disk.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.Disk) assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" @@ -1053,7 +1056,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = DisksClient(credentials=credentials.AnonymousCredentials(),) + client = DisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1078,16 +1081,13 @@ def test_get_rest_flattened(): 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 "disk_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = DisksClient(credentials=credentials.AnonymousCredentials(),) + client = DisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1104,7 +1104,7 @@ def test_get_iam_policy_rest( transport: str = "rest", request_type=compute.GetIamPolicyDiskRequest ): client = DisksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1130,17 +1130,16 @@ def test_get_iam_policy_rest( 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( @@ -1151,7 +1150,6 @@ def test_get_iam_policy_rest( ] 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 @@ -1162,7 +1160,7 @@ def test_get_iam_policy_rest_from_dict(): def test_get_iam_policy_rest_flattened(): - client = DisksClient(credentials=credentials.AnonymousCredentials(),) + client = DisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1187,16 +1185,13 @@ def test_get_iam_policy_rest_flattened(): 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 "resource_value" in http_call[1] + str(body) def test_get_iam_policy_rest_flattened_error(): - client = DisksClient(credentials=credentials.AnonymousCredentials(),) + client = DisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1211,7 +1206,7 @@ def test_get_iam_policy_rest_flattened_error(): def test_insert_rest(transport: str = "rest", request_type=compute.InsertDiskRequest): client = DisksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1246,17 +1241,16 @@ def test_insert_rest(transport: str = "rest", request_type=compute.InsertDiskReq 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" @@ -1290,7 +1284,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = DisksClient(credentials=credentials.AnonymousCredentials(),) + client = DisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1307,7 +1301,6 @@ def test_insert_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. disk_resource = compute.Disk(creation_timestamp="creation_timestamp_value") - client.insert( project="project_value", zone="zone_value", disk_resource=disk_resource, ) @@ -1317,11 +1310,8 @@ def test_insert_rest_flattened(): 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.Disk.to_json( disk_resource, including_default_value_fields=False, @@ -1330,7 +1320,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = DisksClient(credentials=credentials.AnonymousCredentials(),) + client = DisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1345,7 +1335,7 @@ def test_insert_rest_flattened_error(): def test_list_rest(transport: str = "rest", request_type=compute.ListDisksRequest): client = DisksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1363,17 +1353,16 @@ def test_list_rest(transport: str = "rest", request_type=compute.ListDisksReques 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.DiskList.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 == [ @@ -1390,7 +1379,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = DisksClient(credentials=credentials.AnonymousCredentials(),) + client = DisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1415,14 +1404,12 @@ def test_list_rest_flattened(): 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) def test_list_rest_flattened_error(): - client = DisksClient(credentials=credentials.AnonymousCredentials(),) + client = DisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1433,12 +1420,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = DisksClient(credentials=credentials.AnonymousCredentials(),) + client = DisksClient(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.DiskList( items=[compute.Disk(), compute.Disk(), compute.Disk(),], @@ -1448,7 +1434,6 @@ def test_list_pager(): compute.DiskList(items=[compute.Disk(),], next_page_token="ghi",), compute.DiskList(items=[compute.Disk(), compute.Disk(),],), ) - # Two responses for two calls response = response + response @@ -1467,7 +1452,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.Disk) for i in results) pages = list(client.list(request={}).pages) @@ -1479,7 +1463,7 @@ def test_remove_resource_policies_rest( transport: str = "rest", request_type=compute.RemoveResourcePoliciesDiskRequest ): client = DisksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1514,17 +1498,16 @@ def test_remove_resource_policies_rest( 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_resource_policies(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" @@ -1558,7 +1541,7 @@ def test_remove_resource_policies_rest_from_dict(): def test_remove_resource_policies_rest_flattened(): - client = DisksClient(credentials=credentials.AnonymousCredentials(),) + client = DisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1577,7 +1560,6 @@ def test_remove_resource_policies_rest_flattened(): disks_remove_resource_policies_request_resource = compute.DisksRemoveResourcePoliciesRequest( resource_policies=["resource_policies_value"] ) - client.remove_resource_policies( project="project_value", zone="zone_value", @@ -1590,13 +1572,9 @@ def test_remove_resource_policies_rest_flattened(): 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 "disk_value" in http_call[1] + str(body) - assert compute.DisksRemoveResourcePoliciesRequest.to_json( disks_remove_resource_policies_request_resource, including_default_value_fields=False, @@ -1605,7 +1583,7 @@ def test_remove_resource_policies_rest_flattened(): def test_remove_resource_policies_rest_flattened_error(): - client = DisksClient(credentials=credentials.AnonymousCredentials(),) + client = DisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1623,7 +1601,7 @@ def test_remove_resource_policies_rest_flattened_error(): def test_resize_rest(transport: str = "rest", request_type=compute.ResizeDiskRequest): client = DisksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1658,17 +1636,16 @@ def test_resize_rest(transport: str = "rest", request_type=compute.ResizeDiskReq 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.resize(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" @@ -1702,7 +1679,7 @@ def test_resize_rest_from_dict(): def test_resize_rest_flattened(): - client = DisksClient(credentials=credentials.AnonymousCredentials(),) + client = DisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1721,7 +1698,6 @@ def test_resize_rest_flattened(): disks_resize_request_resource = compute.DisksResizeRequest( size_gb="size_gb_value" ) - client.resize( project="project_value", zone="zone_value", @@ -1734,13 +1710,9 @@ def test_resize_rest_flattened(): 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 "disk_value" in http_call[1] + str(body) - assert compute.DisksResizeRequest.to_json( disks_resize_request_resource, including_default_value_fields=False, @@ -1749,7 +1721,7 @@ def test_resize_rest_flattened(): def test_resize_rest_flattened_error(): - client = DisksClient(credentials=credentials.AnonymousCredentials(),) + client = DisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1769,7 +1741,7 @@ def test_set_iam_policy_rest( transport: str = "rest", request_type=compute.SetIamPolicyDiskRequest ): client = DisksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1795,17 +1767,16 @@ def test_set_iam_policy_rest( 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( @@ -1816,7 +1787,6 @@ def test_set_iam_policy_rest( ] 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 @@ -1827,7 +1797,7 @@ def test_set_iam_policy_rest_from_dict(): def test_set_iam_policy_rest_flattened(): - client = DisksClient(credentials=credentials.AnonymousCredentials(),) + client = DisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1846,7 +1816,6 @@ def test_set_iam_policy_rest_flattened(): zone_set_policy_request_resource = compute.ZoneSetPolicyRequest( bindings=[compute.Binding(binding_id="binding_id_value")] ) - client.set_iam_policy( project="project_value", zone="zone_value", @@ -1859,13 +1828,9 @@ def test_set_iam_policy_rest_flattened(): 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 "resource_value" in http_call[1] + str(body) - assert compute.ZoneSetPolicyRequest.to_json( zone_set_policy_request_resource, including_default_value_fields=False, @@ -1874,7 +1839,7 @@ def test_set_iam_policy_rest_flattened(): def test_set_iam_policy_rest_flattened_error(): - client = DisksClient(credentials=credentials.AnonymousCredentials(),) + client = DisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1894,7 +1859,7 @@ def test_set_labels_rest( transport: str = "rest", request_type=compute.SetLabelsDiskRequest ): client = DisksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1929,17 +1894,16 @@ def test_set_labels_rest( 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" @@ -1973,7 +1937,7 @@ def test_set_labels_rest_from_dict(): def test_set_labels_rest_flattened(): - client = DisksClient(credentials=credentials.AnonymousCredentials(),) + client = DisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1992,7 +1956,6 @@ def test_set_labels_rest_flattened(): zone_set_labels_request_resource = compute.ZoneSetLabelsRequest( label_fingerprint="label_fingerprint_value" ) - client.set_labels( project="project_value", zone="zone_value", @@ -2005,13 +1968,9 @@ def test_set_labels_rest_flattened(): 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 "resource_value" in http_call[1] + str(body) - assert compute.ZoneSetLabelsRequest.to_json( zone_set_labels_request_resource, including_default_value_fields=False, @@ -2020,7 +1979,7 @@ def test_set_labels_rest_flattened(): def test_set_labels_rest_flattened_error(): - client = DisksClient(credentials=credentials.AnonymousCredentials(),) + client = DisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2040,7 +1999,7 @@ def test_test_iam_permissions_rest( transport: str = "rest", request_type=compute.TestIamPermissionsDiskRequest ): client = DisksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2053,17 +2012,16 @@ def test_test_iam_permissions_rest( 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"] @@ -2073,7 +2031,7 @@ def test_test_iam_permissions_rest_from_dict(): def test_test_iam_permissions_rest_flattened(): - client = DisksClient(credentials=credentials.AnonymousCredentials(),) + client = DisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -2092,7 +2050,6 @@ def test_test_iam_permissions_rest_flattened(): test_permissions_request_resource = compute.TestPermissionsRequest( permissions=["permissions_value"] ) - client.test_iam_permissions( project="project_value", zone="zone_value", @@ -2105,13 +2062,9 @@ def test_test_iam_permissions_rest_flattened(): 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 "resource_value" in http_call[1] + str(body) - assert compute.TestPermissionsRequest.to_json( test_permissions_request_resource, including_default_value_fields=False, @@ -2120,7 +2073,7 @@ def test_test_iam_permissions_rest_flattened(): def test_test_iam_permissions_rest_flattened_error(): - client = DisksClient(credentials=credentials.AnonymousCredentials(),) + client = DisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2139,16 +2092,16 @@ def test_test_iam_permissions_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.DisksRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = DisksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.DisksRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = DisksClient( @@ -2158,7 +2111,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.DisksRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = DisksClient( @@ -2169,7 +2122,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.DisksRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = DisksClient(transport=transport) assert client.transport is transport @@ -2178,17 +2131,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.DisksRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_disks_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.DisksTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2200,7 +2153,7 @@ def test_disks_base_transport(): ) as Transport: Transport.return_value = None transport = transports.DisksTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2225,15 +2178,40 @@ def test_disks_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_disks_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.disks.transports.DisksTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DisksTransport( + 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_disks_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.disks.transports.DisksTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.DisksTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2249,19 +2227,36 @@ def test_disks_base_transport_with_credentials_file(): def test_disks_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.disks.transports.DisksTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.DisksTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_disks_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + DisksClient() + 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_disks_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) DisksClient() adc.assert_called_once_with( scopes=( @@ -2273,7 +2268,7 @@ def test_disks_auth_adc(): def test_disks_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -2285,7 +2280,7 @@ def test_disks_http_transport_client_cert_source_for_mtls(): def test_disks_host_no_port(): client = DisksClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -2295,7 +2290,7 @@ def test_disks_host_no_port(): def test_disks_host_with_port(): client = DisksClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -2305,7 +2300,6 @@ def test_disks_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2326,7 +2320,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = DisksClient.common_folder_path(folder) assert expected == actual @@ -2345,7 +2338,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = DisksClient.common_organization_path(organization) assert expected == actual @@ -2364,7 +2356,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = DisksClient.common_project_path(project) assert expected == actual @@ -2384,7 +2375,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2409,13 +2399,13 @@ def test_client_withDEFAULT_CLIENT_INFO(): with mock.patch.object(transports.DisksTransport, "_prep_wrapped_messages") as prep: client = DisksClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) with mock.patch.object(transports.DisksTransport, "_prep_wrapped_messages") as prep: transport_class = DisksClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_external_vpn_gateways.py b/tests/unit/gapic/compute_v1/test_external_vpn_gateways.py index 819beb928..694c39b0b 100644 --- a/tests/unit/gapic/compute_v1/test_external_vpn_gateways.py +++ b/tests/unit/gapic/compute_v1/test_external_vpn_gateways.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,33 +13,63 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.compute_v1.services.external_vpn_gateways import ( ExternalVpnGatewaysClient, ) 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, +) 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 +# - 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", +) + +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(): @@ -90,7 +119,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [ExternalVpnGatewaysClient,]) def test_external_vpn_gateways_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -105,7 +134,7 @@ def test_external_vpn_gateways_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [ExternalVpnGatewaysClient,]) def test_external_vpn_gateways_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -146,7 +175,7 @@ def test_external_vpn_gateways_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(ExternalVpnGatewaysClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -394,7 +423,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteExternalVpnGatewayRequest ): client = ExternalVpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -429,17 +458,16 @@ def test_delete_rest( 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" @@ -473,7 +501,9 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = ExternalVpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = ExternalVpnGatewaysClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -498,14 +528,14 @@ def test_delete_rest_flattened(): 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 "external_vpn_gateway_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = ExternalVpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = ExternalVpnGatewaysClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -521,7 +551,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetExternalVpnGatewayRequest ): client = ExternalVpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -543,17 +573,16 @@ def test_get_rest( redundancy_type=compute.ExternalVpnGateway.RedundancyType.FOUR_IPS_REDUNDANCY, self_link="self_link_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.ExternalVpnGateway.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.ExternalVpnGateway) assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" @@ -575,7 +604,9 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = ExternalVpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = ExternalVpnGatewaysClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -600,14 +631,14 @@ def test_get_rest_flattened(): 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 "external_vpn_gateway_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = ExternalVpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = ExternalVpnGatewaysClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -623,7 +654,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertExternalVpnGatewayRequest ): client = ExternalVpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -658,17 +689,16 @@ def test_insert_rest( 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" @@ -702,7 +732,9 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = ExternalVpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = ExternalVpnGatewaysClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -721,7 +753,6 @@ def test_insert_rest_flattened(): external_vpn_gateway_resource = compute.ExternalVpnGateway( creation_timestamp="creation_timestamp_value" ) - client.insert( project="project_value", external_vpn_gateway_resource=external_vpn_gateway_resource, @@ -732,9 +763,7 @@ def test_insert_rest_flattened(): 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.ExternalVpnGateway.to_json( external_vpn_gateway_resource, including_default_value_fields=False, @@ -743,7 +772,9 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = ExternalVpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = ExternalVpnGatewaysClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -761,7 +792,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListExternalVpnGatewaysRequest ): client = ExternalVpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -784,17 +815,16 @@ def test_list_rest( 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.ExternalVpnGatewayList.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.etag == "etag_value" assert response.id == "id_value" @@ -812,7 +842,9 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = ExternalVpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = ExternalVpnGatewaysClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -835,12 +867,13 @@ def test_list_rest_flattened(): 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 = ExternalVpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = ExternalVpnGatewaysClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -851,12 +884,13 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = ExternalVpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = ExternalVpnGatewaysClient( + 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.ExternalVpnGatewayList( items=[ @@ -874,7 +908,6 @@ def test_list_pager(): items=[compute.ExternalVpnGateway(), compute.ExternalVpnGateway(),], ), ) - # Two responses for two calls response = response + response @@ -893,7 +926,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.ExternalVpnGateway) for i in results) pages = list(client.list(request={}).pages) @@ -905,7 +937,7 @@ def test_set_labels_rest( transport: str = "rest", request_type=compute.SetLabelsExternalVpnGatewayRequest ): client = ExternalVpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -940,17 +972,16 @@ def test_set_labels_rest( 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" @@ -984,7 +1015,9 @@ def test_set_labels_rest_from_dict(): def test_set_labels_rest_flattened(): - client = ExternalVpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = ExternalVpnGatewaysClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1003,7 +1036,6 @@ def test_set_labels_rest_flattened(): global_set_labels_request_resource = compute.GlobalSetLabelsRequest( label_fingerprint="label_fingerprint_value" ) - client.set_labels( project="project_value", resource="resource_value", @@ -1015,11 +1047,8 @@ def test_set_labels_rest_flattened(): 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, @@ -1028,7 +1057,9 @@ def test_set_labels_rest_flattened(): def test_set_labels_rest_flattened_error(): - client = ExternalVpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = ExternalVpnGatewaysClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1048,7 +1079,7 @@ def test_test_iam_permissions_rest( request_type=compute.TestIamPermissionsExternalVpnGatewayRequest, ): client = ExternalVpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1061,17 +1092,16 @@ def test_test_iam_permissions_rest( 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"] @@ -1081,7 +1111,9 @@ def test_test_iam_permissions_rest_from_dict(): def test_test_iam_permissions_rest_flattened(): - client = ExternalVpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = ExternalVpnGatewaysClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1100,7 +1132,6 @@ def test_test_iam_permissions_rest_flattened(): test_permissions_request_resource = compute.TestPermissionsRequest( permissions=["permissions_value"] ) - client.test_iam_permissions( project="project_value", resource="resource_value", @@ -1112,11 +1143,8 @@ def test_test_iam_permissions_rest_flattened(): 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.TestPermissionsRequest.to_json( test_permissions_request_resource, including_default_value_fields=False, @@ -1125,7 +1153,9 @@ def test_test_iam_permissions_rest_flattened(): def test_test_iam_permissions_rest_flattened_error(): - client = ExternalVpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = ExternalVpnGatewaysClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1143,16 +1173,16 @@ def test_test_iam_permissions_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ExternalVpnGatewaysRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ExternalVpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.ExternalVpnGatewaysRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ExternalVpnGatewaysClient( @@ -1162,7 +1192,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ExternalVpnGatewaysRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ExternalVpnGatewaysClient( @@ -1173,7 +1203,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ExternalVpnGatewaysRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ExternalVpnGatewaysClient(transport=transport) assert client.transport is transport @@ -1184,17 +1214,17 @@ def test_transport_instance(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_external_vpn_gateways_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ExternalVpnGatewaysTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1206,7 +1236,7 @@ def test_external_vpn_gateways_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ExternalVpnGatewaysTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1224,15 +1254,40 @@ def test_external_vpn_gateways_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_external_vpn_gateways_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.external_vpn_gateways.transports.ExternalVpnGatewaysTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ExternalVpnGatewaysTransport( + 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_external_vpn_gateways_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.external_vpn_gateways.transports.ExternalVpnGatewaysTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ExternalVpnGatewaysTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1248,19 +1303,36 @@ def test_external_vpn_gateways_base_transport_with_credentials_file(): def test_external_vpn_gateways_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.external_vpn_gateways.transports.ExternalVpnGatewaysTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ExternalVpnGatewaysTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_external_vpn_gateways_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ExternalVpnGatewaysClient() + 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_external_vpn_gateways_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) ExternalVpnGatewaysClient() adc.assert_called_once_with( scopes=( @@ -1272,7 +1344,7 @@ def test_external_vpn_gateways_auth_adc(): def test_external_vpn_gateways_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1284,7 +1356,7 @@ def test_external_vpn_gateways_http_transport_client_cert_source_for_mtls(): def test_external_vpn_gateways_host_no_port(): client = ExternalVpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1294,7 +1366,7 @@ def test_external_vpn_gateways_host_no_port(): def test_external_vpn_gateways_host_with_port(): client = ExternalVpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1304,7 +1376,6 @@ def test_external_vpn_gateways_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1325,7 +1396,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = ExternalVpnGatewaysClient.common_folder_path(folder) assert expected == actual @@ -1344,7 +1414,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = ExternalVpnGatewaysClient.common_organization_path(organization) assert expected == actual @@ -1363,7 +1432,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = ExternalVpnGatewaysClient.common_project_path(project) assert expected == actual @@ -1383,7 +1451,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1410,7 +1477,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ExternalVpnGatewaysTransport, "_prep_wrapped_messages" ) as prep: client = ExternalVpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1419,6 +1486,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ExternalVpnGatewaysClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_firewalls.py b/tests/unit/gapic/compute_v1/test_firewalls.py index 42b4c801b..e5973a5fa 100644 --- a/tests/unit/gapic/compute_v1/test_firewalls.py +++ b/tests/unit/gapic/compute_v1/test_firewalls.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,59 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -82,7 +109,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [FirewallsClient,]) def test_firewalls_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -97,7 +124,7 @@ def test_firewalls_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [FirewallsClient,]) def test_firewalls_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -134,7 +161,7 @@ def test_firewalls_client_get_transport_class(): def test_firewalls_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(FirewallsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -370,7 +397,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteFirewallRequest ): client = FirewallsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -405,17 +432,16 @@ def test_delete_rest( 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" @@ -449,7 +475,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = FirewallsClient(credentials=credentials.AnonymousCredentials(),) + client = FirewallsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -474,14 +500,12 @@ def test_delete_rest_flattened(): 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 "firewall_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = FirewallsClient(credentials=credentials.AnonymousCredentials(),) + client = FirewallsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -495,7 +519,7 @@ def test_delete_rest_flattened_error(): def test_get_rest(transport: str = "rest", request_type=compute.GetFirewallRequest): client = FirewallsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -526,17 +550,16 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetFirewallReque target_service_accounts=["target_service_accounts_value"], target_tags=["target_tags_value"], ) + # Wrap the value into a proper Response obj json_return_value = compute.Firewall.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.Firewall) assert response.allowed == [compute.Allowed(i_p_protocol="i_p_protocol_value")] assert response.creation_timestamp == "creation_timestamp_value" @@ -544,7 +567,6 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetFirewallReque assert response.description == "description_value" assert response.destination_ranges == ["destination_ranges_value"] assert response.direction == compute.Firewall.Direction.EGRESS - assert response.disabled is True assert response.id == "id_value" assert response.kind == "kind_value" @@ -565,7 +587,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = FirewallsClient(credentials=credentials.AnonymousCredentials(),) + client = FirewallsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -590,14 +612,12 @@ def test_get_rest_flattened(): 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 "firewall_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = FirewallsClient(credentials=credentials.AnonymousCredentials(),) + client = FirewallsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -613,7 +633,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertFirewallRequest ): client = FirewallsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -648,17 +668,16 @@ def test_insert_rest( 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" @@ -692,7 +711,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = FirewallsClient(credentials=credentials.AnonymousCredentials(),) + client = FirewallsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -711,7 +730,6 @@ def test_insert_rest_flattened(): firewall_resource = compute.Firewall( allowed=[compute.Allowed(i_p_protocol="i_p_protocol_value")] ) - client.insert( project="project_value", firewall_resource=firewall_resource, ) @@ -721,9 +739,7 @@ def test_insert_rest_flattened(): 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.Firewall.to_json( firewall_resource, including_default_value_fields=False, @@ -732,7 +748,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = FirewallsClient(credentials=credentials.AnonymousCredentials(),) + client = FirewallsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -748,7 +764,7 @@ def test_insert_rest_flattened_error(): def test_list_rest(transport: str = "rest", request_type=compute.ListFirewallsRequest): client = FirewallsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -770,17 +786,16 @@ def test_list_rest(transport: str = "rest", request_type=compute.ListFirewallsRe 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.FirewallList.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 == [ @@ -797,7 +812,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = FirewallsClient(credentials=credentials.AnonymousCredentials(),) + client = FirewallsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -820,12 +835,11 @@ def test_list_rest_flattened(): 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 = FirewallsClient(credentials=credentials.AnonymousCredentials(),) + client = FirewallsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -836,12 +850,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = FirewallsClient(credentials=credentials.AnonymousCredentials(),) + client = FirewallsClient(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.FirewallList( items=[compute.Firewall(), compute.Firewall(), compute.Firewall(),], @@ -851,7 +864,6 @@ def test_list_pager(): compute.FirewallList(items=[compute.Firewall(),], next_page_token="ghi",), compute.FirewallList(items=[compute.Firewall(), compute.Firewall(),],), ) - # Two responses for two calls response = response + response @@ -870,7 +882,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.Firewall) for i in results) pages = list(client.list(request={}).pages) @@ -880,7 +891,7 @@ def test_list_pager(): def test_patch_rest(transport: str = "rest", request_type=compute.PatchFirewallRequest): client = FirewallsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -915,17 +926,16 @@ def test_patch_rest(transport: str = "rest", request_type=compute.PatchFirewallR 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" @@ -959,7 +969,7 @@ def test_patch_rest_from_dict(): def test_patch_rest_flattened(): - client = FirewallsClient(credentials=credentials.AnonymousCredentials(),) + client = FirewallsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -978,7 +988,6 @@ def test_patch_rest_flattened(): firewall_resource = compute.Firewall( allowed=[compute.Allowed(i_p_protocol="i_p_protocol_value")] ) - client.patch( project="project_value", firewall="firewall_value", @@ -990,11 +999,8 @@ def test_patch_rest_flattened(): 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 "firewall_value" in http_call[1] + str(body) - assert compute.Firewall.to_json( firewall_resource, including_default_value_fields=False, @@ -1003,7 +1009,7 @@ def test_patch_rest_flattened(): def test_patch_rest_flattened_error(): - client = FirewallsClient(credentials=credentials.AnonymousCredentials(),) + client = FirewallsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1022,7 +1028,7 @@ def test_update_rest( transport: str = "rest", request_type=compute.UpdateFirewallRequest ): client = FirewallsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1057,17 +1063,16 @@ def test_update_rest( 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.update(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" @@ -1101,7 +1106,7 @@ def test_update_rest_from_dict(): def test_update_rest_flattened(): - client = FirewallsClient(credentials=credentials.AnonymousCredentials(),) + client = FirewallsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1120,7 +1125,6 @@ def test_update_rest_flattened(): firewall_resource = compute.Firewall( allowed=[compute.Allowed(i_p_protocol="i_p_protocol_value")] ) - client.update( project="project_value", firewall="firewall_value", @@ -1132,11 +1136,8 @@ def test_update_rest_flattened(): 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 "firewall_value" in http_call[1] + str(body) - assert compute.Firewall.to_json( firewall_resource, including_default_value_fields=False, @@ -1145,7 +1146,7 @@ def test_update_rest_flattened(): def test_update_rest_flattened_error(): - client = FirewallsClient(credentials=credentials.AnonymousCredentials(),) + client = FirewallsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1163,16 +1164,16 @@ def test_update_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.FirewallsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = FirewallsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.FirewallsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = FirewallsClient( @@ -1182,7 +1183,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.FirewallsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = FirewallsClient( @@ -1193,7 +1194,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.FirewallsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = FirewallsClient(transport=transport) assert client.transport is transport @@ -1202,17 +1203,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.FirewallsRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_firewalls_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.FirewallsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1224,7 +1225,7 @@ def test_firewalls_base_transport(): ) as Transport: Transport.return_value = None transport = transports.FirewallsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1242,15 +1243,40 @@ def test_firewalls_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_firewalls_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.firewalls.transports.FirewallsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FirewallsTransport( + 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_firewalls_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.firewalls.transports.FirewallsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.FirewallsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1266,19 +1292,36 @@ def test_firewalls_base_transport_with_credentials_file(): def test_firewalls_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.firewalls.transports.FirewallsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.FirewallsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_firewalls_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + FirewallsClient() + 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_firewalls_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) FirewallsClient() adc.assert_called_once_with( scopes=( @@ -1290,7 +1333,7 @@ def test_firewalls_auth_adc(): def test_firewalls_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1302,7 +1345,7 @@ def test_firewalls_http_transport_client_cert_source_for_mtls(): def test_firewalls_host_no_port(): client = FirewallsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1312,7 +1355,7 @@ def test_firewalls_host_no_port(): def test_firewalls_host_with_port(): client = FirewallsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1322,7 +1365,6 @@ def test_firewalls_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1343,7 +1385,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = FirewallsClient.common_folder_path(folder) assert expected == actual @@ -1362,7 +1403,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = FirewallsClient.common_organization_path(organization) assert expected == actual @@ -1381,7 +1421,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = FirewallsClient.common_project_path(project) assert expected == actual @@ -1401,7 +1440,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1428,7 +1466,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.FirewallsTransport, "_prep_wrapped_messages" ) as prep: client = FirewallsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1437,6 +1475,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = FirewallsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_forwarding_rules.py b/tests/unit/gapic/compute_v1/test_forwarding_rules.py index 9ca266088..845c9270e 100644 --- a/tests/unit/gapic/compute_v1/test_forwarding_rules.py +++ b/tests/unit/gapic/compute_v1/test_forwarding_rules.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -87,7 +116,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [ForwardingRulesClient,]) def test_forwarding_rules_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -102,7 +131,7 @@ def test_forwarding_rules_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [ForwardingRulesClient,]) def test_forwarding_rules_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -143,7 +172,7 @@ def test_forwarding_rules_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(ForwardingRulesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -391,7 +420,7 @@ def test_aggregated_list_rest( transport: str = "rest", request_type=compute.AggregatedListForwardingRulesRequest ): client = ForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -414,17 +443,16 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.ForwardingRuleAggregatedList.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 == { @@ -444,7 +472,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = ForwardingRulesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -467,12 +495,11 @@ def test_aggregated_list_rest_flattened(): 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 = ForwardingRulesClient(credentials=credentials.AnonymousCredentials(),) + client = ForwardingRulesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -483,12 +510,11 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = ForwardingRulesClient(credentials=credentials.AnonymousCredentials(),) + 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: # Set the response as a series of pages - response = ( compute.ForwardingRuleAggregatedList( items={ @@ -510,7 +536,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -534,7 +559,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -555,7 +579,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteForwardingRuleRequest ): client = ForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -590,17 +614,16 @@ def test_delete_rest( 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" @@ -634,7 +657,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = ForwardingRulesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -661,16 +684,13 @@ def test_delete_rest_flattened(): 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 "forwarding_rule_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = ForwardingRulesClient(credentials=credentials.AnonymousCredentials(),) + client = ForwardingRulesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -687,7 +707,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetForwardingRuleRequest ): client = ForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -728,21 +748,18 @@ def test_get_rest( subnetwork="subnetwork_value", target="target_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.ForwardingRule.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.ForwardingRule) - 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" @@ -752,7 +769,6 @@ def test_get_rest( 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 ( @@ -782,7 +798,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = ForwardingRulesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -809,16 +825,13 @@ def test_get_rest_flattened(): 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 "forwarding_rule_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = ForwardingRulesClient(credentials=credentials.AnonymousCredentials(),) + client = ForwardingRulesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -835,7 +848,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertForwardingRuleRequest ): client = ForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -870,17 +883,16 @@ def test_insert_rest( 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" @@ -914,7 +926,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = ForwardingRulesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -931,7 +943,6 @@ 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) - client.insert( project="project_value", region="region_value", @@ -943,11 +954,8 @@ def test_insert_rest_flattened(): 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.ForwardingRule.to_json( forwarding_rule_resource, including_default_value_fields=False, @@ -956,7 +964,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = ForwardingRulesClient(credentials=credentials.AnonymousCredentials(),) + client = ForwardingRulesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -973,7 +981,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListForwardingRulesRequest ): client = ForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -991,17 +999,16 @@ def test_list_rest( 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.ForwardingRuleList.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.ForwardingRule(all_ports=True)] @@ -1016,7 +1023,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = ForwardingRulesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -1041,14 +1048,12 @@ def test_list_rest_flattened(): 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 = ForwardingRulesClient(credentials=credentials.AnonymousCredentials(),) + client = ForwardingRulesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1061,12 +1066,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = ForwardingRulesClient(credentials=credentials.AnonymousCredentials(),) + 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: # Set the response as a series of pages - response = ( compute.ForwardingRuleList( items=[ @@ -1084,7 +1088,6 @@ def test_list_pager(): items=[compute.ForwardingRule(), compute.ForwardingRule(),], ), ) - # Two responses for two calls response = response + response @@ -1103,7 +1106,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.ForwardingRule) for i in results) pages = list(client.list(request={}).pages) @@ -1115,7 +1117,7 @@ def test_patch_rest( transport: str = "rest", request_type=compute.PatchForwardingRuleRequest ): client = ForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1150,17 +1152,16 @@ def test_patch_rest( 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" @@ -1194,7 +1195,7 @@ def test_patch_rest_from_dict(): def test_patch_rest_flattened(): - client = ForwardingRulesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -1211,7 +1212,6 @@ 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) - client.patch( project="project_value", region="region_value", @@ -1224,13 +1224,9 @@ def test_patch_rest_flattened(): 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 "forwarding_rule_value" in http_call[1] + str(body) - assert compute.ForwardingRule.to_json( forwarding_rule_resource, including_default_value_fields=False, @@ -1239,7 +1235,7 @@ def test_patch_rest_flattened(): def test_patch_rest_flattened_error(): - client = ForwardingRulesClient(credentials=credentials.AnonymousCredentials(),) + client = ForwardingRulesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1257,7 +1253,7 @@ def test_set_target_rest( transport: str = "rest", request_type=compute.SetTargetForwardingRuleRequest ): client = ForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1292,17 +1288,16 @@ def test_set_target_rest( 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_target(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" @@ -1336,7 +1331,7 @@ def test_set_target_rest_from_dict(): def test_set_target_rest_flattened(): - client = ForwardingRulesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -1353,7 +1348,6 @@ def test_set_target_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. target_reference_resource = compute.TargetReference(target="target_value") - client.set_target( project="project_value", region="region_value", @@ -1366,13 +1360,9 @@ def test_set_target_rest_flattened(): 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 "forwarding_rule_value" in http_call[1] + str(body) - assert compute.TargetReference.to_json( target_reference_resource, including_default_value_fields=False, @@ -1381,7 +1371,7 @@ def test_set_target_rest_flattened(): def test_set_target_rest_flattened_error(): - client = ForwardingRulesClient(credentials=credentials.AnonymousCredentials(),) + client = ForwardingRulesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1398,16 +1388,16 @@ def test_set_target_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ForwardingRulesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.ForwardingRulesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ForwardingRulesClient( @@ -1417,7 +1407,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ForwardingRulesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ForwardingRulesClient( @@ -1428,7 +1418,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ForwardingRulesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ForwardingRulesClient(transport=transport) assert client.transport is transport @@ -1437,17 +1427,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.ForwardingRulesRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_forwarding_rules_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ForwardingRulesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1459,7 +1449,7 @@ def test_forwarding_rules_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ForwardingRulesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1478,15 +1468,40 @@ def test_forwarding_rules_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_forwarding_rules_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.forwarding_rules.transports.ForwardingRulesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ForwardingRulesTransport( + 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_forwarding_rules_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.forwarding_rules.transports.ForwardingRulesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ForwardingRulesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1502,19 +1517,36 @@ def test_forwarding_rules_base_transport_with_credentials_file(): def test_forwarding_rules_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.forwarding_rules.transports.ForwardingRulesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ForwardingRulesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_forwarding_rules_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ForwardingRulesClient() + 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_forwarding_rules_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) ForwardingRulesClient() adc.assert_called_once_with( scopes=( @@ -1526,7 +1558,7 @@ def test_forwarding_rules_auth_adc(): def test_forwarding_rules_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1538,7 +1570,7 @@ def test_forwarding_rules_http_transport_client_cert_source_for_mtls(): def test_forwarding_rules_host_no_port(): client = ForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1548,7 +1580,7 @@ def test_forwarding_rules_host_no_port(): def test_forwarding_rules_host_with_port(): client = ForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1558,7 +1590,6 @@ def test_forwarding_rules_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1579,7 +1610,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = ForwardingRulesClient.common_folder_path(folder) assert expected == actual @@ -1598,7 +1628,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = ForwardingRulesClient.common_organization_path(organization) assert expected == actual @@ -1617,7 +1646,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = ForwardingRulesClient.common_project_path(project) assert expected == actual @@ -1637,7 +1665,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1664,7 +1691,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ForwardingRulesTransport, "_prep_wrapped_messages" ) as prep: client = ForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1673,6 +1700,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ForwardingRulesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_global_addresses.py b/tests/unit/gapic/compute_v1/test_global_addresses.py index aa6b7534f..528b20ca1 100644 --- a/tests/unit/gapic/compute_v1/test_global_addresses.py +++ b/tests/unit/gapic/compute_v1/test_global_addresses.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -87,7 +116,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [GlobalAddressesClient,]) def test_global_addresses_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -102,7 +131,7 @@ def test_global_addresses_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [GlobalAddressesClient,]) def test_global_addresses_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -143,7 +172,7 @@ def test_global_addresses_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(GlobalAddressesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -391,7 +420,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteGlobalAddressRequest ): client = GlobalAddressesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -426,17 +455,16 @@ def test_delete_rest( 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" @@ -470,7 +498,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = GlobalAddressesClient(credentials=credentials.AnonymousCredentials(),) + client = GlobalAddressesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -495,14 +523,12 @@ def test_delete_rest_flattened(): 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 "address_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = GlobalAddressesClient(credentials=credentials.AnonymousCredentials(),) + client = GlobalAddressesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -518,7 +544,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetGlobalAddressRequest ): client = GlobalAddressesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -547,17 +573,16 @@ def test_get_rest( subnetwork="subnetwork_value", users=["users_value"], ) + # Wrap the value into a proper Response obj json_return_value = compute.Address.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.Address) assert response.address == "address_value" assert response.address_type == compute.Address.AddressType.EXTERNAL @@ -583,7 +608,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = GlobalAddressesClient(credentials=credentials.AnonymousCredentials(),) + client = GlobalAddressesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -608,14 +633,12 @@ def test_get_rest_flattened(): 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 "address_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = GlobalAddressesClient(credentials=credentials.AnonymousCredentials(),) + client = GlobalAddressesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -631,7 +654,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertGlobalAddressRequest ): client = GlobalAddressesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -666,17 +689,16 @@ def test_insert_rest( 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" @@ -710,7 +732,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = GlobalAddressesClient(credentials=credentials.AnonymousCredentials(),) + client = GlobalAddressesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -727,7 +749,6 @@ def test_insert_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. address_resource = compute.Address(address="address_value") - client.insert( project="project_value", address_resource=address_resource, ) @@ -737,9 +758,7 @@ def test_insert_rest_flattened(): 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.Address.to_json( address_resource, including_default_value_fields=False, @@ -748,7 +767,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = GlobalAddressesClient(credentials=credentials.AnonymousCredentials(),) + client = GlobalAddressesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -764,7 +783,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListGlobalAddressesRequest ): client = GlobalAddressesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -782,17 +801,16 @@ def test_list_rest( 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.AddressList.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.Address(address="address_value")] @@ -807,7 +825,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = GlobalAddressesClient(credentials=credentials.AnonymousCredentials(),) + client = GlobalAddressesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -830,12 +848,11 @@ def test_list_rest_flattened(): 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 = GlobalAddressesClient(credentials=credentials.AnonymousCredentials(),) + client = GlobalAddressesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -846,12 +863,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = GlobalAddressesClient(credentials=credentials.AnonymousCredentials(),) + client = GlobalAddressesClient(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.AddressList( items=[compute.Address(), compute.Address(), compute.Address(),], @@ -861,7 +877,6 @@ def test_list_pager(): compute.AddressList(items=[compute.Address(),], next_page_token="ghi",), compute.AddressList(items=[compute.Address(), compute.Address(),],), ) - # Two responses for two calls response = response + response @@ -880,7 +895,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.Address) for i in results) pages = list(client.list(request={}).pages) @@ -891,16 +905,16 @@ def test_list_pager(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.GlobalAddressesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = GlobalAddressesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.GlobalAddressesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = GlobalAddressesClient( @@ -910,7 +924,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.GlobalAddressesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = GlobalAddressesClient( @@ -921,7 +935,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.GlobalAddressesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = GlobalAddressesClient(transport=transport) assert client.transport is transport @@ -930,17 +944,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.GlobalAddressesRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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_addresses_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.GlobalAddressesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -952,7 +966,7 @@ def test_global_addresses_base_transport(): ) as Transport: Transport.return_value = None transport = transports.GlobalAddressesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -968,15 +982,40 @@ def test_global_addresses_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_global_addresses_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.global_addresses.transports.GlobalAddressesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GlobalAddressesTransport( + 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_addresses_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_addresses.transports.GlobalAddressesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.GlobalAddressesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -992,19 +1031,36 @@ def test_global_addresses_base_transport_with_credentials_file(): def test_global_addresses_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.global_addresses.transports.GlobalAddressesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.GlobalAddressesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_global_addresses_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + GlobalAddressesClient() + 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_addresses_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) GlobalAddressesClient() adc.assert_called_once_with( scopes=( @@ -1016,7 +1072,7 @@ def test_global_addresses_auth_adc(): def test_global_addresses_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1028,7 +1084,7 @@ def test_global_addresses_http_transport_client_cert_source_for_mtls(): def test_global_addresses_host_no_port(): client = GlobalAddressesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1038,7 +1094,7 @@ def test_global_addresses_host_no_port(): def test_global_addresses_host_with_port(): client = GlobalAddressesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1048,7 +1104,6 @@ def test_global_addresses_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1069,7 +1124,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = GlobalAddressesClient.common_folder_path(folder) assert expected == actual @@ -1088,7 +1142,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = GlobalAddressesClient.common_organization_path(organization) assert expected == actual @@ -1107,7 +1160,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = GlobalAddressesClient.common_project_path(project) assert expected == actual @@ -1127,7 +1179,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1154,7 +1205,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.GlobalAddressesTransport, "_prep_wrapped_messages" ) as prep: client = GlobalAddressesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1163,6 +1214,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = GlobalAddressesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_global_forwarding_rules.py b/tests/unit/gapic/compute_v1/test_global_forwarding_rules.py index 522424d58..a519ef8cf 100644 --- a/tests/unit/gapic/compute_v1/test_global_forwarding_rules.py +++ b/tests/unit/gapic/compute_v1/test_global_forwarding_rules.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,33 +13,63 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.compute_v1.services.global_forwarding_rules import ( GlobalForwardingRulesClient, ) 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, +) 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 +# - 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", +) + +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(): @@ -90,7 +119,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [GlobalForwardingRulesClient,]) def test_global_forwarding_rules_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -105,7 +134,7 @@ def test_global_forwarding_rules_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [GlobalForwardingRulesClient,]) def test_global_forwarding_rules_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -152,7 +181,7 @@ def test_global_forwarding_rules_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(GlobalForwardingRulesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -412,7 +441,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteGlobalForwardingRuleRequest ): client = GlobalForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -447,17 +476,16 @@ def test_delete_rest( 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" @@ -492,7 +520,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): client = GlobalForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -518,15 +546,13 @@ def test_delete_rest_flattened(): 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 "forwarding_rule_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): client = GlobalForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -543,7 +569,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetGlobalForwardingRuleRequest ): client = GlobalForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -584,21 +610,18 @@ def test_get_rest( subnetwork="subnetwork_value", target="target_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.ForwardingRule.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.ForwardingRule) - 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" @@ -608,7 +631,6 @@ def test_get_rest( 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 ( @@ -639,7 +661,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): client = GlobalForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -665,15 +687,13 @@ def test_get_rest_flattened(): 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 "forwarding_rule_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): client = GlobalForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -690,7 +710,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertGlobalForwardingRuleRequest ): client = GlobalForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -725,17 +745,16 @@ def test_insert_rest( 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" @@ -770,7 +789,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): client = GlobalForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -788,7 +807,6 @@ 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) - client.insert( project="project_value", forwarding_rule_resource=forwarding_rule_resource, ) @@ -798,9 +816,7 @@ def test_insert_rest_flattened(): 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.ForwardingRule.to_json( forwarding_rule_resource, including_default_value_fields=False, @@ -810,7 +826,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): client = GlobalForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -827,7 +843,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListGlobalForwardingRulesRequest ): client = GlobalForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -845,17 +861,16 @@ def test_list_rest( 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.ForwardingRuleList.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.ForwardingRule(all_ports=True)] @@ -871,7 +886,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): client = GlobalForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -895,13 +910,12 @@ def test_list_rest_flattened(): 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 = GlobalForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -914,13 +928,12 @@ def test_list_rest_flattened_error(): def test_list_pager(): client = GlobalForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), + 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.ForwardingRuleList( items=[ @@ -938,7 +951,6 @@ def test_list_pager(): items=[compute.ForwardingRule(), compute.ForwardingRule(),], ), ) - # Two responses for two calls response = response + response @@ -957,7 +969,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.ForwardingRule) for i in results) pages = list(client.list(request={}).pages) @@ -969,7 +980,7 @@ def test_patch_rest( transport: str = "rest", request_type=compute.PatchGlobalForwardingRuleRequest ): client = GlobalForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1004,17 +1015,16 @@ def test_patch_rest( 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" @@ -1049,7 +1059,7 @@ def test_patch_rest_from_dict(): def test_patch_rest_flattened(): client = GlobalForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1067,7 +1077,6 @@ 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) - client.patch( project="project_value", forwarding_rule="forwarding_rule_value", @@ -1079,11 +1088,8 @@ def test_patch_rest_flattened(): 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 "forwarding_rule_value" in http_call[1] + str(body) - assert compute.ForwardingRule.to_json( forwarding_rule_resource, including_default_value_fields=False, @@ -1093,7 +1099,7 @@ def test_patch_rest_flattened(): def test_patch_rest_flattened_error(): client = GlobalForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1111,7 +1117,7 @@ def test_set_target_rest( transport: str = "rest", request_type=compute.SetTargetGlobalForwardingRuleRequest ): client = GlobalForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1146,17 +1152,16 @@ def test_set_target_rest( 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_target(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" @@ -1191,7 +1196,7 @@ def test_set_target_rest_from_dict(): def test_set_target_rest_flattened(): client = GlobalForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1209,7 +1214,6 @@ def test_set_target_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. target_reference_resource = compute.TargetReference(target="target_value") - client.set_target( project="project_value", forwarding_rule="forwarding_rule_value", @@ -1221,11 +1225,8 @@ def test_set_target_rest_flattened(): 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 "forwarding_rule_value" in http_call[1] + str(body) - assert compute.TargetReference.to_json( target_reference_resource, including_default_value_fields=False, @@ -1235,7 +1236,7 @@ def test_set_target_rest_flattened(): def test_set_target_rest_flattened_error(): client = GlobalForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1252,16 +1253,16 @@ def test_set_target_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.GlobalForwardingRulesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = GlobalForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.GlobalForwardingRulesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = GlobalForwardingRulesClient( @@ -1271,7 +1272,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.GlobalForwardingRulesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = GlobalForwardingRulesClient( @@ -1282,7 +1283,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.GlobalForwardingRulesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = GlobalForwardingRulesClient(transport=transport) assert client.transport is transport @@ -1293,17 +1294,17 @@ def test_transport_instance(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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_forwarding_rules_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.GlobalForwardingRulesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1315,7 +1316,7 @@ def test_global_forwarding_rules_base_transport(): ) as Transport: Transport.return_value = None transport = transports.GlobalForwardingRulesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1333,15 +1334,40 @@ def test_global_forwarding_rules_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_global_forwarding_rules_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.global_forwarding_rules.transports.GlobalForwardingRulesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GlobalForwardingRulesTransport( + 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_forwarding_rules_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_forwarding_rules.transports.GlobalForwardingRulesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.GlobalForwardingRulesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1357,19 +1383,36 @@ def test_global_forwarding_rules_base_transport_with_credentials_file(): def test_global_forwarding_rules_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.global_forwarding_rules.transports.GlobalForwardingRulesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.GlobalForwardingRulesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_global_forwarding_rules_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + GlobalForwardingRulesClient() + 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_forwarding_rules_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) GlobalForwardingRulesClient() adc.assert_called_once_with( scopes=( @@ -1381,7 +1424,7 @@ def test_global_forwarding_rules_auth_adc(): def test_global_forwarding_rules_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1393,7 +1436,7 @@ def test_global_forwarding_rules_http_transport_client_cert_source_for_mtls(): def test_global_forwarding_rules_host_no_port(): client = GlobalForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1403,7 +1446,7 @@ def test_global_forwarding_rules_host_no_port(): def test_global_forwarding_rules_host_with_port(): client = GlobalForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1413,7 +1456,6 @@ def test_global_forwarding_rules_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1434,7 +1476,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = GlobalForwardingRulesClient.common_folder_path(folder) assert expected == actual @@ -1453,7 +1494,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = GlobalForwardingRulesClient.common_organization_path(organization) assert expected == actual @@ -1472,7 +1512,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = GlobalForwardingRulesClient.common_project_path(project) assert expected == actual @@ -1492,7 +1531,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1519,7 +1557,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.GlobalForwardingRulesTransport, "_prep_wrapped_messages" ) as prep: client = GlobalForwardingRulesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1528,6 +1566,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = GlobalForwardingRulesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_global_network_endpoint_groups.py b/tests/unit/gapic/compute_v1/test_global_network_endpoint_groups.py index c936e733d..09ee43b1b 100644 --- a/tests/unit/gapic/compute_v1/test_global_network_endpoint_groups.py +++ b/tests/unit/gapic/compute_v1/test_global_network_endpoint_groups.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,33 +13,63 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.compute_v1.services.global_network_endpoint_groups import ( GlobalNetworkEndpointGroupsClient, ) 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, +) 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 +# - 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", +) + +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(): @@ -92,7 +121,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [GlobalNetworkEndpointGroupsClient,]) def test_global_network_endpoint_groups_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -107,7 +136,7 @@ def test_global_network_endpoint_groups_client_from_service_account_info(client_ @pytest.mark.parametrize("client_class", [GlobalNetworkEndpointGroupsClient,]) def test_global_network_endpoint_groups_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -156,7 +185,7 @@ def test_global_network_endpoint_groups_client_client_options( with mock.patch.object( GlobalNetworkEndpointGroupsClient, "get_transport_class" ) as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -419,7 +448,7 @@ def test_attach_network_endpoints_rest( request_type=compute.AttachNetworkEndpointsGlobalNetworkEndpointGroupRequest, ): client = GlobalNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -454,17 +483,16 @@ def test_attach_network_endpoints_rest( 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.attach_network_endpoints(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" @@ -499,7 +527,7 @@ def test_attach_network_endpoints_rest_from_dict(): def test_attach_network_endpoints_rest_flattened(): client = GlobalNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -521,7 +549,6 @@ def test_attach_network_endpoints_rest_flattened(): compute.NetworkEndpoint(annotations={"key_value": "value_value"}) ] ) - client.attach_network_endpoints( project="project_value", network_endpoint_group="network_endpoint_group_value", @@ -533,11 +560,8 @@ def test_attach_network_endpoints_rest_flattened(): 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_endpoint_group_value" in http_call[1] + str(body) - assert compute.GlobalNetworkEndpointGroupsAttachEndpointsRequest.to_json( global_network_endpoint_groups_attach_endpoints_request_resource, including_default_value_fields=False, @@ -547,7 +571,7 @@ def test_attach_network_endpoints_rest_flattened(): def test_attach_network_endpoints_rest_flattened_error(): client = GlobalNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -570,7 +594,7 @@ def test_delete_rest( request_type=compute.DeleteGlobalNetworkEndpointGroupRequest, ): client = GlobalNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -605,17 +629,16 @@ def test_delete_rest( 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" @@ -650,7 +673,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): client = GlobalNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -677,15 +700,13 @@ def test_delete_rest_flattened(): 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_endpoint_group_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): client = GlobalNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -703,7 +724,7 @@ def test_detach_network_endpoints_rest( request_type=compute.DetachNetworkEndpointsGlobalNetworkEndpointGroupRequest, ): client = GlobalNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -738,17 +759,16 @@ def test_detach_network_endpoints_rest( 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.detach_network_endpoints(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" @@ -783,7 +803,7 @@ def test_detach_network_endpoints_rest_from_dict(): def test_detach_network_endpoints_rest_flattened(): client = GlobalNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -805,7 +825,6 @@ def test_detach_network_endpoints_rest_flattened(): compute.NetworkEndpoint(annotations={"key_value": "value_value"}) ] ) - client.detach_network_endpoints( project="project_value", network_endpoint_group="network_endpoint_group_value", @@ -817,11 +836,8 @@ def test_detach_network_endpoints_rest_flattened(): 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_endpoint_group_value" in http_call[1] + str(body) - assert compute.GlobalNetworkEndpointGroupsDetachEndpointsRequest.to_json( global_network_endpoint_groups_detach_endpoints_request_resource, including_default_value_fields=False, @@ -831,7 +847,7 @@ def test_detach_network_endpoints_rest_flattened(): def test_detach_network_endpoints_rest_flattened_error(): client = GlobalNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -853,7 +869,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetGlobalNetworkEndpointGroupRequest ): client = GlobalNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -884,17 +900,16 @@ def test_get_rest( subnetwork="subnetwork_value", zone="zone_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.NetworkEndpointGroup.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.NetworkEndpointGroup) assert response.annotations == {"key_value": "value_value"} assert response.app_engine == compute.NetworkEndpointGroupAppEngine( @@ -930,7 +945,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): client = GlobalNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -957,15 +972,13 @@ def test_get_rest_flattened(): 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_endpoint_group_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): client = GlobalNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -983,7 +996,7 @@ def test_insert_rest( request_type=compute.InsertGlobalNetworkEndpointGroupRequest, ): client = GlobalNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1018,17 +1031,16 @@ def test_insert_rest( 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" @@ -1063,7 +1075,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): client = GlobalNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1083,7 +1095,6 @@ def test_insert_rest_flattened(): network_endpoint_group_resource = compute.NetworkEndpointGroup( annotations={"key_value": "value_value"} ) - client.insert( project="project_value", network_endpoint_group_resource=network_endpoint_group_resource, @@ -1094,9 +1105,7 @@ def test_insert_rest_flattened(): 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.NetworkEndpointGroup.to_json( network_endpoint_group_resource, including_default_value_fields=False, @@ -1106,7 +1115,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): client = GlobalNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1125,7 +1134,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListGlobalNetworkEndpointGroupsRequest ): client = GlobalNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1145,17 +1154,16 @@ def test_list_rest( 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.NetworkEndpointGroupList.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 == [ @@ -1173,7 +1181,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): client = GlobalNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1197,13 +1205,12 @@ def test_list_rest_flattened(): 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 = GlobalNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1216,13 +1223,12 @@ def test_list_rest_flattened_error(): def test_list_pager(): client = GlobalNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + 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.NetworkEndpointGroupList( items=[ @@ -1240,7 +1246,6 @@ def test_list_pager(): items=[compute.NetworkEndpointGroup(), compute.NetworkEndpointGroup(),], ), ) - # Two responses for two calls response = response + response @@ -1259,7 +1264,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.NetworkEndpointGroup) for i in results) pages = list(client.list(request={}).pages) @@ -1272,7 +1276,7 @@ def test_list_network_endpoints_rest( request_type=compute.ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest, ): client = GlobalNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1299,6 +1303,7 @@ def test_list_network_endpoints_rest( 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.NetworkEndpointGroupsListNetworkEndpoints.to_json( return_value @@ -1307,11 +1312,9 @@ def test_list_network_endpoints_rest( response_value.status_code = 200 response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_network_endpoints(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNetworkEndpointsPager) assert response.id == "id_value" assert response.items == [ @@ -1336,7 +1339,7 @@ def test_list_network_endpoints_rest_from_dict(): def test_list_network_endpoints_rest_flattened(): client = GlobalNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1365,15 +1368,13 @@ def test_list_network_endpoints_rest_flattened(): 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_endpoint_group_value" in http_call[1] + str(body) def test_list_network_endpoints_rest_flattened_error(): client = GlobalNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1388,13 +1389,12 @@ def test_list_network_endpoints_rest_flattened_error(): def test_list_network_endpoints_pager(): client = GlobalNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + 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.NetworkEndpointGroupsListNetworkEndpoints( items=[ @@ -1418,7 +1418,6 @@ def test_list_network_endpoints_pager(): ], ), ) - # Two responses for two calls response = response + response @@ -1440,7 +1439,6 @@ def test_list_network_endpoints_pager(): results = list(pager) assert len(results) == 6 - assert all( isinstance(i, compute.NetworkEndpointWithHealthStatus) for i in results ) @@ -1453,16 +1451,16 @@ def test_list_network_endpoints_pager(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.GlobalNetworkEndpointGroupsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = GlobalNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.GlobalNetworkEndpointGroupsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = GlobalNetworkEndpointGroupsClient( @@ -1472,7 +1470,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.GlobalNetworkEndpointGroupsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = GlobalNetworkEndpointGroupsClient( @@ -1483,7 +1481,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.GlobalNetworkEndpointGroupsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = GlobalNetworkEndpointGroupsClient(transport=transport) assert client.transport is transport @@ -1494,17 +1492,17 @@ def test_transport_instance(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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_network_endpoint_groups_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.GlobalNetworkEndpointGroupsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1516,7 +1514,7 @@ def test_global_network_endpoint_groups_base_transport(): ) as Transport: Transport.return_value = None transport = transports.GlobalNetworkEndpointGroupsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1535,15 +1533,40 @@ def test_global_network_endpoint_groups_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_global_network_endpoint_groups_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.global_network_endpoint_groups.transports.GlobalNetworkEndpointGroupsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GlobalNetworkEndpointGroupsTransport( + 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_network_endpoint_groups_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_network_endpoint_groups.transports.GlobalNetworkEndpointGroupsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.GlobalNetworkEndpointGroupsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1559,19 +1582,36 @@ def test_global_network_endpoint_groups_base_transport_with_credentials_file(): def test_global_network_endpoint_groups_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.global_network_endpoint_groups.transports.GlobalNetworkEndpointGroupsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.GlobalNetworkEndpointGroupsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_global_network_endpoint_groups_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + GlobalNetworkEndpointGroupsClient() + 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_network_endpoint_groups_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) GlobalNetworkEndpointGroupsClient() adc.assert_called_once_with( scopes=( @@ -1583,7 +1623,7 @@ def test_global_network_endpoint_groups_auth_adc(): def test_global_network_endpoint_groups_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1595,7 +1635,7 @@ def test_global_network_endpoint_groups_http_transport_client_cert_source_for_mt def test_global_network_endpoint_groups_host_no_port(): client = GlobalNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1605,7 +1645,7 @@ def test_global_network_endpoint_groups_host_no_port(): def test_global_network_endpoint_groups_host_with_port(): client = GlobalNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1615,7 +1655,6 @@ def test_global_network_endpoint_groups_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1638,7 +1677,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = GlobalNetworkEndpointGroupsClient.common_folder_path(folder) assert expected == actual @@ -1657,7 +1695,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = GlobalNetworkEndpointGroupsClient.common_organization_path(organization) assert expected == actual @@ -1676,7 +1713,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = GlobalNetworkEndpointGroupsClient.common_project_path(project) assert expected == actual @@ -1696,7 +1732,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1723,7 +1758,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.GlobalNetworkEndpointGroupsTransport, "_prep_wrapped_messages" ) as prep: client = GlobalNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1732,6 +1767,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = GlobalNetworkEndpointGroupsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_global_operations.py b/tests/unit/gapic/compute_v1/test_global_operations.py index 03248ae0c..6461a92ed 100644 --- a/tests/unit/gapic/compute_v1/test_global_operations.py +++ b/tests/unit/gapic/compute_v1/test_global_operations.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -88,7 +117,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [GlobalOperationsClient,]) def test_global_operations_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -103,7 +132,7 @@ def test_global_operations_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [GlobalOperationsClient,]) def test_global_operations_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -144,7 +173,7 @@ def test_global_operations_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(GlobalOperationsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -392,7 +421,7 @@ def test_aggregated_list_rest( transport: str = "rest", request_type=compute.AggregatedListGlobalOperationsRequest ): client = GlobalOperationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -419,17 +448,16 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.OperationAggregatedList.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 == { @@ -451,7 +479,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = GlobalOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = GlobalOperationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -474,12 +502,11 @@ def test_aggregated_list_rest_flattened(): 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 = GlobalOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = GlobalOperationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -490,12 +517,11 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = GlobalOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = GlobalOperationsClient(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.OperationAggregatedList( items={ @@ -516,7 +542,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -538,7 +563,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -556,7 +580,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteGlobalOperationRequest ): client = GlobalOperationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -567,17 +591,16 @@ def test_delete_rest( with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. return_value = compute.DeleteGlobalOperationResponse() + # Wrap the value into a proper Response obj json_return_value = compute.DeleteGlobalOperationResponse.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.DeleteGlobalOperationResponse) @@ -586,7 +609,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = GlobalOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = GlobalOperationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -611,14 +634,12 @@ def test_delete_rest_flattened(): 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 "operation_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = GlobalOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = GlobalOperationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -634,7 +655,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetGlobalOperationRequest ): client = GlobalOperationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -669,17 +690,16 @@ def test_get_rest( 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.get(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" @@ -713,7 +733,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = GlobalOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = GlobalOperationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -738,14 +758,12 @@ def test_get_rest_flattened(): 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 "operation_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = GlobalOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = GlobalOperationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -761,7 +779,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListGlobalOperationsRequest ): client = GlobalOperationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -779,17 +797,16 @@ def test_list_rest( 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.OperationList.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 == [ @@ -806,7 +823,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = GlobalOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = GlobalOperationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -829,12 +846,11 @@ def test_list_rest_flattened(): 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 = GlobalOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = GlobalOperationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -845,12 +861,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = GlobalOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = GlobalOperationsClient(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.OperationList( items=[compute.Operation(), compute.Operation(), compute.Operation(),], @@ -860,7 +875,6 @@ def test_list_pager(): compute.OperationList(items=[compute.Operation(),], next_page_token="ghi",), compute.OperationList(items=[compute.Operation(), compute.Operation(),],), ) - # Two responses for two calls response = response + response @@ -879,7 +893,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.Operation) for i in results) pages = list(client.list(request={}).pages) @@ -891,7 +904,7 @@ def test_wait_rest( transport: str = "rest", request_type=compute.WaitGlobalOperationRequest ): client = GlobalOperationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -926,17 +939,16 @@ def test_wait_rest( 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.wait(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" @@ -970,7 +982,7 @@ def test_wait_rest_from_dict(): def test_wait_rest_flattened(): - client = GlobalOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = GlobalOperationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -995,14 +1007,12 @@ def test_wait_rest_flattened(): 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 "operation_value" in http_call[1] + str(body) def test_wait_rest_flattened_error(): - client = GlobalOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = GlobalOperationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1017,16 +1027,16 @@ def test_wait_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.GlobalOperationsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = GlobalOperationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.GlobalOperationsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = GlobalOperationsClient( @@ -1036,7 +1046,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.GlobalOperationsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = GlobalOperationsClient( @@ -1047,7 +1057,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.GlobalOperationsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = GlobalOperationsClient(transport=transport) assert client.transport is transport @@ -1056,17 +1066,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.GlobalOperationsRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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_operations_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.GlobalOperationsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1078,7 +1088,7 @@ def test_global_operations_base_transport(): ) as Transport: Transport.return_value = None transport = transports.GlobalOperationsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1095,15 +1105,40 @@ def test_global_operations_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_global_operations_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.global_operations.transports.GlobalOperationsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GlobalOperationsTransport( + 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_operations_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_operations.transports.GlobalOperationsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.GlobalOperationsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1119,19 +1154,36 @@ def test_global_operations_base_transport_with_credentials_file(): def test_global_operations_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.global_operations.transports.GlobalOperationsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.GlobalOperationsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_global_operations_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + GlobalOperationsClient() + 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_operations_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) GlobalOperationsClient() adc.assert_called_once_with( scopes=( @@ -1143,7 +1195,7 @@ def test_global_operations_auth_adc(): def test_global_operations_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1155,7 +1207,7 @@ def test_global_operations_http_transport_client_cert_source_for_mtls(): def test_global_operations_host_no_port(): client = GlobalOperationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1165,7 +1217,7 @@ def test_global_operations_host_no_port(): def test_global_operations_host_with_port(): client = GlobalOperationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1175,7 +1227,6 @@ def test_global_operations_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1196,7 +1247,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = GlobalOperationsClient.common_folder_path(folder) assert expected == actual @@ -1215,7 +1265,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = GlobalOperationsClient.common_organization_path(organization) assert expected == actual @@ -1234,7 +1283,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = GlobalOperationsClient.common_project_path(project) assert expected == actual @@ -1254,7 +1302,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1281,7 +1328,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.GlobalOperationsTransport, "_prep_wrapped_messages" ) as prep: client = GlobalOperationsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1290,6 +1337,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = GlobalOperationsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_global_organization_operations.py b/tests/unit/gapic/compute_v1/test_global_organization_operations.py index bf8189fab..0573d6b72 100644 --- a/tests/unit/gapic/compute_v1/test_global_organization_operations.py +++ b/tests/unit/gapic/compute_v1/test_global_organization_operations.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,33 +13,63 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.compute_v1.services.global_organization_operations import ( GlobalOrganizationOperationsClient, ) 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, +) 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 +# - 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", +) + +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(): @@ -92,7 +121,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [GlobalOrganizationOperationsClient,]) def test_global_organization_operations_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -107,7 +136,7 @@ def test_global_organization_operations_client_from_service_account_info(client_ @pytest.mark.parametrize("client_class", [GlobalOrganizationOperationsClient,]) def test_global_organization_operations_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -156,7 +185,7 @@ def test_global_organization_operations_client_client_options( with mock.patch.object( GlobalOrganizationOperationsClient, "get_transport_class" ) as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -419,7 +448,7 @@ def test_delete_rest( request_type=compute.DeleteGlobalOrganizationOperationRequest, ): client = GlobalOrganizationOperationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -430,6 +459,7 @@ def test_delete_rest( with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. return_value = compute.DeleteGlobalOrganizationOperationResponse() + # Wrap the value into a proper Response obj json_return_value = compute.DeleteGlobalOrganizationOperationResponse.to_json( return_value @@ -438,11 +468,9 @@ def test_delete_rest( 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.DeleteGlobalOrganizationOperationResponse) @@ -452,7 +480,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): client = GlobalOrganizationOperationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -478,13 +506,12 @@ def test_delete_rest_flattened(): assert len(req.mock_calls) == 1 _, http_call, http_params = req.mock_calls[0] body = http_params.get("data") - assert "operation_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): client = GlobalOrganizationOperationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -500,7 +527,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetGlobalOrganizationOperationRequest ): client = GlobalOrganizationOperationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -535,17 +562,16 @@ def test_get_rest( 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.get(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" @@ -580,7 +606,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): client = GlobalOrganizationOperationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -604,13 +630,12 @@ def test_get_rest_flattened(): assert len(req.mock_calls) == 1 _, http_call, http_params = req.mock_calls[0] body = http_params.get("data") - assert "operation_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): client = GlobalOrganizationOperationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -627,7 +652,7 @@ def test_list_rest( request_type=compute.ListGlobalOrganizationOperationsRequest, ): client = GlobalOrganizationOperationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -645,17 +670,16 @@ def test_list_rest( 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.OperationList.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 == [ @@ -673,7 +697,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): client = GlobalOrganizationOperationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -701,7 +725,7 @@ def test_list_rest_flattened(): def test_list_rest_flattened_error(): client = GlobalOrganizationOperationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -712,13 +736,12 @@ def test_list_rest_flattened_error(): def test_list_pager(): client = GlobalOrganizationOperationsClient( - credentials=credentials.AnonymousCredentials(), + 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.OperationList( items=[compute.Operation(), compute.Operation(), compute.Operation(),], @@ -728,7 +751,6 @@ def test_list_pager(): compute.OperationList(items=[compute.Operation(),], next_page_token="ghi",), compute.OperationList(items=[compute.Operation(), compute.Operation(),],), ) - # Two responses for two calls response = response + response @@ -747,7 +769,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.Operation) for i in results) pages = list(client.list(request={}).pages) @@ -758,16 +779,16 @@ def test_list_pager(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.GlobalOrganizationOperationsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = GlobalOrganizationOperationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.GlobalOrganizationOperationsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = GlobalOrganizationOperationsClient( @@ -777,7 +798,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.GlobalOrganizationOperationsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = GlobalOrganizationOperationsClient( @@ -788,7 +809,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.GlobalOrganizationOperationsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = GlobalOrganizationOperationsClient(transport=transport) assert client.transport is transport @@ -799,17 +820,17 @@ def test_transport_instance(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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_organization_operations_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.GlobalOrganizationOperationsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -821,7 +842,7 @@ def test_global_organization_operations_base_transport(): ) as Transport: Transport.return_value = None transport = transports.GlobalOrganizationOperationsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -836,15 +857,40 @@ def test_global_organization_operations_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_global_organization_operations_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.global_organization_operations.transports.GlobalOrganizationOperationsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GlobalOrganizationOperationsTransport( + 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_organization_operations_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_organization_operations.transports.GlobalOrganizationOperationsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.GlobalOrganizationOperationsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -860,19 +906,36 @@ def test_global_organization_operations_base_transport_with_credentials_file(): def test_global_organization_operations_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.global_organization_operations.transports.GlobalOrganizationOperationsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.GlobalOrganizationOperationsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_global_organization_operations_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + GlobalOrganizationOperationsClient() + 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_organization_operations_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) GlobalOrganizationOperationsClient() adc.assert_called_once_with( scopes=( @@ -884,7 +947,7 @@ def test_global_organization_operations_auth_adc(): def test_global_organization_operations_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -896,7 +959,7 @@ def test_global_organization_operations_http_transport_client_cert_source_for_mt def test_global_organization_operations_host_no_port(): client = GlobalOrganizationOperationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -906,7 +969,7 @@ def test_global_organization_operations_host_no_port(): def test_global_organization_operations_host_with_port(): client = GlobalOrganizationOperationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -916,7 +979,6 @@ def test_global_organization_operations_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -939,7 +1001,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = GlobalOrganizationOperationsClient.common_folder_path(folder) assert expected == actual @@ -958,7 +1019,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = GlobalOrganizationOperationsClient.common_organization_path(organization) assert expected == actual @@ -977,7 +1037,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = GlobalOrganizationOperationsClient.common_project_path(project) assert expected == actual @@ -997,7 +1056,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1024,7 +1082,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.GlobalOrganizationOperationsTransport, "_prep_wrapped_messages" ) as prep: client = GlobalOrganizationOperationsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1033,6 +1091,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = GlobalOrganizationOperationsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_health_checks.py b/tests/unit/gapic/compute_v1/test_health_checks.py index 9a15e64f3..7167dd9b2 100644 --- a/tests/unit/gapic/compute_v1/test_health_checks.py +++ b/tests/unit/gapic/compute_v1/test_health_checks.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -84,7 +113,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [HealthChecksClient,]) def test_health_checks_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -99,7 +128,7 @@ def test_health_checks_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [HealthChecksClient,]) def test_health_checks_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -138,7 +167,7 @@ def test_health_checks_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(HealthChecksClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -374,7 +403,7 @@ def test_aggregated_list_rest( transport: str = "rest", request_type=compute.AggregatedListHealthChecksRequest ): client = HealthChecksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -397,17 +426,16 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.HealthChecksAggregatedList.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 == { @@ -427,7 +455,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = HealthChecksClient(credentials=credentials.AnonymousCredentials(),) + client = HealthChecksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -450,12 +478,11 @@ def test_aggregated_list_rest_flattened(): 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 = HealthChecksClient(credentials=credentials.AnonymousCredentials(),) + client = HealthChecksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -466,12 +493,11 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = HealthChecksClient(credentials=credentials.AnonymousCredentials(),) + client = HealthChecksClient(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.HealthChecksAggregatedList( items={ @@ -492,7 +518,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -516,7 +541,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -537,7 +561,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteHealthCheckRequest ): client = HealthChecksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -572,17 +596,16 @@ def test_delete_rest( 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" @@ -616,7 +639,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = HealthChecksClient(credentials=credentials.AnonymousCredentials(),) + client = HealthChecksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -641,14 +664,12 @@ def test_delete_rest_flattened(): 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 "health_check_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = HealthChecksClient(credentials=credentials.AnonymousCredentials(),) + client = HealthChecksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -662,7 +683,7 @@ def test_delete_rest_flattened_error(): def test_get_rest(transport: str = "rest", request_type=compute.GetHealthCheckRequest): client = HealthChecksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -695,17 +716,16 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetHealthCheckRe type_=compute.HealthCheck.Type.GRPC, unhealthy_threshold=2046, ) + # Wrap the value into a proper Response obj json_return_value = compute.HealthCheck.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.HealthCheck) assert response.check_interval_sec == 1884 assert response.creation_timestamp == "creation_timestamp_value" @@ -735,7 +755,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = HealthChecksClient(credentials=credentials.AnonymousCredentials(),) + client = HealthChecksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -760,14 +780,12 @@ def test_get_rest_flattened(): 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 "health_check_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = HealthChecksClient(credentials=credentials.AnonymousCredentials(),) + client = HealthChecksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -783,7 +801,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertHealthCheckRequest ): client = HealthChecksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -818,17 +836,16 @@ def test_insert_rest( 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" @@ -862,7 +879,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = HealthChecksClient(credentials=credentials.AnonymousCredentials(),) + client = HealthChecksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -879,7 +896,6 @@ def test_insert_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. health_check_resource = compute.HealthCheck(check_interval_sec=1884) - client.insert( project="project_value", health_check_resource=health_check_resource, ) @@ -889,9 +905,7 @@ def test_insert_rest_flattened(): 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.HealthCheck.to_json( health_check_resource, including_default_value_fields=False, @@ -900,7 +914,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = HealthChecksClient(credentials=credentials.AnonymousCredentials(),) + client = HealthChecksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -916,7 +930,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListHealthChecksRequest ): client = HealthChecksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -934,17 +948,16 @@ def test_list_rest( 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.HealthCheckList.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.HealthCheck(check_interval_sec=1884)] @@ -959,7 +972,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = HealthChecksClient(credentials=credentials.AnonymousCredentials(),) + client = HealthChecksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -982,12 +995,11 @@ def test_list_rest_flattened(): 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 = HealthChecksClient(credentials=credentials.AnonymousCredentials(),) + client = HealthChecksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -998,12 +1010,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = HealthChecksClient(credentials=credentials.AnonymousCredentials(),) + client = HealthChecksClient(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.HealthCheckList( items=[ @@ -1021,7 +1032,6 @@ def test_list_pager(): items=[compute.HealthCheck(), compute.HealthCheck(),], ), ) - # Two responses for two calls response = response + response @@ -1040,7 +1050,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.HealthCheck) for i in results) pages = list(client.list(request={}).pages) @@ -1052,7 +1061,7 @@ def test_patch_rest( transport: str = "rest", request_type=compute.PatchHealthCheckRequest ): client = HealthChecksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1087,17 +1096,16 @@ def test_patch_rest( 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" @@ -1131,7 +1139,7 @@ def test_patch_rest_from_dict(): def test_patch_rest_flattened(): - client = HealthChecksClient(credentials=credentials.AnonymousCredentials(),) + client = HealthChecksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1148,7 +1156,6 @@ def test_patch_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. health_check_resource = compute.HealthCheck(check_interval_sec=1884) - client.patch( project="project_value", health_check="health_check_value", @@ -1160,11 +1167,8 @@ def test_patch_rest_flattened(): 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 "health_check_value" in http_call[1] + str(body) - assert compute.HealthCheck.to_json( health_check_resource, including_default_value_fields=False, @@ -1173,7 +1177,7 @@ def test_patch_rest_flattened(): def test_patch_rest_flattened_error(): - client = HealthChecksClient(credentials=credentials.AnonymousCredentials(),) + client = HealthChecksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1190,7 +1194,7 @@ def test_update_rest( transport: str = "rest", request_type=compute.UpdateHealthCheckRequest ): client = HealthChecksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1225,17 +1229,16 @@ def test_update_rest( 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.update(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" @@ -1269,7 +1272,7 @@ def test_update_rest_from_dict(): def test_update_rest_flattened(): - client = HealthChecksClient(credentials=credentials.AnonymousCredentials(),) + client = HealthChecksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1286,7 +1289,6 @@ def test_update_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. health_check_resource = compute.HealthCheck(check_interval_sec=1884) - client.update( project="project_value", health_check="health_check_value", @@ -1298,11 +1300,8 @@ def test_update_rest_flattened(): 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 "health_check_value" in http_call[1] + str(body) - assert compute.HealthCheck.to_json( health_check_resource, including_default_value_fields=False, @@ -1311,7 +1310,7 @@ def test_update_rest_flattened(): def test_update_rest_flattened_error(): - client = HealthChecksClient(credentials=credentials.AnonymousCredentials(),) + client = HealthChecksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1327,16 +1326,16 @@ def test_update_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.HealthChecksRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = HealthChecksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.HealthChecksRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = HealthChecksClient( @@ -1346,7 +1345,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.HealthChecksRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = HealthChecksClient( @@ -1357,7 +1356,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.HealthChecksRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = HealthChecksClient(transport=transport) assert client.transport is transport @@ -1366,17 +1365,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.HealthChecksRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_health_checks_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.HealthChecksTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1388,7 +1387,7 @@ def test_health_checks_base_transport(): ) as Transport: Transport.return_value = None transport = transports.HealthChecksTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1407,15 +1406,40 @@ def test_health_checks_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_health_checks_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.health_checks.transports.HealthChecksTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.HealthChecksTransport( + 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_health_checks_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.health_checks.transports.HealthChecksTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.HealthChecksTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1431,19 +1455,36 @@ def test_health_checks_base_transport_with_credentials_file(): def test_health_checks_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.health_checks.transports.HealthChecksTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.HealthChecksTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_health_checks_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + HealthChecksClient() + 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_health_checks_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) HealthChecksClient() adc.assert_called_once_with( scopes=( @@ -1455,7 +1496,7 @@ def test_health_checks_auth_adc(): def test_health_checks_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1467,7 +1508,7 @@ def test_health_checks_http_transport_client_cert_source_for_mtls(): def test_health_checks_host_no_port(): client = HealthChecksClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1477,7 +1518,7 @@ def test_health_checks_host_no_port(): def test_health_checks_host_with_port(): client = HealthChecksClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1487,7 +1528,6 @@ def test_health_checks_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1508,7 +1548,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = HealthChecksClient.common_folder_path(folder) assert expected == actual @@ -1527,7 +1566,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = HealthChecksClient.common_organization_path(organization) assert expected == actual @@ -1546,7 +1584,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = HealthChecksClient.common_project_path(project) assert expected == actual @@ -1566,7 +1603,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1593,7 +1629,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.HealthChecksTransport, "_prep_wrapped_messages" ) as prep: client = HealthChecksClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1602,6 +1638,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = HealthChecksClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_images.py b/tests/unit/gapic/compute_v1/test_images.py index 0c139489f..7bdd5f0d9 100644 --- a/tests/unit/gapic/compute_v1/test_images.py +++ b/tests/unit/gapic/compute_v1/test_images.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,57 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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 +# - 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", +) + +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(): @@ -81,7 +106,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [ImagesClient,]) def test_images_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -96,7 +121,7 @@ def test_images_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [ImagesClient,]) def test_images_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -133,7 +158,7 @@ def test_images_client_get_transport_class(): def test_images_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(ImagesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -367,7 +392,7 @@ def test_images_client_client_options_credentials_file( def test_delete_rest(transport: str = "rest", request_type=compute.DeleteImageRequest): client = ImagesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -402,17 +427,16 @@ def test_delete_rest(transport: str = "rest", request_type=compute.DeleteImageRe 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" @@ -446,7 +470,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = ImagesClient(credentials=credentials.AnonymousCredentials(),) + client = ImagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -471,14 +495,12 @@ def test_delete_rest_flattened(): 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 "image_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = ImagesClient(credentials=credentials.AnonymousCredentials(),) + client = ImagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -492,7 +514,7 @@ def test_deprecate_rest( transport: str = "rest", request_type=compute.DeprecateImageRequest ): client = ImagesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -527,17 +549,16 @@ def test_deprecate_rest( 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.deprecate(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" @@ -571,7 +592,7 @@ def test_deprecate_rest_from_dict(): def test_deprecate_rest_flattened(): - client = ImagesClient(credentials=credentials.AnonymousCredentials(),) + client = ImagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -588,7 +609,6 @@ def test_deprecate_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. deprecation_status_resource = compute.DeprecationStatus(deleted="deleted_value") - client.deprecate( project="project_value", image="image_value", @@ -600,11 +620,8 @@ def test_deprecate_rest_flattened(): 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 "image_value" in http_call[1] + str(body) - assert compute.DeprecationStatus.to_json( deprecation_status_resource, including_default_value_fields=False, @@ -613,7 +630,7 @@ def test_deprecate_rest_flattened(): def test_deprecate_rest_flattened_error(): - client = ImagesClient(credentials=credentials.AnonymousCredentials(),) + client = ImagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -630,7 +647,7 @@ def test_deprecate_rest_flattened_error(): def test_get_rest(transport: str = "rest", request_type=compute.GetImageRequest): client = ImagesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -686,17 +703,16 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetImageRequest) status=compute.Image.Status.DELETING, storage_locations=["storage_locations_value"], ) + # Wrap the value into a proper Response obj json_return_value = compute.Image.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.Image) assert response.archive_size_bytes == "archive_size_bytes_value" assert response.creation_timestamp == "creation_timestamp_value" @@ -751,7 +767,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = ImagesClient(credentials=credentials.AnonymousCredentials(),) + client = ImagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -776,14 +792,12 @@ def test_get_rest_flattened(): 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 "image_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = ImagesClient(credentials=credentials.AnonymousCredentials(),) + client = ImagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -797,7 +811,7 @@ def test_get_from_family_rest( transport: str = "rest", request_type=compute.GetFromFamilyImageRequest ): client = ImagesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -853,17 +867,16 @@ def test_get_from_family_rest( status=compute.Image.Status.DELETING, storage_locations=["storage_locations_value"], ) + # Wrap the value into a proper Response obj json_return_value = compute.Image.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_from_family(request) # Establish that the response is the type that we expect. - assert isinstance(response, compute.Image) assert response.archive_size_bytes == "archive_size_bytes_value" assert response.creation_timestamp == "creation_timestamp_value" @@ -918,7 +931,7 @@ def test_get_from_family_rest_from_dict(): def test_get_from_family_rest_flattened(): - client = ImagesClient(credentials=credentials.AnonymousCredentials(),) + client = ImagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -943,14 +956,12 @@ def test_get_from_family_rest_flattened(): 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 "family_value" in http_call[1] + str(body) def test_get_from_family_rest_flattened_error(): - client = ImagesClient(credentials=credentials.AnonymousCredentials(),) + client = ImagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -966,7 +977,7 @@ def test_get_iam_policy_rest( transport: str = "rest", request_type=compute.GetIamPolicyImageRequest ): client = ImagesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -992,17 +1003,16 @@ def test_get_iam_policy_rest( 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( @@ -1013,7 +1023,6 @@ def test_get_iam_policy_rest( ] 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 @@ -1024,7 +1033,7 @@ def test_get_iam_policy_rest_from_dict(): def test_get_iam_policy_rest_flattened(): - client = ImagesClient(credentials=credentials.AnonymousCredentials(),) + client = ImagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1049,14 +1058,12 @@ def test_get_iam_policy_rest_flattened(): 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) def test_get_iam_policy_rest_flattened_error(): - client = ImagesClient(credentials=credentials.AnonymousCredentials(),) + client = ImagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1070,7 +1077,7 @@ def test_get_iam_policy_rest_flattened_error(): def test_insert_rest(transport: str = "rest", request_type=compute.InsertImageRequest): client = ImagesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1105,17 +1112,16 @@ def test_insert_rest(transport: str = "rest", request_type=compute.InsertImageRe 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" @@ -1149,7 +1155,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = ImagesClient(credentials=credentials.AnonymousCredentials(),) + client = ImagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1166,7 +1172,6 @@ def test_insert_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. image_resource = compute.Image(archive_size_bytes="archive_size_bytes_value") - client.insert( project="project_value", image_resource=image_resource, ) @@ -1176,9 +1181,7 @@ def test_insert_rest_flattened(): 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.Image.to_json( image_resource, including_default_value_fields=False, @@ -1187,7 +1190,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = ImagesClient(credentials=credentials.AnonymousCredentials(),) + client = ImagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1201,7 +1204,7 @@ def test_insert_rest_flattened_error(): def test_list_rest(transport: str = "rest", request_type=compute.ListImagesRequest): client = ImagesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1219,17 +1222,16 @@ def test_list_rest(transport: str = "rest", request_type=compute.ListImagesReque 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.ImageList.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 == [ @@ -1246,7 +1248,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = ImagesClient(credentials=credentials.AnonymousCredentials(),) + client = ImagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1269,12 +1271,11 @@ def test_list_rest_flattened(): 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 = ImagesClient(credentials=credentials.AnonymousCredentials(),) + client = ImagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1285,12 +1286,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = ImagesClient(credentials=credentials.AnonymousCredentials(),) + client = ImagesClient(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.ImageList( items=[compute.Image(), compute.Image(), compute.Image(),], @@ -1300,7 +1300,6 @@ def test_list_pager(): compute.ImageList(items=[compute.Image(),], next_page_token="ghi",), compute.ImageList(items=[compute.Image(), compute.Image(),],), ) - # Two responses for two calls response = response + response @@ -1319,7 +1318,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.Image) for i in results) pages = list(client.list(request={}).pages) @@ -1329,7 +1327,7 @@ def test_list_pager(): def test_patch_rest(transport: str = "rest", request_type=compute.PatchImageRequest): client = ImagesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1364,17 +1362,16 @@ def test_patch_rest(transport: str = "rest", request_type=compute.PatchImageRequ 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" @@ -1408,7 +1405,7 @@ def test_patch_rest_from_dict(): def test_patch_rest_flattened(): - client = ImagesClient(credentials=credentials.AnonymousCredentials(),) + client = ImagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1425,7 +1422,6 @@ def test_patch_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. image_resource = compute.Image(archive_size_bytes="archive_size_bytes_value") - client.patch( project="project_value", image="image_value", image_resource=image_resource, ) @@ -1435,11 +1431,8 @@ def test_patch_rest_flattened(): 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 "image_value" in http_call[1] + str(body) - assert compute.Image.to_json( image_resource, including_default_value_fields=False, @@ -1448,7 +1441,7 @@ def test_patch_rest_flattened(): def test_patch_rest_flattened_error(): - client = ImagesClient(credentials=credentials.AnonymousCredentials(),) + client = ImagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1465,7 +1458,7 @@ def test_set_iam_policy_rest( transport: str = "rest", request_type=compute.SetIamPolicyImageRequest ): client = ImagesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1491,17 +1484,16 @@ def test_set_iam_policy_rest( 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( @@ -1512,7 +1504,6 @@ def test_set_iam_policy_rest( ] 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 @@ -1523,7 +1514,7 @@ def test_set_iam_policy_rest_from_dict(): def test_set_iam_policy_rest_flattened(): - client = ImagesClient(credentials=credentials.AnonymousCredentials(),) + client = ImagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1542,7 +1533,6 @@ def test_set_iam_policy_rest_flattened(): global_set_policy_request_resource = compute.GlobalSetPolicyRequest( bindings=[compute.Binding(binding_id="binding_id_value")] ) - client.set_iam_policy( project="project_value", resource="resource_value", @@ -1554,11 +1544,8 @@ def test_set_iam_policy_rest_flattened(): 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.GlobalSetPolicyRequest.to_json( global_set_policy_request_resource, including_default_value_fields=False, @@ -1567,7 +1554,7 @@ def test_set_iam_policy_rest_flattened(): def test_set_iam_policy_rest_flattened_error(): - client = ImagesClient(credentials=credentials.AnonymousCredentials(),) + client = ImagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1586,7 +1573,7 @@ def test_set_labels_rest( transport: str = "rest", request_type=compute.SetLabelsImageRequest ): client = ImagesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1621,17 +1608,16 @@ def test_set_labels_rest( 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" @@ -1665,7 +1651,7 @@ def test_set_labels_rest_from_dict(): def test_set_labels_rest_flattened(): - client = ImagesClient(credentials=credentials.AnonymousCredentials(),) + client = ImagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1684,7 +1670,6 @@ def test_set_labels_rest_flattened(): global_set_labels_request_resource = compute.GlobalSetLabelsRequest( label_fingerprint="label_fingerprint_value" ) - client.set_labels( project="project_value", resource="resource_value", @@ -1696,11 +1681,8 @@ def test_set_labels_rest_flattened(): 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, @@ -1709,7 +1691,7 @@ def test_set_labels_rest_flattened(): def test_set_labels_rest_flattened_error(): - client = ImagesClient(credentials=credentials.AnonymousCredentials(),) + client = ImagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1728,7 +1710,7 @@ def test_test_iam_permissions_rest( transport: str = "rest", request_type=compute.TestIamPermissionsImageRequest ): client = ImagesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1741,17 +1723,16 @@ def test_test_iam_permissions_rest( 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"] @@ -1761,7 +1742,7 @@ def test_test_iam_permissions_rest_from_dict(): def test_test_iam_permissions_rest_flattened(): - client = ImagesClient(credentials=credentials.AnonymousCredentials(),) + client = ImagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1780,7 +1761,6 @@ def test_test_iam_permissions_rest_flattened(): test_permissions_request_resource = compute.TestPermissionsRequest( permissions=["permissions_value"] ) - client.test_iam_permissions( project="project_value", resource="resource_value", @@ -1792,11 +1772,8 @@ def test_test_iam_permissions_rest_flattened(): 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.TestPermissionsRequest.to_json( test_permissions_request_resource, including_default_value_fields=False, @@ -1805,7 +1782,7 @@ def test_test_iam_permissions_rest_flattened(): def test_test_iam_permissions_rest_flattened_error(): - client = ImagesClient(credentials=credentials.AnonymousCredentials(),) + client = ImagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1823,16 +1800,16 @@ def test_test_iam_permissions_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ImagesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ImagesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.ImagesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ImagesClient( @@ -1842,7 +1819,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ImagesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ImagesClient( @@ -1853,7 +1830,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ImagesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ImagesClient(transport=transport) assert client.transport is transport @@ -1862,17 +1839,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.ImagesRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_images_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ImagesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1884,7 +1861,7 @@ def test_images_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ImagesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1907,15 +1884,40 @@ def test_images_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_images_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.images.transports.ImagesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ImagesTransport( + 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_images_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.images.transports.ImagesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ImagesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1931,19 +1933,36 @@ def test_images_base_transport_with_credentials_file(): def test_images_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.images.transports.ImagesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ImagesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_images_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ImagesClient() + 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_images_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) ImagesClient() adc.assert_called_once_with( scopes=( @@ -1955,7 +1974,7 @@ def test_images_auth_adc(): def test_images_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1967,7 +1986,7 @@ def test_images_http_transport_client_cert_source_for_mtls(): def test_images_host_no_port(): client = ImagesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1977,7 +1996,7 @@ def test_images_host_no_port(): def test_images_host_with_port(): client = ImagesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1987,7 +2006,6 @@ def test_images_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2008,7 +2026,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = ImagesClient.common_folder_path(folder) assert expected == actual @@ -2027,7 +2044,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = ImagesClient.common_organization_path(organization) assert expected == actual @@ -2046,7 +2062,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = ImagesClient.common_project_path(project) assert expected == actual @@ -2066,7 +2081,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2093,7 +2107,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ImagesTransport, "_prep_wrapped_messages" ) as prep: client = ImagesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2102,6 +2116,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ImagesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_instance_group_managers.py b/tests/unit/gapic/compute_v1/test_instance_group_managers.py index 2f4763a50..dc42e79c0 100644 --- a/tests/unit/gapic/compute_v1/test_instance_group_managers.py +++ b/tests/unit/gapic/compute_v1/test_instance_group_managers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,33 +13,63 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.compute_v1.services.instance_group_managers import ( InstanceGroupManagersClient, ) 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, +) 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 +# - 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", +) + +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(): @@ -90,7 +119,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [InstanceGroupManagersClient,]) def test_instance_group_managers_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -105,7 +134,7 @@ def test_instance_group_managers_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [InstanceGroupManagersClient,]) def test_instance_group_managers_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -152,7 +181,7 @@ def test_instance_group_managers_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(InstanceGroupManagersClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -413,7 +442,7 @@ def test_abandon_instances_rest( request_type=compute.AbandonInstancesInstanceGroupManagerRequest, ): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -448,17 +477,16 @@ def test_abandon_instances_rest( 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.abandon_instances(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" @@ -493,7 +521,7 @@ def test_abandon_instances_rest_from_dict(): def test_abandon_instances_rest_flattened(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -513,7 +541,6 @@ def test_abandon_instances_rest_flattened(): instance_group_managers_abandon_instances_request_resource = compute.InstanceGroupManagersAbandonInstancesRequest( instances=["instances_value"] ) - client.abandon_instances( project="project_value", zone="zone_value", @@ -526,13 +553,9 @@ def test_abandon_instances_rest_flattened(): 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_group_manager_value" in http_call[1] + str(body) - assert compute.InstanceGroupManagersAbandonInstancesRequest.to_json( instance_group_managers_abandon_instances_request_resource, including_default_value_fields=False, @@ -542,7 +565,7 @@ def test_abandon_instances_rest_flattened(): def test_abandon_instances_rest_flattened_error(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -564,7 +587,7 @@ def test_aggregated_list_rest( request_type=compute.AggregatedListInstanceGroupManagersRequest, ): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -595,6 +618,7 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.InstanceGroupManagerAggregatedList.to_json( return_value @@ -603,11 +627,9 @@ def test_aggregated_list_rest( 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 == { @@ -636,7 +658,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -662,13 +684,12 @@ def test_aggregated_list_rest_flattened(): 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 = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -682,13 +703,12 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + 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.InstanceGroupManagerAggregatedList( items={ @@ -712,7 +732,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -736,7 +755,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -758,7 +776,7 @@ def test_apply_updates_to_instances_rest( request_type=compute.ApplyUpdatesToInstancesInstanceGroupManagerRequest, ): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -793,17 +811,16 @@ def test_apply_updates_to_instances_rest( 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.apply_updates_to_instances(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" @@ -838,7 +855,7 @@ def test_apply_updates_to_instances_rest_from_dict(): def test_apply_updates_to_instances_rest_flattened(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -858,7 +875,6 @@ def test_apply_updates_to_instances_rest_flattened(): instance_group_managers_apply_updates_request_resource = compute.InstanceGroupManagersApplyUpdatesRequest( all_instances=True ) - client.apply_updates_to_instances( project="project_value", zone="zone_value", @@ -871,13 +887,9 @@ def test_apply_updates_to_instances_rest_flattened(): 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_group_manager_value" in http_call[1] + str(body) - assert compute.InstanceGroupManagersApplyUpdatesRequest.to_json( instance_group_managers_apply_updates_request_resource, including_default_value_fields=False, @@ -887,7 +899,7 @@ def test_apply_updates_to_instances_rest_flattened(): def test_apply_updates_to_instances_rest_flattened_error(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -909,7 +921,7 @@ def test_create_instances_rest( request_type=compute.CreateInstancesInstanceGroupManagerRequest, ): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -944,17 +956,16 @@ def test_create_instances_rest( 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.create_instances(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" @@ -989,7 +1000,7 @@ def test_create_instances_rest_from_dict(): def test_create_instances_rest_flattened(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1009,7 +1020,6 @@ def test_create_instances_rest_flattened(): instance_group_managers_create_instances_request_resource = compute.InstanceGroupManagersCreateInstancesRequest( instances=[compute.PerInstanceConfig(fingerprint="fingerprint_value")] ) - client.create_instances( project="project_value", zone="zone_value", @@ -1022,13 +1032,9 @@ def test_create_instances_rest_flattened(): 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_group_manager_value" in http_call[1] + str(body) - assert compute.InstanceGroupManagersCreateInstancesRequest.to_json( instance_group_managers_create_instances_request_resource, including_default_value_fields=False, @@ -1038,7 +1044,7 @@ def test_create_instances_rest_flattened(): def test_create_instances_rest_flattened_error(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1059,7 +1065,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteInstanceGroupManagerRequest ): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1094,17 +1100,16 @@ def test_delete_rest( 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" @@ -1139,7 +1144,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1167,17 +1172,14 @@ def test_delete_rest_flattened(): 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_group_manager_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1196,7 +1198,7 @@ def test_delete_instances_rest( request_type=compute.DeleteInstancesInstanceGroupManagerRequest, ): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1231,17 +1233,16 @@ def test_delete_instances_rest( 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_instances(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" @@ -1276,7 +1277,7 @@ def test_delete_instances_rest_from_dict(): def test_delete_instances_rest_flattened(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1296,7 +1297,6 @@ def test_delete_instances_rest_flattened(): instance_group_managers_delete_instances_request_resource = compute.InstanceGroupManagersDeleteInstancesRequest( instances=["instances_value"] ) - client.delete_instances( project="project_value", zone="zone_value", @@ -1309,13 +1309,9 @@ def test_delete_instances_rest_flattened(): 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_group_manager_value" in http_call[1] + str(body) - assert compute.InstanceGroupManagersDeleteInstancesRequest.to_json( instance_group_managers_delete_instances_request_resource, including_default_value_fields=False, @@ -1325,7 +1321,7 @@ def test_delete_instances_rest_flattened(): def test_delete_instances_rest_flattened_error(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1347,7 +1343,7 @@ def test_delete_per_instance_configs_rest( request_type=compute.DeletePerInstanceConfigsInstanceGroupManagerRequest, ): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1382,17 +1378,16 @@ def test_delete_per_instance_configs_rest( 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_per_instance_configs(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" @@ -1427,7 +1422,7 @@ def test_delete_per_instance_configs_rest_from_dict(): def test_delete_per_instance_configs_rest_flattened(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1447,7 +1442,6 @@ def test_delete_per_instance_configs_rest_flattened(): instance_group_managers_delete_per_instance_configs_req_resource = compute.InstanceGroupManagersDeletePerInstanceConfigsReq( names=["names_value"] ) - client.delete_per_instance_configs( project="project_value", zone="zone_value", @@ -1460,13 +1454,9 @@ def test_delete_per_instance_configs_rest_flattened(): 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_group_manager_value" in http_call[1] + str(body) - assert compute.InstanceGroupManagersDeletePerInstanceConfigsReq.to_json( instance_group_managers_delete_per_instance_configs_req_resource, including_default_value_fields=False, @@ -1476,7 +1466,7 @@ def test_delete_per_instance_configs_rest_flattened(): def test_delete_per_instance_configs_rest_flattened_error(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1497,7 +1487,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetInstanceGroupManagerRequest ): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1551,17 +1541,16 @@ def test_get_rest( ], zone="zone_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.InstanceGroupManager.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.InstanceGroupManager) assert response.auto_healing_policies == [ compute.InstanceGroupManagerAutoHealingPolicy(health_check="health_check_value") @@ -1613,7 +1602,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1641,17 +1630,14 @@ def test_get_rest_flattened(): 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_group_manager_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1669,7 +1655,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertInstanceGroupManagerRequest ): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1704,17 +1690,16 @@ def test_insert_rest( 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" @@ -1749,7 +1734,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1773,7 +1758,6 @@ def test_insert_rest_flattened(): ) ] ) - client.insert( project="project_value", zone="zone_value", @@ -1785,11 +1769,8 @@ def test_insert_rest_flattened(): 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.InstanceGroupManager.to_json( instance_group_manager_resource, including_default_value_fields=False, @@ -1799,7 +1780,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1823,7 +1804,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListInstanceGroupManagersRequest ): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1849,17 +1830,16 @@ def test_list_rest( 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.InstanceGroupManagerList.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 == [ @@ -1883,7 +1863,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1909,15 +1889,13 @@ def test_list_rest_flattened(): 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) def test_list_rest_flattened_error(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1932,13 +1910,12 @@ def test_list_rest_flattened_error(): def test_list_pager(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + 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.InstanceGroupManagerList( items=[ @@ -1956,7 +1933,6 @@ def test_list_pager(): items=[compute.InstanceGroupManager(), compute.InstanceGroupManager(),], ), ) - # Two responses for two calls response = response + response @@ -1975,7 +1951,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.InstanceGroupManager) for i in results) pages = list(client.list(request={}).pages) @@ -1987,7 +1962,7 @@ def test_list_errors_rest( transport: str = "rest", request_type=compute.ListErrorsInstanceGroupManagersRequest ): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2007,6 +1982,7 @@ def test_list_errors_rest( ], next_page_token="next_page_token_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.InstanceGroupManagersListErrorsResponse.to_json( return_value @@ -2015,11 +1991,9 @@ def test_list_errors_rest( response_value.status_code = 200 response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_errors(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListErrorsPager) assert response.items == [ compute.InstanceManagedByIgmError( @@ -2037,7 +2011,7 @@ def test_list_errors_rest_from_dict(): def test_list_errors_rest_flattened(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -2067,17 +2041,14 @@ def test_list_errors_rest_flattened(): 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_group_manager_value" in http_call[1] + str(body) def test_list_errors_rest_flattened_error(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2093,13 +2064,12 @@ def test_list_errors_rest_flattened_error(): def test_list_errors_pager(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + 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.InstanceGroupManagersListErrorsResponse( items=[ @@ -2122,7 +2092,6 @@ def test_list_errors_pager(): ], ), ) - # Two responses for two calls response = response + response @@ -2143,7 +2112,6 @@ def test_list_errors_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.InstanceManagedByIgmError) for i in results) pages = list(client.list_errors(request={}).pages) @@ -2156,7 +2124,7 @@ def test_list_managed_instances_rest( request_type=compute.ListManagedInstancesInstanceGroupManagersRequest, ): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2174,6 +2142,7 @@ def test_list_managed_instances_rest( ], next_page_token="next_page_token_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.InstanceGroupManagersListManagedInstancesResponse.to_json( return_value @@ -2182,11 +2151,9 @@ def test_list_managed_instances_rest( response_value.status_code = 200 response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_managed_instances(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListManagedInstancesPager) assert response.managed_instances == [ compute.ManagedInstance( @@ -2202,7 +2169,7 @@ def test_list_managed_instances_rest_from_dict(): def test_list_managed_instances_rest_flattened(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -2232,17 +2199,14 @@ def test_list_managed_instances_rest_flattened(): 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_group_manager_value" in http_call[1] + str(body) def test_list_managed_instances_rest_flattened_error(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2258,13 +2222,12 @@ def test_list_managed_instances_rest_flattened_error(): def test_list_managed_instances_pager(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + 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.InstanceGroupManagersListManagedInstancesResponse( managed_instances=[ @@ -2287,7 +2250,6 @@ def test_list_managed_instances_pager(): ], ), ) - # Two responses for two calls response = response + response @@ -2309,7 +2271,6 @@ def test_list_managed_instances_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.ManagedInstance) for i in results) pages = list(client.list_managed_instances(request={}).pages) @@ -2322,7 +2283,7 @@ def test_list_per_instance_configs_rest( request_type=compute.ListPerInstanceConfigsInstanceGroupManagersRequest, ): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2337,6 +2298,7 @@ def test_list_per_instance_configs_rest( 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.InstanceGroupManagersListPerInstanceConfigsResp.to_json( return_value @@ -2345,11 +2307,9 @@ def test_list_per_instance_configs_rest( response_value.status_code = 200 response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_per_instance_configs(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPerInstanceConfigsPager) assert response.items == [ compute.PerInstanceConfig(fingerprint="fingerprint_value") @@ -2364,7 +2324,7 @@ def test_list_per_instance_configs_rest_from_dict(): def test_list_per_instance_configs_rest_flattened(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -2394,17 +2354,14 @@ def test_list_per_instance_configs_rest_flattened(): 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_group_manager_value" in http_call[1] + str(body) def test_list_per_instance_configs_rest_flattened_error(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2420,13 +2377,12 @@ def test_list_per_instance_configs_rest_flattened_error(): def test_list_per_instance_configs_pager(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + 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.InstanceGroupManagersListPerInstanceConfigsResp( items=[ @@ -2446,7 +2402,6 @@ def test_list_per_instance_configs_pager(): items=[compute.PerInstanceConfig(), compute.PerInstanceConfig(),], ), ) - # Two responses for two calls response = response + response @@ -2468,7 +2423,6 @@ def test_list_per_instance_configs_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.PerInstanceConfig) for i in results) pages = list(client.list_per_instance_configs(request={}).pages) @@ -2480,7 +2434,7 @@ def test_patch_rest( transport: str = "rest", request_type=compute.PatchInstanceGroupManagerRequest ): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2515,17 +2469,16 @@ def test_patch_rest( 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" @@ -2560,7 +2513,7 @@ def test_patch_rest_from_dict(): def test_patch_rest_flattened(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -2584,7 +2537,6 @@ def test_patch_rest_flattened(): ) ] ) - client.patch( project="project_value", zone="zone_value", @@ -2597,13 +2549,9 @@ def test_patch_rest_flattened(): 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_group_manager_value" in http_call[1] + str(body) - assert compute.InstanceGroupManager.to_json( instance_group_manager_resource, including_default_value_fields=False, @@ -2613,7 +2561,7 @@ def test_patch_rest_flattened(): def test_patch_rest_flattened_error(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2639,7 +2587,7 @@ def test_patch_per_instance_configs_rest( request_type=compute.PatchPerInstanceConfigsInstanceGroupManagerRequest, ): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2674,17 +2622,16 @@ def test_patch_per_instance_configs_rest( 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_per_instance_configs(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" @@ -2719,7 +2666,7 @@ def test_patch_per_instance_configs_rest_from_dict(): def test_patch_per_instance_configs_rest_flattened(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -2741,7 +2688,6 @@ def test_patch_per_instance_configs_rest_flattened(): compute.PerInstanceConfig(fingerprint="fingerprint_value") ] ) - client.patch_per_instance_configs( project="project_value", zone="zone_value", @@ -2754,13 +2700,9 @@ def test_patch_per_instance_configs_rest_flattened(): 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_group_manager_value" in http_call[1] + str(body) - assert compute.InstanceGroupManagersPatchPerInstanceConfigsReq.to_json( instance_group_managers_patch_per_instance_configs_req_resource, including_default_value_fields=False, @@ -2770,7 +2712,7 @@ def test_patch_per_instance_configs_rest_flattened(): def test_patch_per_instance_configs_rest_flattened_error(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2794,7 +2736,7 @@ def test_recreate_instances_rest( request_type=compute.RecreateInstancesInstanceGroupManagerRequest, ): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2829,17 +2771,16 @@ def test_recreate_instances_rest( 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.recreate_instances(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" @@ -2874,7 +2815,7 @@ def test_recreate_instances_rest_from_dict(): def test_recreate_instances_rest_flattened(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -2894,7 +2835,6 @@ def test_recreate_instances_rest_flattened(): instance_group_managers_recreate_instances_request_resource = compute.InstanceGroupManagersRecreateInstancesRequest( instances=["instances_value"] ) - client.recreate_instances( project="project_value", zone="zone_value", @@ -2907,13 +2847,9 @@ def test_recreate_instances_rest_flattened(): 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_group_manager_value" in http_call[1] + str(body) - assert compute.InstanceGroupManagersRecreateInstancesRequest.to_json( instance_group_managers_recreate_instances_request_resource, including_default_value_fields=False, @@ -2923,7 +2859,7 @@ def test_recreate_instances_rest_flattened(): def test_recreate_instances_rest_flattened_error(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2944,7 +2880,7 @@ def test_resize_rest( transport: str = "rest", request_type=compute.ResizeInstanceGroupManagerRequest ): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2979,17 +2915,16 @@ def test_resize_rest( 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.resize(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" @@ -3024,7 +2959,7 @@ def test_resize_rest_from_dict(): def test_resize_rest_flattened(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -3053,19 +2988,15 @@ def test_resize_rest_flattened(): 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_group_manager_value" in http_call[1] + str(body) - assert str(443) in http_call[1] + str(body) def test_resize_rest_flattened_error(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -3085,7 +3016,7 @@ def test_set_instance_template_rest( request_type=compute.SetInstanceTemplateInstanceGroupManagerRequest, ): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3120,17 +3051,16 @@ def test_set_instance_template_rest( 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_instance_template(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" @@ -3165,7 +3095,7 @@ def test_set_instance_template_rest_from_dict(): def test_set_instance_template_rest_flattened(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -3185,7 +3115,6 @@ def test_set_instance_template_rest_flattened(): instance_group_managers_set_instance_template_request_resource = compute.InstanceGroupManagersSetInstanceTemplateRequest( instance_template="instance_template_value" ) - client.set_instance_template( project="project_value", zone="zone_value", @@ -3198,13 +3127,9 @@ def test_set_instance_template_rest_flattened(): 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_group_manager_value" in http_call[1] + str(body) - assert compute.InstanceGroupManagersSetInstanceTemplateRequest.to_json( instance_group_managers_set_instance_template_request_resource, including_default_value_fields=False, @@ -3214,7 +3139,7 @@ def test_set_instance_template_rest_flattened(): def test_set_instance_template_rest_flattened_error(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -3236,7 +3161,7 @@ def test_set_target_pools_rest( request_type=compute.SetTargetPoolsInstanceGroupManagerRequest, ): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3271,17 +3196,16 @@ def test_set_target_pools_rest( 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_target_pools(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" @@ -3316,7 +3240,7 @@ def test_set_target_pools_rest_from_dict(): def test_set_target_pools_rest_flattened(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -3336,7 +3260,6 @@ def test_set_target_pools_rest_flattened(): instance_group_managers_set_target_pools_request_resource = compute.InstanceGroupManagersSetTargetPoolsRequest( fingerprint="fingerprint_value" ) - client.set_target_pools( project="project_value", zone="zone_value", @@ -3349,13 +3272,9 @@ def test_set_target_pools_rest_flattened(): 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_group_manager_value" in http_call[1] + str(body) - assert compute.InstanceGroupManagersSetTargetPoolsRequest.to_json( instance_group_managers_set_target_pools_request_resource, including_default_value_fields=False, @@ -3365,7 +3284,7 @@ def test_set_target_pools_rest_flattened(): def test_set_target_pools_rest_flattened_error(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -3387,7 +3306,7 @@ def test_update_per_instance_configs_rest( request_type=compute.UpdatePerInstanceConfigsInstanceGroupManagerRequest, ): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3422,17 +3341,16 @@ def test_update_per_instance_configs_rest( 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.update_per_instance_configs(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" @@ -3467,7 +3385,7 @@ def test_update_per_instance_configs_rest_from_dict(): def test_update_per_instance_configs_rest_flattened(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -3489,7 +3407,6 @@ def test_update_per_instance_configs_rest_flattened(): compute.PerInstanceConfig(fingerprint="fingerprint_value") ] ) - client.update_per_instance_configs( project="project_value", zone="zone_value", @@ -3502,13 +3419,9 @@ def test_update_per_instance_configs_rest_flattened(): 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_group_manager_value" in http_call[1] + str(body) - assert compute.InstanceGroupManagersUpdatePerInstanceConfigsReq.to_json( instance_group_managers_update_per_instance_configs_req_resource, including_default_value_fields=False, @@ -3518,7 +3431,7 @@ def test_update_per_instance_configs_rest_flattened(): def test_update_per_instance_configs_rest_flattened_error(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -3540,16 +3453,16 @@ def test_update_per_instance_configs_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.InstanceGroupManagersRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.InstanceGroupManagersRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = InstanceGroupManagersClient( @@ -3559,7 +3472,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.InstanceGroupManagersRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = InstanceGroupManagersClient( @@ -3570,7 +3483,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.InstanceGroupManagersRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = InstanceGroupManagersClient(transport=transport) assert client.transport is transport @@ -3581,17 +3494,17 @@ def test_transport_instance(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_instance_group_managers_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.InstanceGroupManagersTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -3603,7 +3516,7 @@ def test_instance_group_managers_base_transport(): ) as Transport: Transport.return_value = None transport = transports.InstanceGroupManagersTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -3635,15 +3548,40 @@ def test_instance_group_managers_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_instance_group_managers_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.instance_group_managers.transports.InstanceGroupManagersTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.InstanceGroupManagersTransport( + 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_instance_group_managers_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.instance_group_managers.transports.InstanceGroupManagersTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.InstanceGroupManagersTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -3659,19 +3597,36 @@ def test_instance_group_managers_base_transport_with_credentials_file(): def test_instance_group_managers_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.instance_group_managers.transports.InstanceGroupManagersTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.InstanceGroupManagersTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_instance_group_managers_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + InstanceGroupManagersClient() + 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_instance_group_managers_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) InstanceGroupManagersClient() adc.assert_called_once_with( scopes=( @@ -3683,7 +3638,7 @@ def test_instance_group_managers_auth_adc(): def test_instance_group_managers_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -3695,7 +3650,7 @@ def test_instance_group_managers_http_transport_client_cert_source_for_mtls(): def test_instance_group_managers_host_no_port(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -3705,7 +3660,7 @@ def test_instance_group_managers_host_no_port(): def test_instance_group_managers_host_with_port(): client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -3715,7 +3670,6 @@ def test_instance_group_managers_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -3736,7 +3690,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = InstanceGroupManagersClient.common_folder_path(folder) assert expected == actual @@ -3755,7 +3708,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = InstanceGroupManagersClient.common_organization_path(organization) assert expected == actual @@ -3774,7 +3726,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = InstanceGroupManagersClient.common_project_path(project) assert expected == actual @@ -3794,7 +3745,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -3821,7 +3771,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.InstanceGroupManagersTransport, "_prep_wrapped_messages" ) as prep: client = InstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -3830,6 +3780,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = InstanceGroupManagersClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_instance_groups.py b/tests/unit/gapic/compute_v1/test_instance_groups.py index 702ec56ca..1b0835bc8 100644 --- a/tests/unit/gapic/compute_v1/test_instance_groups.py +++ b/tests/unit/gapic/compute_v1/test_instance_groups.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -87,7 +116,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [InstanceGroupsClient,]) def test_instance_groups_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -102,7 +131,7 @@ def test_instance_groups_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [InstanceGroupsClient,]) def test_instance_groups_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -143,7 +172,7 @@ def test_instance_groups_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(InstanceGroupsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -381,7 +410,7 @@ def test_add_instances_rest( transport: str = "rest", request_type=compute.AddInstancesInstanceGroupRequest ): client = InstanceGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -416,17 +445,16 @@ def test_add_instances_rest( 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_instances(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" @@ -460,7 +488,7 @@ def test_add_instances_rest_from_dict(): def test_add_instances_rest_flattened(): - client = InstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -479,7 +507,6 @@ def test_add_instances_rest_flattened(): instance_groups_add_instances_request_resource = compute.InstanceGroupsAddInstancesRequest( instances=[compute.InstanceReference(instance="instance_value")] ) - client.add_instances( project="project_value", zone="zone_value", @@ -492,13 +519,9 @@ def test_add_instances_rest_flattened(): 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_group_value" in http_call[1] + str(body) - assert compute.InstanceGroupsAddInstancesRequest.to_json( instance_groups_add_instances_request_resource, including_default_value_fields=False, @@ -507,7 +530,7 @@ def test_add_instances_rest_flattened(): def test_add_instances_rest_flattened_error(): - client = InstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -527,7 +550,7 @@ def test_aggregated_list_rest( transport: str = "rest", request_type=compute.AggregatedListInstanceGroupsRequest ): client = InstanceGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -554,17 +577,16 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.InstanceGroupAggregatedList.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 == { @@ -586,7 +608,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = InstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -609,12 +631,11 @@ def test_aggregated_list_rest_flattened(): 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 = InstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -625,12 +646,11 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = InstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceGroupsClient(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.InstanceGroupAggregatedList( items={ @@ -651,7 +671,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -675,7 +694,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -696,7 +714,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteInstanceGroupRequest ): client = InstanceGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -731,17 +749,16 @@ def test_delete_rest( 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" @@ -775,7 +792,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = InstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -802,16 +819,13 @@ def test_delete_rest_flattened(): 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_group_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = InstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -828,7 +842,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetInstanceGroupRequest ): client = InstanceGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -853,17 +867,16 @@ def test_get_rest( subnetwork="subnetwork_value", zone="zone_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.InstanceGroup.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.InstanceGroup) assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" @@ -885,7 +898,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = InstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -912,16 +925,13 @@ def test_get_rest_flattened(): 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_group_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = InstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -938,7 +948,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertInstanceGroupRequest ): client = InstanceGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -973,17 +983,16 @@ def test_insert_rest( 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" @@ -1017,7 +1026,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = InstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1036,7 +1045,6 @@ def test_insert_rest_flattened(): instance_group_resource = compute.InstanceGroup( creation_timestamp="creation_timestamp_value" ) - client.insert( project="project_value", zone="zone_value", @@ -1048,11 +1056,8 @@ def test_insert_rest_flattened(): 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.InstanceGroup.to_json( instance_group_resource, including_default_value_fields=False, @@ -1061,7 +1066,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = InstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1080,7 +1085,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListInstanceGroupsRequest ): client = InstanceGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1100,17 +1105,16 @@ def test_list_rest( 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.InstanceGroupList.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 == [ @@ -1127,7 +1131,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = InstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1152,14 +1156,12 @@ def test_list_rest_flattened(): 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) def test_list_rest_flattened_error(): - client = InstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1172,12 +1174,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = InstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceGroupsClient(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.InstanceGroupList( items=[ @@ -1195,7 +1196,6 @@ def test_list_pager(): items=[compute.InstanceGroup(), compute.InstanceGroup(),], ), ) - # Two responses for two calls response = response + response @@ -1214,7 +1214,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.InstanceGroup) for i in results) pages = list(client.list(request={}).pages) @@ -1226,7 +1225,7 @@ def test_list_instances_rest( transport: str = "rest", request_type=compute.ListInstancesInstanceGroupsRequest ): client = InstanceGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1244,17 +1243,16 @@ def test_list_instances_rest( 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.InstanceGroupsListInstances.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_instances(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInstancesPager) assert response.id == "id_value" assert response.items == [compute.InstanceWithNamedPorts(instance="instance_value")] @@ -1269,7 +1267,7 @@ def test_list_instances_rest_from_dict(): def test_list_instances_rest_flattened(): - client = InstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1288,7 +1286,6 @@ def test_list_instances_rest_flattened(): instance_groups_list_instances_request_resource = compute.InstanceGroupsListInstancesRequest( instance_state=compute.InstanceGroupsListInstancesRequest.InstanceState.ALL ) - client.list_instances( project="project_value", zone="zone_value", @@ -1301,13 +1298,9 @@ def test_list_instances_rest_flattened(): 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_group_value" in http_call[1] + str(body) - assert compute.InstanceGroupsListInstancesRequest.to_json( instance_groups_list_instances_request_resource, including_default_value_fields=False, @@ -1316,7 +1309,7 @@ def test_list_instances_rest_flattened(): def test_list_instances_rest_flattened_error(): - client = InstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1333,12 +1326,11 @@ def test_list_instances_rest_flattened_error(): def test_list_instances_pager(): - client = InstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceGroupsClient(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.InstanceGroupsListInstances( items=[ @@ -1359,7 +1351,6 @@ def test_list_instances_pager(): ], ), ) - # Two responses for two calls response = response + response @@ -1380,7 +1371,6 @@ def test_list_instances_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.InstanceWithNamedPorts) for i in results) pages = list(client.list_instances(request={}).pages) @@ -1392,7 +1382,7 @@ def test_remove_instances_rest( transport: str = "rest", request_type=compute.RemoveInstancesInstanceGroupRequest ): client = InstanceGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1427,17 +1417,16 @@ def test_remove_instances_rest( 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_instances(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" @@ -1471,7 +1460,7 @@ def test_remove_instances_rest_from_dict(): def test_remove_instances_rest_flattened(): - client = InstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1490,7 +1479,6 @@ def test_remove_instances_rest_flattened(): instance_groups_remove_instances_request_resource = compute.InstanceGroupsRemoveInstancesRequest( instances=[compute.InstanceReference(instance="instance_value")] ) - client.remove_instances( project="project_value", zone="zone_value", @@ -1503,13 +1491,9 @@ def test_remove_instances_rest_flattened(): 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_group_value" in http_call[1] + str(body) - assert compute.InstanceGroupsRemoveInstancesRequest.to_json( instance_groups_remove_instances_request_resource, including_default_value_fields=False, @@ -1518,7 +1502,7 @@ def test_remove_instances_rest_flattened(): def test_remove_instances_rest_flattened_error(): - client = InstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1538,7 +1522,7 @@ def test_set_named_ports_rest( transport: str = "rest", request_type=compute.SetNamedPortsInstanceGroupRequest ): client = InstanceGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1573,17 +1557,16 @@ def test_set_named_ports_rest( 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_named_ports(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" @@ -1617,7 +1600,7 @@ def test_set_named_ports_rest_from_dict(): def test_set_named_ports_rest_flattened(): - client = InstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1636,7 +1619,6 @@ def test_set_named_ports_rest_flattened(): instance_groups_set_named_ports_request_resource = compute.InstanceGroupsSetNamedPortsRequest( fingerprint="fingerprint_value" ) - client.set_named_ports( project="project_value", zone="zone_value", @@ -1649,13 +1631,9 @@ def test_set_named_ports_rest_flattened(): 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_group_value" in http_call[1] + str(body) - assert compute.InstanceGroupsSetNamedPortsRequest.to_json( instance_groups_set_named_ports_request_resource, including_default_value_fields=False, @@ -1664,7 +1642,7 @@ def test_set_named_ports_rest_flattened(): def test_set_named_ports_rest_flattened_error(): - client = InstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1683,16 +1661,16 @@ def test_set_named_ports_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.InstanceGroupsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = InstanceGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.InstanceGroupsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = InstanceGroupsClient( @@ -1702,7 +1680,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.InstanceGroupsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = InstanceGroupsClient( @@ -1713,7 +1691,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.InstanceGroupsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = InstanceGroupsClient(transport=transport) assert client.transport is transport @@ -1722,17 +1700,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.InstanceGroupsRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_instance_groups_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.InstanceGroupsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1744,7 +1722,7 @@ def test_instance_groups_base_transport(): ) as Transport: Transport.return_value = None transport = transports.InstanceGroupsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1765,15 +1743,40 @@ def test_instance_groups_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_instance_groups_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.instance_groups.transports.InstanceGroupsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.InstanceGroupsTransport( + 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_instance_groups_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.instance_groups.transports.InstanceGroupsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.InstanceGroupsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1789,19 +1792,36 @@ def test_instance_groups_base_transport_with_credentials_file(): def test_instance_groups_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.instance_groups.transports.InstanceGroupsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.InstanceGroupsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_instance_groups_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + InstanceGroupsClient() + 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_instance_groups_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) InstanceGroupsClient() adc.assert_called_once_with( scopes=( @@ -1813,7 +1833,7 @@ def test_instance_groups_auth_adc(): def test_instance_groups_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1825,7 +1845,7 @@ def test_instance_groups_http_transport_client_cert_source_for_mtls(): def test_instance_groups_host_no_port(): client = InstanceGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1835,7 +1855,7 @@ def test_instance_groups_host_no_port(): def test_instance_groups_host_with_port(): client = InstanceGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1845,7 +1865,6 @@ def test_instance_groups_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1866,7 +1885,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = InstanceGroupsClient.common_folder_path(folder) assert expected == actual @@ -1885,7 +1903,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = InstanceGroupsClient.common_organization_path(organization) assert expected == actual @@ -1904,7 +1921,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = InstanceGroupsClient.common_project_path(project) assert expected == actual @@ -1924,7 +1940,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1951,7 +1966,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.InstanceGroupsTransport, "_prep_wrapped_messages" ) as prep: client = InstanceGroupsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1960,6 +1975,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = InstanceGroupsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_instance_templates.py b/tests/unit/gapic/compute_v1/test_instance_templates.py index 9d0d78927..1cc5e0d4c 100644 --- a/tests/unit/gapic/compute_v1/test_instance_templates.py +++ b/tests/unit/gapic/compute_v1/test_instance_templates.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -88,7 +117,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [InstanceTemplatesClient,]) def test_instance_templates_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -103,7 +132,7 @@ def test_instance_templates_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [InstanceTemplatesClient,]) def test_instance_templates_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -144,7 +173,7 @@ def test_instance_templates_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(InstanceTemplatesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -392,7 +421,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteInstanceTemplateRequest ): client = InstanceTemplatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -427,17 +456,16 @@ def test_delete_rest( 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" @@ -471,7 +499,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = InstanceTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -496,14 +524,12 @@ def test_delete_rest_flattened(): 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 "instance_template_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = InstanceTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -519,7 +545,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetInstanceTemplateRequest ): client = InstanceTemplatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -542,17 +568,16 @@ def test_get_rest( disk_configs=[compute.DiskInstantiationConfig(auto_delete=True)] ), ) + # Wrap the value into a proper Response obj json_return_value = compute.InstanceTemplate.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.InstanceTemplate) assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" @@ -572,7 +597,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = InstanceTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -597,14 +622,12 @@ def test_get_rest_flattened(): 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 "instance_template_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = InstanceTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -620,7 +643,7 @@ def test_get_iam_policy_rest( transport: str = "rest", request_type=compute.GetIamPolicyInstanceTemplateRequest ): client = InstanceTemplatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -646,17 +669,16 @@ def test_get_iam_policy_rest( 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( @@ -667,7 +689,6 @@ def test_get_iam_policy_rest( ] 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 @@ -678,7 +699,7 @@ def test_get_iam_policy_rest_from_dict(): def test_get_iam_policy_rest_flattened(): - client = InstanceTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -703,14 +724,12 @@ def test_get_iam_policy_rest_flattened(): 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) def test_get_iam_policy_rest_flattened_error(): - client = InstanceTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -726,7 +745,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertInstanceTemplateRequest ): client = InstanceTemplatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -761,17 +780,16 @@ def test_insert_rest( 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" @@ -805,7 +823,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = InstanceTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -824,7 +842,6 @@ def test_insert_rest_flattened(): instance_template_resource = compute.InstanceTemplate( creation_timestamp="creation_timestamp_value" ) - client.insert( project="project_value", instance_template_resource=instance_template_resource, @@ -835,9 +852,7 @@ def test_insert_rest_flattened(): 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.InstanceTemplate.to_json( instance_template_resource, including_default_value_fields=False, @@ -846,7 +861,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = InstanceTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -864,7 +879,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListInstanceTemplatesRequest ): client = InstanceTemplatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -884,17 +899,16 @@ def test_list_rest( 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.InstanceTemplateList.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 == [ @@ -911,7 +925,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = InstanceTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -934,12 +948,11 @@ def test_list_rest_flattened(): 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 = InstanceTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -950,12 +963,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = InstanceTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceTemplatesClient(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.InstanceTemplateList( items=[ @@ -973,7 +985,6 @@ def test_list_pager(): items=[compute.InstanceTemplate(), compute.InstanceTemplate(),], ), ) - # Two responses for two calls response = response + response @@ -992,7 +1003,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.InstanceTemplate) for i in results) pages = list(client.list(request={}).pages) @@ -1004,7 +1014,7 @@ def test_set_iam_policy_rest( transport: str = "rest", request_type=compute.SetIamPolicyInstanceTemplateRequest ): client = InstanceTemplatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1030,17 +1040,16 @@ def test_set_iam_policy_rest( 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( @@ -1051,7 +1060,6 @@ def test_set_iam_policy_rest( ] 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 @@ -1062,7 +1070,7 @@ def test_set_iam_policy_rest_from_dict(): def test_set_iam_policy_rest_flattened(): - client = InstanceTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1081,7 +1089,6 @@ def test_set_iam_policy_rest_flattened(): global_set_policy_request_resource = compute.GlobalSetPolicyRequest( bindings=[compute.Binding(binding_id="binding_id_value")] ) - client.set_iam_policy( project="project_value", resource="resource_value", @@ -1093,11 +1100,8 @@ def test_set_iam_policy_rest_flattened(): 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.GlobalSetPolicyRequest.to_json( global_set_policy_request_resource, including_default_value_fields=False, @@ -1106,7 +1110,7 @@ def test_set_iam_policy_rest_flattened(): def test_set_iam_policy_rest_flattened_error(): - client = InstanceTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1126,7 +1130,7 @@ def test_test_iam_permissions_rest( request_type=compute.TestIamPermissionsInstanceTemplateRequest, ): client = InstanceTemplatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1139,17 +1143,16 @@ def test_test_iam_permissions_rest( 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"] @@ -1159,7 +1162,7 @@ def test_test_iam_permissions_rest_from_dict(): def test_test_iam_permissions_rest_flattened(): - client = InstanceTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1178,7 +1181,6 @@ def test_test_iam_permissions_rest_flattened(): test_permissions_request_resource = compute.TestPermissionsRequest( permissions=["permissions_value"] ) - client.test_iam_permissions( project="project_value", resource="resource_value", @@ -1190,11 +1192,8 @@ def test_test_iam_permissions_rest_flattened(): 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.TestPermissionsRequest.to_json( test_permissions_request_resource, including_default_value_fields=False, @@ -1203,7 +1202,7 @@ def test_test_iam_permissions_rest_flattened(): def test_test_iam_permissions_rest_flattened_error(): - client = InstanceTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = InstanceTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1221,16 +1220,16 @@ def test_test_iam_permissions_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.InstanceTemplatesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = InstanceTemplatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.InstanceTemplatesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = InstanceTemplatesClient( @@ -1240,7 +1239,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.InstanceTemplatesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = InstanceTemplatesClient( @@ -1251,7 +1250,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.InstanceTemplatesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = InstanceTemplatesClient(transport=transport) assert client.transport is transport @@ -1262,17 +1261,17 @@ def test_transport_instance(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_instance_templates_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.InstanceTemplatesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1284,7 +1283,7 @@ def test_instance_templates_base_transport(): ) as Transport: Transport.return_value = None transport = transports.InstanceTemplatesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1303,15 +1302,40 @@ def test_instance_templates_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_instance_templates_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.instance_templates.transports.InstanceTemplatesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.InstanceTemplatesTransport( + 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_instance_templates_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.instance_templates.transports.InstanceTemplatesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.InstanceTemplatesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1327,19 +1351,36 @@ def test_instance_templates_base_transport_with_credentials_file(): def test_instance_templates_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.instance_templates.transports.InstanceTemplatesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.InstanceTemplatesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_instance_templates_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + InstanceTemplatesClient() + 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_instance_templates_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) InstanceTemplatesClient() adc.assert_called_once_with( scopes=( @@ -1351,7 +1392,7 @@ def test_instance_templates_auth_adc(): def test_instance_templates_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1363,7 +1404,7 @@ def test_instance_templates_http_transport_client_cert_source_for_mtls(): def test_instance_templates_host_no_port(): client = InstanceTemplatesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1373,7 +1414,7 @@ def test_instance_templates_host_no_port(): def test_instance_templates_host_with_port(): client = InstanceTemplatesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1383,7 +1424,6 @@ def test_instance_templates_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1404,7 +1444,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = InstanceTemplatesClient.common_folder_path(folder) assert expected == actual @@ -1423,7 +1462,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = InstanceTemplatesClient.common_organization_path(organization) assert expected == actual @@ -1442,7 +1480,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = InstanceTemplatesClient.common_project_path(project) assert expected == actual @@ -1462,7 +1499,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1489,7 +1525,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.InstanceTemplatesTransport, "_prep_wrapped_messages" ) as prep: client = InstanceTemplatesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1498,6 +1534,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = InstanceTemplatesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_instances.py b/tests/unit/gapic/compute_v1/test_instances.py index fbe11bb1f..319de0ce0 100644 --- a/tests/unit/gapic/compute_v1/test_instances.py +++ b/tests/unit/gapic/compute_v1/test_instances.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,59 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -82,7 +109,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [InstancesClient,]) def test_instances_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -97,7 +124,7 @@ def test_instances_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [InstancesClient,]) def test_instances_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -134,7 +161,7 @@ def test_instances_client_get_transport_class(): def test_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(InstancesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -370,7 +397,7 @@ def test_add_access_config_rest( transport: str = "rest", request_type=compute.AddAccessConfigInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -405,17 +432,16 @@ def test_add_access_config_rest( 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_access_config(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" @@ -449,7 +475,7 @@ def test_add_access_config_rest_from_dict(): def test_add_access_config_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -466,7 +492,6 @@ def test_add_access_config_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. access_config_resource = compute.AccessConfig(kind="kind_value") - client.add_access_config( project="project_value", zone="zone_value", @@ -480,15 +505,10 @@ def test_add_access_config_rest_flattened(): 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) - assert compute.AccessConfig.to_json( access_config_resource, including_default_value_fields=False, @@ -497,7 +517,7 @@ def test_add_access_config_rest_flattened(): def test_add_access_config_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -516,7 +536,7 @@ def test_add_resource_policies_rest( transport: str = "rest", request_type=compute.AddResourcePoliciesInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -551,17 +571,16 @@ def test_add_resource_policies_rest( 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_resource_policies(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" @@ -595,7 +614,7 @@ def test_add_resource_policies_rest_from_dict(): def test_add_resource_policies_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -614,7 +633,6 @@ def test_add_resource_policies_rest_flattened(): instances_add_resource_policies_request_resource = compute.InstancesAddResourcePoliciesRequest( resource_policies=["resource_policies_value"] ) - client.add_resource_policies( project="project_value", zone="zone_value", @@ -627,13 +645,9 @@ def test_add_resource_policies_rest_flattened(): 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 compute.InstancesAddResourcePoliciesRequest.to_json( instances_add_resource_policies_request_resource, including_default_value_fields=False, @@ -642,7 +656,7 @@ def test_add_resource_policies_rest_flattened(): def test_add_resource_policies_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -662,7 +676,7 @@ def test_aggregated_list_rest( transport: str = "rest", request_type=compute.AggregatedListInstancesRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -685,17 +699,16 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.InstanceAggregatedList.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 == { @@ -715,7 +728,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -738,12 +751,11 @@ def test_aggregated_list_rest_flattened(): 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 = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -754,12 +766,11 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: # Set the response as a series of pages - response = ( compute.InstanceAggregatedList( items={ @@ -780,7 +791,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -802,7 +812,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -820,7 +829,7 @@ def test_attach_disk_rest( transport: str = "rest", request_type=compute.AttachDiskInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -855,17 +864,16 @@ def test_attach_disk_rest( 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.attach_disk(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" @@ -899,7 +907,7 @@ def test_attach_disk_rest_from_dict(): def test_attach_disk_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -916,7 +924,6 @@ def test_attach_disk_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. attached_disk_resource = compute.AttachedDisk(auto_delete=True) - client.attach_disk( project="project_value", zone="zone_value", @@ -929,13 +936,9 @@ def test_attach_disk_rest_flattened(): 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 compute.AttachedDisk.to_json( attached_disk_resource, including_default_value_fields=False, @@ -944,7 +947,7 @@ def test_attach_disk_rest_flattened(): def test_attach_disk_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -962,7 +965,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -997,17 +1000,16 @@ def test_delete_rest( 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" @@ -1041,7 +1043,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -1066,16 +1068,13 @@ def test_delete_rest_flattened(): 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) def test_delete_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1092,7 +1091,7 @@ def test_delete_access_config_rest( transport: str = "rest", request_type=compute.DeleteAccessConfigInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1127,17 +1126,16 @@ def test_delete_access_config_rest( 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_access_config(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" @@ -1171,7 +1169,7 @@ def test_delete_access_config_rest_from_dict(): def test_delete_access_config_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -1200,20 +1198,15 @@ def test_delete_access_config_rest_flattened(): 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 "access_config_value" in http_call[1] + str(body) - assert "network_interface_value" in http_call[1] + str(body) def test_delete_access_config_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1232,7 +1225,7 @@ def test_detach_disk_rest( transport: str = "rest", request_type=compute.DetachDiskInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1267,17 +1260,16 @@ def test_detach_disk_rest( 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.detach_disk(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" @@ -1311,7 +1303,7 @@ def test_detach_disk_rest_from_dict(): def test_detach_disk_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -1339,18 +1331,14 @@ def test_detach_disk_rest_flattened(): 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 "device_name_value" in http_call[1] + str(body) def test_detach_disk_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1366,7 +1354,7 @@ def test_detach_disk_rest_flattened_error(): def test_get_rest(transport: str = "rest", request_type=compute.GetInstanceRequest): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1426,26 +1414,23 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetInstanceReque tags=compute.Tags(fingerprint="fingerprint_value"), zone="zone_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.Instance.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.Instance) - assert response.can_ip_forward is True assert response.confidential_instance_config == compute.ConfidentialInstanceConfig( enable_confidential_compute=True ) assert response.cpu_platform == "cpu_platform_value" assert response.creation_timestamp == "creation_timestamp_value" - assert response.deletion_protection is True assert response.description == "description_value" assert response.disks == [compute.AttachedDisk(auto_delete=True)] @@ -1489,7 +1474,6 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetInstanceReque response.shielded_instance_integrity_policy == compute.ShieldedInstanceIntegrityPolicy(update_auto_learn_policy=True) ) - assert response.start_restricted is True assert response.status == compute.Instance.Status.DEPROVISIONING assert response.status_message == "status_message_value" @@ -1502,7 +1486,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -1527,16 +1511,13 @@ def test_get_rest_flattened(): 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) def test_get_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1553,7 +1534,7 @@ def test_get_guest_attributes_rest( transport: str = "rest", request_type=compute.GetGuestAttributesInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1573,17 +1554,16 @@ def test_get_guest_attributes_rest( variable_key="variable_key_value", variable_value="variable_value_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.GuestAttributes.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_guest_attributes(request) # Establish that the response is the type that we expect. - assert isinstance(response, compute.GuestAttributes) assert response.kind == "kind_value" assert response.query_path == "query_path_value" @@ -1600,7 +1580,7 @@ def test_get_guest_attributes_rest_from_dict(): def test_get_guest_attributes_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -1625,16 +1605,13 @@ def test_get_guest_attributes_rest_flattened(): 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) def test_get_guest_attributes_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1651,7 +1628,7 @@ def test_get_iam_policy_rest( transport: str = "rest", request_type=compute.GetIamPolicyInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1677,17 +1654,16 @@ def test_get_iam_policy_rest( 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( @@ -1698,7 +1674,6 @@ def test_get_iam_policy_rest( ] 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 @@ -1709,7 +1684,7 @@ def test_get_iam_policy_rest_from_dict(): def test_get_iam_policy_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -1734,16 +1709,13 @@ def test_get_iam_policy_rest_flattened(): 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 "resource_value" in http_call[1] + str(body) def test_get_iam_policy_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1760,7 +1732,7 @@ def test_get_screenshot_rest( transport: str = "rest", request_type=compute.GetScreenshotInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1771,17 +1743,16 @@ def test_get_screenshot_rest( with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. return_value = compute.Screenshot(contents="contents_value", kind="kind_value",) + # Wrap the value into a proper Response obj json_return_value = compute.Screenshot.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_screenshot(request) # Establish that the response is the type that we expect. - assert isinstance(response, compute.Screenshot) assert response.contents == "contents_value" assert response.kind == "kind_value" @@ -1792,7 +1763,7 @@ def test_get_screenshot_rest_from_dict(): def test_get_screenshot_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -1817,16 +1788,13 @@ def test_get_screenshot_rest_flattened(): 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) def test_get_screenshot_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1843,7 +1811,7 @@ def test_get_serial_port_output_rest( transport: str = "rest", request_type=compute.GetSerialPortOutputInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1860,17 +1828,16 @@ def test_get_serial_port_output_rest( self_link="self_link_value", start="start_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.SerialPortOutput.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_serial_port_output(request) # Establish that the response is the type that we expect. - assert isinstance(response, compute.SerialPortOutput) assert response.contents == "contents_value" assert response.kind == "kind_value" @@ -1884,7 +1851,7 @@ def test_get_serial_port_output_rest_from_dict(): def test_get_serial_port_output_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -1909,16 +1876,13 @@ def test_get_serial_port_output_rest_flattened(): 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) def test_get_serial_port_output_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1936,7 +1900,7 @@ def test_get_shielded_instance_identity_rest( request_type=compute.GetShieldedInstanceIdentityInstanceRequest, ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1953,17 +1917,16 @@ def test_get_shielded_instance_identity_rest( kind="kind_value", signing_key=compute.ShieldedInstanceIdentityEntry(ek_cert="ek_cert_value"), ) + # Wrap the value into a proper Response obj json_return_value = compute.ShieldedInstanceIdentity.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_shielded_instance_identity(request) # Establish that the response is the type that we expect. - assert isinstance(response, compute.ShieldedInstanceIdentity) assert response.encryption_key == compute.ShieldedInstanceIdentityEntry( ek_cert="ek_cert_value" @@ -1979,7 +1942,7 @@ def test_get_shielded_instance_identity_rest_from_dict(): def test_get_shielded_instance_identity_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -2004,16 +1967,13 @@ def test_get_shielded_instance_identity_rest_flattened(): 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) def test_get_shielded_instance_identity_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2030,7 +1990,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2065,17 +2025,16 @@ def test_insert_rest( 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" @@ -2109,7 +2068,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -2126,7 +2085,6 @@ 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) - client.insert( project="project_value", zone="zone_value", @@ -2138,11 +2096,8 @@ def test_insert_rest_flattened(): 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.Instance.to_json( instance_resource, including_default_value_fields=False, @@ -2151,7 +2106,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2166,7 +2121,7 @@ def test_insert_rest_flattened_error(): def test_list_rest(transport: str = "rest", request_type=compute.ListInstancesRequest): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2184,17 +2139,16 @@ def test_list_rest(transport: str = "rest", request_type=compute.ListInstancesRe 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.InstanceList.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.Instance(can_ip_forward=True)] @@ -2209,7 +2163,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -2234,14 +2188,12 @@ def test_list_rest_flattened(): 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) def test_list_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2252,12 +2204,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: # Set the response as a series of pages - response = ( compute.InstanceList( items=[compute.Instance(), compute.Instance(), compute.Instance(),], @@ -2267,7 +2218,6 @@ def test_list_pager(): compute.InstanceList(items=[compute.Instance(),], next_page_token="ghi",), compute.InstanceList(items=[compute.Instance(), compute.Instance(),],), ) - # Two responses for two calls response = response + response @@ -2286,7 +2236,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.Instance) for i in results) pages = list(client.list(request={}).pages) @@ -2298,7 +2247,7 @@ def test_list_referrers_rest( transport: str = "rest", request_type=compute.ListReferrersInstancesRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2316,17 +2265,16 @@ def test_list_referrers_rest( 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.InstanceListReferrers.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_referrers(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListReferrersPager) assert response.id == "id_value" assert response.items == [compute.Reference(kind="kind_value")] @@ -2341,7 +2289,7 @@ def test_list_referrers_rest_from_dict(): def test_list_referrers_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -2366,16 +2314,13 @@ def test_list_referrers_rest_flattened(): 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) def test_list_referrers_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2389,12 +2334,11 @@ def test_list_referrers_rest_flattened_error(): def test_list_referrers_pager(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: # Set the response as a series of pages - response = ( compute.InstanceListReferrers( items=[compute.Reference(), compute.Reference(), compute.Reference(),], @@ -2408,7 +2352,6 @@ def test_list_referrers_pager(): items=[compute.Reference(), compute.Reference(),], ), ) - # Two responses for two calls response = response + response @@ -2427,7 +2370,6 @@ def test_list_referrers_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.Reference) for i in results) pages = list(client.list_referrers(request={}).pages) @@ -2439,7 +2381,7 @@ def test_remove_resource_policies_rest( transport: str = "rest", request_type=compute.RemoveResourcePoliciesInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2474,17 +2416,16 @@ def test_remove_resource_policies_rest( 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_resource_policies(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" @@ -2518,7 +2459,7 @@ def test_remove_resource_policies_rest_from_dict(): def test_remove_resource_policies_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -2537,7 +2478,6 @@ def test_remove_resource_policies_rest_flattened(): instances_remove_resource_policies_request_resource = compute.InstancesRemoveResourcePoliciesRequest( resource_policies=["resource_policies_value"] ) - client.remove_resource_policies( project="project_value", zone="zone_value", @@ -2550,13 +2490,9 @@ def test_remove_resource_policies_rest_flattened(): 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 compute.InstancesRemoveResourcePoliciesRequest.to_json( instances_remove_resource_policies_request_resource, including_default_value_fields=False, @@ -2565,7 +2501,7 @@ def test_remove_resource_policies_rest_flattened(): def test_remove_resource_policies_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2583,7 +2519,7 @@ def test_remove_resource_policies_rest_flattened_error(): def test_reset_rest(transport: str = "rest", request_type=compute.ResetInstanceRequest): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2618,17 +2554,16 @@ def test_reset_rest(transport: str = "rest", request_type=compute.ResetInstanceR 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.reset(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" @@ -2662,7 +2597,7 @@ def test_reset_rest_from_dict(): def test_reset_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -2687,16 +2622,13 @@ def test_reset_rest_flattened(): 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) def test_reset_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2713,7 +2645,7 @@ def test_set_deletion_protection_rest( transport: str = "rest", request_type=compute.SetDeletionProtectionInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2748,17 +2680,16 @@ def test_set_deletion_protection_rest( 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_deletion_protection(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" @@ -2792,7 +2723,7 @@ def test_set_deletion_protection_rest_from_dict(): def test_set_deletion_protection_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -2817,16 +2748,13 @@ def test_set_deletion_protection_rest_flattened(): 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 "resource_value" in http_call[1] + str(body) def test_set_deletion_protection_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2843,7 +2771,7 @@ def test_set_disk_auto_delete_rest( transport: str = "rest", request_type=compute.SetDiskAutoDeleteInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2878,17 +2806,16 @@ def test_set_disk_auto_delete_rest( 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_disk_auto_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" @@ -2922,7 +2849,7 @@ def test_set_disk_auto_delete_rest_from_dict(): def test_set_disk_auto_delete_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -2951,20 +2878,15 @@ def test_set_disk_auto_delete_rest_flattened(): 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 str(True) in http_call[1] + str(body) - assert "device_name_value" in http_call[1] + str(body) def test_set_disk_auto_delete_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2983,7 +2905,7 @@ def test_set_iam_policy_rest( transport: str = "rest", request_type=compute.SetIamPolicyInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3009,17 +2931,16 @@ def test_set_iam_policy_rest( 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( @@ -3030,7 +2951,6 @@ def test_set_iam_policy_rest( ] 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 @@ -3041,7 +2961,7 @@ def test_set_iam_policy_rest_from_dict(): def test_set_iam_policy_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -3060,7 +2980,6 @@ def test_set_iam_policy_rest_flattened(): zone_set_policy_request_resource = compute.ZoneSetPolicyRequest( bindings=[compute.Binding(binding_id="binding_id_value")] ) - client.set_iam_policy( project="project_value", zone="zone_value", @@ -3073,13 +2992,9 @@ def test_set_iam_policy_rest_flattened(): 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 "resource_value" in http_call[1] + str(body) - assert compute.ZoneSetPolicyRequest.to_json( zone_set_policy_request_resource, including_default_value_fields=False, @@ -3088,7 +3003,7 @@ def test_set_iam_policy_rest_flattened(): def test_set_iam_policy_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3108,7 +3023,7 @@ def test_set_labels_rest( transport: str = "rest", request_type=compute.SetLabelsInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3143,17 +3058,16 @@ def test_set_labels_rest( 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" @@ -3187,7 +3101,7 @@ def test_set_labels_rest_from_dict(): def test_set_labels_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -3206,7 +3120,6 @@ def test_set_labels_rest_flattened(): instances_set_labels_request_resource = compute.InstancesSetLabelsRequest( label_fingerprint="label_fingerprint_value" ) - client.set_labels( project="project_value", zone="zone_value", @@ -3219,13 +3132,9 @@ def test_set_labels_rest_flattened(): 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 compute.InstancesSetLabelsRequest.to_json( instances_set_labels_request_resource, including_default_value_fields=False, @@ -3234,7 +3143,7 @@ def test_set_labels_rest_flattened(): def test_set_labels_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3254,7 +3163,7 @@ def test_set_machine_resources_rest( transport: str = "rest", request_type=compute.SetMachineResourcesInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3289,17 +3198,16 @@ def test_set_machine_resources_rest( 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_machine_resources(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" @@ -3333,7 +3241,7 @@ def test_set_machine_resources_rest_from_dict(): def test_set_machine_resources_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -3352,7 +3260,6 @@ def test_set_machine_resources_rest_flattened(): instances_set_machine_resources_request_resource = compute.InstancesSetMachineResourcesRequest( guest_accelerators=[compute.AcceleratorConfig(accelerator_count=1805)] ) - client.set_machine_resources( project="project_value", zone="zone_value", @@ -3365,13 +3272,9 @@ def test_set_machine_resources_rest_flattened(): 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 compute.InstancesSetMachineResourcesRequest.to_json( instances_set_machine_resources_request_resource, including_default_value_fields=False, @@ -3380,7 +3283,7 @@ def test_set_machine_resources_rest_flattened(): def test_set_machine_resources_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3400,7 +3303,7 @@ def test_set_machine_type_rest( transport: str = "rest", request_type=compute.SetMachineTypeInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3435,17 +3338,16 @@ def test_set_machine_type_rest( 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_machine_type(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" @@ -3479,7 +3381,7 @@ def test_set_machine_type_rest_from_dict(): def test_set_machine_type_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -3498,7 +3400,6 @@ def test_set_machine_type_rest_flattened(): instances_set_machine_type_request_resource = compute.InstancesSetMachineTypeRequest( machine_type="machine_type_value" ) - client.set_machine_type( project="project_value", zone="zone_value", @@ -3511,13 +3412,9 @@ def test_set_machine_type_rest_flattened(): 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 compute.InstancesSetMachineTypeRequest.to_json( instances_set_machine_type_request_resource, including_default_value_fields=False, @@ -3526,7 +3423,7 @@ def test_set_machine_type_rest_flattened(): def test_set_machine_type_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3546,7 +3443,7 @@ def test_set_metadata_rest( transport: str = "rest", request_type=compute.SetMetadataInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3581,17 +3478,16 @@ def test_set_metadata_rest( 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_metadata(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" @@ -3625,7 +3521,7 @@ def test_set_metadata_rest_from_dict(): def test_set_metadata_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -3642,7 +3538,6 @@ def test_set_metadata_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. metadata_resource = compute.Metadata(fingerprint="fingerprint_value") - client.set_metadata( project="project_value", zone="zone_value", @@ -3655,13 +3550,9 @@ def test_set_metadata_rest_flattened(): 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 compute.Metadata.to_json( metadata_resource, including_default_value_fields=False, @@ -3670,7 +3561,7 @@ def test_set_metadata_rest_flattened(): def test_set_metadata_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3688,7 +3579,7 @@ def test_set_min_cpu_platform_rest( transport: str = "rest", request_type=compute.SetMinCpuPlatformInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3723,17 +3614,16 @@ def test_set_min_cpu_platform_rest( 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_min_cpu_platform(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" @@ -3767,7 +3657,7 @@ def test_set_min_cpu_platform_rest_from_dict(): def test_set_min_cpu_platform_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -3786,7 +3676,6 @@ def test_set_min_cpu_platform_rest_flattened(): instances_set_min_cpu_platform_request_resource = compute.InstancesSetMinCpuPlatformRequest( min_cpu_platform="min_cpu_platform_value" ) - client.set_min_cpu_platform( project="project_value", zone="zone_value", @@ -3799,13 +3688,9 @@ def test_set_min_cpu_platform_rest_flattened(): 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 compute.InstancesSetMinCpuPlatformRequest.to_json( instances_set_min_cpu_platform_request_resource, including_default_value_fields=False, @@ -3814,7 +3699,7 @@ def test_set_min_cpu_platform_rest_flattened(): def test_set_min_cpu_platform_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3834,7 +3719,7 @@ def test_set_scheduling_rest( transport: str = "rest", request_type=compute.SetSchedulingInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3869,17 +3754,16 @@ def test_set_scheduling_rest( 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_scheduling(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" @@ -3913,7 +3797,7 @@ def test_set_scheduling_rest_from_dict(): def test_set_scheduling_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -3930,7 +3814,6 @@ def test_set_scheduling_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. scheduling_resource = compute.Scheduling(automatic_restart=True) - client.set_scheduling( project="project_value", zone="zone_value", @@ -3943,13 +3826,9 @@ def test_set_scheduling_rest_flattened(): 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 compute.Scheduling.to_json( scheduling_resource, including_default_value_fields=False, @@ -3958,7 +3837,7 @@ def test_set_scheduling_rest_flattened(): def test_set_scheduling_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3976,7 +3855,7 @@ def test_set_service_account_rest( transport: str = "rest", request_type=compute.SetServiceAccountInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4011,17 +3890,16 @@ def test_set_service_account_rest( 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_service_account(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" @@ -4055,7 +3933,7 @@ def test_set_service_account_rest_from_dict(): def test_set_service_account_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -4074,7 +3952,6 @@ def test_set_service_account_rest_flattened(): instances_set_service_account_request_resource = compute.InstancesSetServiceAccountRequest( email="email_value" ) - client.set_service_account( project="project_value", zone="zone_value", @@ -4087,13 +3964,9 @@ def test_set_service_account_rest_flattened(): 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 compute.InstancesSetServiceAccountRequest.to_json( instances_set_service_account_request_resource, including_default_value_fields=False, @@ -4102,7 +3975,7 @@ def test_set_service_account_rest_flattened(): def test_set_service_account_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4123,7 +3996,7 @@ def test_set_shielded_instance_integrity_policy_rest( request_type=compute.SetShieldedInstanceIntegrityPolicyInstanceRequest, ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4158,17 +4031,16 @@ def test_set_shielded_instance_integrity_policy_rest( 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_shielded_instance_integrity_policy(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" @@ -4202,7 +4074,7 @@ def test_set_shielded_instance_integrity_policy_rest_from_dict(): def test_set_shielded_instance_integrity_policy_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -4221,7 +4093,6 @@ def test_set_shielded_instance_integrity_policy_rest_flattened(): shielded_instance_integrity_policy_resource = compute.ShieldedInstanceIntegrityPolicy( update_auto_learn_policy=True ) - client.set_shielded_instance_integrity_policy( project="project_value", zone="zone_value", @@ -4234,13 +4105,9 @@ def test_set_shielded_instance_integrity_policy_rest_flattened(): 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 compute.ShieldedInstanceIntegrityPolicy.to_json( shielded_instance_integrity_policy_resource, including_default_value_fields=False, @@ -4249,7 +4116,7 @@ def test_set_shielded_instance_integrity_policy_rest_flattened(): def test_set_shielded_instance_integrity_policy_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4269,7 +4136,7 @@ def test_set_tags_rest( transport: str = "rest", request_type=compute.SetTagsInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4304,17 +4171,16 @@ def test_set_tags_rest( 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_tags(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" @@ -4348,7 +4214,7 @@ def test_set_tags_rest_from_dict(): def test_set_tags_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -4365,7 +4231,6 @@ def test_set_tags_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. tags_resource = compute.Tags(fingerprint="fingerprint_value") - client.set_tags( project="project_value", zone="zone_value", @@ -4378,13 +4243,9 @@ def test_set_tags_rest_flattened(): 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 compute.Tags.to_json( tags_resource, including_default_value_fields=False, @@ -4393,7 +4254,7 @@ def test_set_tags_rest_flattened(): def test_set_tags_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4412,7 +4273,7 @@ def test_simulate_maintenance_event_rest( request_type=compute.SimulateMaintenanceEventInstanceRequest, ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4447,17 +4308,16 @@ def test_simulate_maintenance_event_rest( 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.simulate_maintenance_event(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" @@ -4491,7 +4351,7 @@ def test_simulate_maintenance_event_rest_from_dict(): def test_simulate_maintenance_event_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -4516,16 +4376,13 @@ def test_simulate_maintenance_event_rest_flattened(): 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) def test_simulate_maintenance_event_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4540,7 +4397,7 @@ def test_simulate_maintenance_event_rest_flattened_error(): def test_start_rest(transport: str = "rest", request_type=compute.StartInstanceRequest): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4575,17 +4432,16 @@ def test_start_rest(transport: str = "rest", request_type=compute.StartInstanceR 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.start(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" @@ -4619,7 +4475,7 @@ def test_start_rest_from_dict(): def test_start_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -4644,16 +4500,13 @@ def test_start_rest_flattened(): 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) def test_start_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4670,7 +4523,7 @@ def test_start_with_encryption_key_rest( transport: str = "rest", request_type=compute.StartWithEncryptionKeyInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4705,17 +4558,16 @@ def test_start_with_encryption_key_rest( 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.start_with_encryption_key(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" @@ -4749,7 +4601,7 @@ def test_start_with_encryption_key_rest_from_dict(): def test_start_with_encryption_key_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -4774,7 +4626,6 @@ def test_start_with_encryption_key_rest_flattened(): ) ] ) - client.start_with_encryption_key( project="project_value", zone="zone_value", @@ -4787,13 +4638,9 @@ def test_start_with_encryption_key_rest_flattened(): 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 compute.InstancesStartWithEncryptionKeyRequest.to_json( instances_start_with_encryption_key_request_resource, including_default_value_fields=False, @@ -4802,7 +4649,7 @@ def test_start_with_encryption_key_rest_flattened(): def test_start_with_encryption_key_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4826,7 +4673,7 @@ def test_start_with_encryption_key_rest_flattened_error(): def test_stop_rest(transport: str = "rest", request_type=compute.StopInstanceRequest): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4861,17 +4708,16 @@ def test_stop_rest(transport: str = "rest", request_type=compute.StopInstanceReq 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.stop(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" @@ -4905,7 +4751,7 @@ def test_stop_rest_from_dict(): def test_stop_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -4930,16 +4776,13 @@ def test_stop_rest_flattened(): 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) def test_stop_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4956,7 +4799,7 @@ def test_test_iam_permissions_rest( transport: str = "rest", request_type=compute.TestIamPermissionsInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4969,17 +4812,16 @@ def test_test_iam_permissions_rest( 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"] @@ -4989,7 +4831,7 @@ def test_test_iam_permissions_rest_from_dict(): def test_test_iam_permissions_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -5008,7 +4850,6 @@ def test_test_iam_permissions_rest_flattened(): test_permissions_request_resource = compute.TestPermissionsRequest( permissions=["permissions_value"] ) - client.test_iam_permissions( project="project_value", zone="zone_value", @@ -5021,13 +4862,9 @@ def test_test_iam_permissions_rest_flattened(): 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 "resource_value" in http_call[1] + str(body) - assert compute.TestPermissionsRequest.to_json( test_permissions_request_resource, including_default_value_fields=False, @@ -5036,7 +4873,7 @@ def test_test_iam_permissions_rest_flattened(): def test_test_iam_permissions_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -5056,7 +4893,7 @@ def test_update_rest( transport: str = "rest", request_type=compute.UpdateInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5091,17 +4928,16 @@ def test_update_rest( 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.update(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" @@ -5135,7 +4971,7 @@ def test_update_rest_from_dict(): def test_update_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -5152,7 +4988,6 @@ 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) - client.update( project="project_value", zone="zone_value", @@ -5165,13 +5000,9 @@ def test_update_rest_flattened(): 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 compute.Instance.to_json( instance_resource, including_default_value_fields=False, @@ -5180,7 +5011,7 @@ def test_update_rest_flattened(): def test_update_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -5198,7 +5029,7 @@ def test_update_access_config_rest( transport: str = "rest", request_type=compute.UpdateAccessConfigInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5233,17 +5064,16 @@ def test_update_access_config_rest( 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.update_access_config(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" @@ -5277,7 +5107,7 @@ def test_update_access_config_rest_from_dict(): def test_update_access_config_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -5294,7 +5124,6 @@ def test_update_access_config_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. access_config_resource = compute.AccessConfig(kind="kind_value") - client.update_access_config( project="project_value", zone="zone_value", @@ -5308,15 +5137,10 @@ def test_update_access_config_rest_flattened(): 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) - assert compute.AccessConfig.to_json( access_config_resource, including_default_value_fields=False, @@ -5325,7 +5149,7 @@ def test_update_access_config_rest_flattened(): def test_update_access_config_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -5344,7 +5168,7 @@ def test_update_display_device_rest( transport: str = "rest", request_type=compute.UpdateDisplayDeviceInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5379,17 +5203,16 @@ def test_update_display_device_rest( 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.update_display_device(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" @@ -5423,7 +5246,7 @@ def test_update_display_device_rest_from_dict(): def test_update_display_device_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -5440,7 +5263,6 @@ def test_update_display_device_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. display_device_resource = compute.DisplayDevice(enable_display=True) - client.update_display_device( project="project_value", zone="zone_value", @@ -5453,13 +5275,9 @@ def test_update_display_device_rest_flattened(): 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 compute.DisplayDevice.to_json( display_device_resource, including_default_value_fields=False, @@ -5468,7 +5286,7 @@ def test_update_display_device_rest_flattened(): def test_update_display_device_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -5486,7 +5304,7 @@ def test_update_network_interface_rest( transport: str = "rest", request_type=compute.UpdateNetworkInterfaceInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5521,17 +5339,16 @@ def test_update_network_interface_rest( 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.update_network_interface(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" @@ -5565,7 +5382,7 @@ def test_update_network_interface_rest_from_dict(): def test_update_network_interface_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -5584,7 +5401,6 @@ def test_update_network_interface_rest_flattened(): network_interface_resource = compute.NetworkInterface( access_configs=[compute.AccessConfig(kind="kind_value")] ) - client.update_network_interface( project="project_value", zone="zone_value", @@ -5598,15 +5414,10 @@ def test_update_network_interface_rest_flattened(): 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) - assert compute.NetworkInterface.to_json( network_interface_resource, including_default_value_fields=False, @@ -5615,7 +5426,7 @@ def test_update_network_interface_rest_flattened(): def test_update_network_interface_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -5637,7 +5448,7 @@ def test_update_shielded_instance_config_rest( request_type=compute.UpdateShieldedInstanceConfigInstanceRequest, ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5672,17 +5483,16 @@ def test_update_shielded_instance_config_rest( 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.update_shielded_instance_config(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" @@ -5716,7 +5526,7 @@ def test_update_shielded_instance_config_rest_from_dict(): def test_update_shielded_instance_config_rest_flattened(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -5735,7 +5545,6 @@ def test_update_shielded_instance_config_rest_flattened(): shielded_instance_config_resource = compute.ShieldedInstanceConfig( enable_integrity_monitoring=True ) - client.update_shielded_instance_config( project="project_value", zone="zone_value", @@ -5748,13 +5557,9 @@ def test_update_shielded_instance_config_rest_flattened(): 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 compute.ShieldedInstanceConfig.to_json( shielded_instance_config_resource, including_default_value_fields=False, @@ -5763,7 +5568,7 @@ def test_update_shielded_instance_config_rest_flattened(): def test_update_shielded_instance_config_rest_flattened_error(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -5782,16 +5587,16 @@ def test_update_shielded_instance_config_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.InstancesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.InstancesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = InstancesClient( @@ -5801,7 +5606,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.InstancesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = InstancesClient( @@ -5812,7 +5617,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.InstancesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = InstancesClient(transport=transport) assert client.transport is transport @@ -5821,17 +5626,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.InstancesRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_instances_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.InstancesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -5843,7 +5648,7 @@ def test_instances_base_transport(): ) as Transport: Transport.return_value = None transport = transports.InstancesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -5895,15 +5700,40 @@ def test_instances_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_instances_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.instances.transports.InstancesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.InstancesTransport( + 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_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.instances.transports.InstancesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.InstancesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -5919,19 +5749,36 @@ def test_instances_base_transport_with_credentials_file(): def test_instances_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.instances.transports.InstancesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.InstancesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_instances_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + InstancesClient() + 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_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) InstancesClient() adc.assert_called_once_with( scopes=( @@ -5943,7 +5790,7 @@ def test_instances_auth_adc(): def test_instances_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -5955,7 +5802,7 @@ def test_instances_http_transport_client_cert_source_for_mtls(): def test_instances_host_no_port(): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -5965,7 +5812,7 @@ def test_instances_host_no_port(): def test_instances_host_with_port(): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -5975,7 +5822,6 @@ def test_instances_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -5996,7 +5842,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = InstancesClient.common_folder_path(folder) assert expected == actual @@ -6015,7 +5860,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = InstancesClient.common_organization_path(organization) assert expected == actual @@ -6034,7 +5878,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = InstancesClient.common_project_path(project) assert expected == actual @@ -6054,7 +5897,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -6081,7 +5923,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.InstancesTransport, "_prep_wrapped_messages" ) as prep: client = InstancesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -6090,6 +5932,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = InstancesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_interconnect_attachments.py b/tests/unit/gapic/compute_v1/test_interconnect_attachments.py index 644843d71..a9a9916fd 100644 --- a/tests/unit/gapic/compute_v1/test_interconnect_attachments.py +++ b/tests/unit/gapic/compute_v1/test_interconnect_attachments.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,33 +13,63 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.compute_v1.services.interconnect_attachments import ( InterconnectAttachmentsClient, ) 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, +) 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 +# - 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", +) + +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(): @@ -90,7 +119,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [InterconnectAttachmentsClient,]) def test_interconnect_attachments_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -105,7 +134,7 @@ def test_interconnect_attachments_client_from_service_account_info(client_class) @pytest.mark.parametrize("client_class", [InterconnectAttachmentsClient,]) def test_interconnect_attachments_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -152,7 +181,7 @@ def test_interconnect_attachments_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(InterconnectAttachmentsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -413,7 +442,7 @@ def test_aggregated_list_rest( request_type=compute.AggregatedListInterconnectAttachmentsRequest, ): client = InterconnectAttachmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -438,6 +467,7 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.InterconnectAttachmentAggregatedList.to_json( return_value @@ -446,11 +476,9 @@ def test_aggregated_list_rest( 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 == { @@ -473,7 +501,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): client = InterconnectAttachmentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -499,13 +527,12 @@ def test_aggregated_list_rest_flattened(): 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 = InterconnectAttachmentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -519,13 +546,12 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): client = InterconnectAttachmentsClient( - credentials=credentials.AnonymousCredentials(), + 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.InterconnectAttachmentAggregatedList( items={ @@ -549,7 +575,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -573,7 +598,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -594,7 +618,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteInterconnectAttachmentRequest ): client = InterconnectAttachmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -629,17 +653,16 @@ def test_delete_rest( 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" @@ -674,7 +697,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): client = InterconnectAttachmentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -702,17 +725,14 @@ def test_delete_rest_flattened(): 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 "interconnect_attachment_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): client = InterconnectAttachmentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -730,7 +750,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetInterconnectAttachmentRequest ): client = InterconnectAttachmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -772,19 +792,17 @@ def test_get_rest( type_=compute.InterconnectAttachment.Type.DEDICATED, vlan_tag8021q=1160, ) + # Wrap the value into a proper Response obj json_return_value = compute.InterconnectAttachment.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.InterconnectAttachment) - assert response.admin_enabled is True assert response.bandwidth == compute.InterconnectAttachment.Bandwidth.BPS_100M assert response.candidate_subnets == ["candidate_subnets_value"] @@ -830,7 +848,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): client = InterconnectAttachmentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -858,17 +876,14 @@ def test_get_rest_flattened(): 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 "interconnect_attachment_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): client = InterconnectAttachmentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -886,7 +901,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertInterconnectAttachmentRequest ): client = InterconnectAttachmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -921,17 +936,16 @@ def test_insert_rest( 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" @@ -966,7 +980,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): client = InterconnectAttachmentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -986,7 +1000,6 @@ def test_insert_rest_flattened(): interconnect_attachment_resource = compute.InterconnectAttachment( admin_enabled=True ) - client.insert( project="project_value", region="region_value", @@ -998,11 +1011,8 @@ def test_insert_rest_flattened(): 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.InterconnectAttachment.to_json( interconnect_attachment_resource, including_default_value_fields=False, @@ -1012,7 +1022,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): client = InterconnectAttachmentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1032,7 +1042,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListInterconnectAttachmentsRequest ): client = InterconnectAttachmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1050,17 +1060,16 @@ def test_list_rest( 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.InterconnectAttachmentList.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.InterconnectAttachment(admin_enabled=True)] @@ -1076,7 +1085,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): client = InterconnectAttachmentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1102,15 +1111,13 @@ def test_list_rest_flattened(): 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 = InterconnectAttachmentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1125,13 +1132,12 @@ def test_list_rest_flattened_error(): def test_list_pager(): client = InterconnectAttachmentsClient( - credentials=credentials.AnonymousCredentials(), + 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.InterconnectAttachmentList( items=[ @@ -1152,7 +1158,6 @@ def test_list_pager(): ], ), ) - # Two responses for two calls response = response + response @@ -1173,7 +1178,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.InterconnectAttachment) for i in results) pages = list(client.list(request={}).pages) @@ -1185,7 +1189,7 @@ def test_patch_rest( transport: str = "rest", request_type=compute.PatchInterconnectAttachmentRequest ): client = InterconnectAttachmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1220,17 +1224,16 @@ def test_patch_rest( 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" @@ -1265,7 +1268,7 @@ def test_patch_rest_from_dict(): def test_patch_rest_flattened(): client = InterconnectAttachmentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1285,7 +1288,6 @@ def test_patch_rest_flattened(): interconnect_attachment_resource = compute.InterconnectAttachment( admin_enabled=True ) - client.patch( project="project_value", region="region_value", @@ -1298,13 +1300,9 @@ def test_patch_rest_flattened(): 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 "interconnect_attachment_value" in http_call[1] + str(body) - assert compute.InterconnectAttachment.to_json( interconnect_attachment_resource, including_default_value_fields=False, @@ -1314,7 +1312,7 @@ def test_patch_rest_flattened(): def test_patch_rest_flattened_error(): client = InterconnectAttachmentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1334,16 +1332,16 @@ def test_patch_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.InterconnectAttachmentsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = InterconnectAttachmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.InterconnectAttachmentsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = InterconnectAttachmentsClient( @@ -1353,7 +1351,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.InterconnectAttachmentsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = InterconnectAttachmentsClient( @@ -1364,7 +1362,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.InterconnectAttachmentsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = InterconnectAttachmentsClient(transport=transport) assert client.transport is transport @@ -1375,17 +1373,17 @@ def test_transport_instance(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_interconnect_attachments_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.InterconnectAttachmentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1397,7 +1395,7 @@ def test_interconnect_attachments_base_transport(): ) as Transport: Transport.return_value = None transport = transports.InterconnectAttachmentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1415,15 +1413,40 @@ def test_interconnect_attachments_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_interconnect_attachments_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.interconnect_attachments.transports.InterconnectAttachmentsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.InterconnectAttachmentsTransport( + 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_interconnect_attachments_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.interconnect_attachments.transports.InterconnectAttachmentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.InterconnectAttachmentsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1439,19 +1462,36 @@ def test_interconnect_attachments_base_transport_with_credentials_file(): def test_interconnect_attachments_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.interconnect_attachments.transports.InterconnectAttachmentsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.InterconnectAttachmentsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_interconnect_attachments_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + InterconnectAttachmentsClient() + 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_interconnect_attachments_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) InterconnectAttachmentsClient() adc.assert_called_once_with( scopes=( @@ -1463,7 +1503,7 @@ def test_interconnect_attachments_auth_adc(): def test_interconnect_attachments_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1475,7 +1515,7 @@ def test_interconnect_attachments_http_transport_client_cert_source_for_mtls(): def test_interconnect_attachments_host_no_port(): client = InterconnectAttachmentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1485,7 +1525,7 @@ def test_interconnect_attachments_host_no_port(): def test_interconnect_attachments_host_with_port(): client = InterconnectAttachmentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1495,7 +1535,6 @@ def test_interconnect_attachments_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1516,7 +1555,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = InterconnectAttachmentsClient.common_folder_path(folder) assert expected == actual @@ -1535,7 +1573,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = InterconnectAttachmentsClient.common_organization_path(organization) assert expected == actual @@ -1554,7 +1591,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = InterconnectAttachmentsClient.common_project_path(project) assert expected == actual @@ -1574,7 +1610,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1601,7 +1636,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.InterconnectAttachmentsTransport, "_prep_wrapped_messages" ) as prep: client = InterconnectAttachmentsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1610,6 +1645,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = InterconnectAttachmentsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_interconnect_locations.py b/tests/unit/gapic/compute_v1/test_interconnect_locations.py index 8109b3448..d0b5f3b95 100644 --- a/tests/unit/gapic/compute_v1/test_interconnect_locations.py +++ b/tests/unit/gapic/compute_v1/test_interconnect_locations.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,33 +13,63 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.compute_v1.services.interconnect_locations import ( InterconnectLocationsClient, ) 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, +) 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 +# - 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", +) + +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(): @@ -90,7 +119,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [InterconnectLocationsClient,]) def test_interconnect_locations_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -105,7 +134,7 @@ def test_interconnect_locations_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [InterconnectLocationsClient,]) def test_interconnect_locations_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -152,7 +181,7 @@ def test_interconnect_locations_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(InterconnectLocationsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -412,7 +441,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetInterconnectLocationRequest ): client = InterconnectLocationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -443,17 +472,16 @@ def test_get_rest( self_link="self_link_value", status=compute.InterconnectLocation.Status.AVAILABLE, ) + # Wrap the value into a proper Response obj json_return_value = compute.InterconnectLocation.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.InterconnectLocation) assert response.address == "address_value" assert response.availability_zone == "availability_zone_value" @@ -482,7 +510,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): client = InterconnectLocationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -509,15 +537,13 @@ def test_get_rest_flattened(): 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 "interconnect_location_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): client = InterconnectLocationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -534,7 +560,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListInterconnectLocationsRequest ): client = InterconnectLocationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -552,17 +578,16 @@ def test_list_rest( 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.InterconnectLocationList.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.InterconnectLocation(address="address_value")] @@ -578,7 +603,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): client = InterconnectLocationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -602,13 +627,12 @@ def test_list_rest_flattened(): 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 = InterconnectLocationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -621,13 +645,12 @@ def test_list_rest_flattened_error(): def test_list_pager(): client = InterconnectLocationsClient( - credentials=credentials.AnonymousCredentials(), + 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.InterconnectLocationList( items=[ @@ -645,7 +668,6 @@ def test_list_pager(): items=[compute.InterconnectLocation(), compute.InterconnectLocation(),], ), ) - # Two responses for two calls response = response + response @@ -664,7 +686,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.InterconnectLocation) for i in results) pages = list(client.list(request={}).pages) @@ -675,16 +696,16 @@ def test_list_pager(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.InterconnectLocationsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = InterconnectLocationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.InterconnectLocationsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = InterconnectLocationsClient( @@ -694,7 +715,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.InterconnectLocationsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = InterconnectLocationsClient( @@ -705,7 +726,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.InterconnectLocationsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = InterconnectLocationsClient(transport=transport) assert client.transport is transport @@ -716,17 +737,17 @@ def test_transport_instance(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_interconnect_locations_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.InterconnectLocationsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -738,7 +759,7 @@ def test_interconnect_locations_base_transport(): ) as Transport: Transport.return_value = None transport = transports.InterconnectLocationsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -752,15 +773,41 @@ def test_interconnect_locations_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_interconnect_locations_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.interconnect_locations.transports.InterconnectLocationsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.InterconnectLocationsTransport( + 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.readonly", + "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_interconnect_locations_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.interconnect_locations.transports.InterconnectLocationsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.InterconnectLocationsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -777,19 +824,37 @@ def test_interconnect_locations_base_transport_with_credentials_file(): def test_interconnect_locations_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.interconnect_locations.transports.InterconnectLocationsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.InterconnectLocationsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_interconnect_locations_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + InterconnectLocationsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/compute.readonly", + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_interconnect_locations_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) InterconnectLocationsClient() adc.assert_called_once_with( scopes=( @@ -802,7 +867,7 @@ def test_interconnect_locations_auth_adc(): def test_interconnect_locations_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -814,7 +879,7 @@ def test_interconnect_locations_http_transport_client_cert_source_for_mtls(): def test_interconnect_locations_host_no_port(): client = InterconnectLocationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -824,7 +889,7 @@ def test_interconnect_locations_host_no_port(): def test_interconnect_locations_host_with_port(): client = InterconnectLocationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -834,7 +899,6 @@ def test_interconnect_locations_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -855,7 +919,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = InterconnectLocationsClient.common_folder_path(folder) assert expected == actual @@ -874,7 +937,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = InterconnectLocationsClient.common_organization_path(organization) assert expected == actual @@ -893,7 +955,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = InterconnectLocationsClient.common_project_path(project) assert expected == actual @@ -913,7 +974,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -940,7 +1000,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.InterconnectLocationsTransport, "_prep_wrapped_messages" ) as prep: client = InterconnectLocationsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -949,6 +1009,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = InterconnectLocationsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_interconnects.py b/tests/unit/gapic/compute_v1/test_interconnects.py index 86e749db9..528d548ff 100644 --- a/tests/unit/gapic/compute_v1/test_interconnects.py +++ b/tests/unit/gapic/compute_v1/test_interconnects.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -87,7 +116,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [InterconnectsClient,]) def test_interconnects_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -102,7 +131,7 @@ def test_interconnects_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [InterconnectsClient,]) def test_interconnects_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -143,7 +172,7 @@ def test_interconnects_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(InterconnectsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -381,7 +410,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteInterconnectRequest ): client = InterconnectsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -416,17 +445,16 @@ def test_delete_rest( 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" @@ -460,7 +488,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = InterconnectsClient(credentials=credentials.AnonymousCredentials(),) + client = InterconnectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -485,14 +513,12 @@ def test_delete_rest_flattened(): 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 "interconnect_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = InterconnectsClient(credentials=credentials.AnonymousCredentials(),) + client = InterconnectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -506,7 +532,7 @@ def test_delete_rest_flattened_error(): def test_get_rest(transport: str = "rest", request_type=compute.GetInterconnectRequest): client = InterconnectsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -548,19 +574,17 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetInterconnectR self_link="self_link_value", state=compute.Interconnect.State.ACTIVE, ) + # Wrap the value into a proper Response obj json_return_value = compute.Interconnect.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.Interconnect) - assert response.admin_enabled is True assert response.circuit_infos == [ compute.InterconnectCircuitInfo(customer_demarc_id="customer_demarc_id_value") @@ -600,7 +624,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = InterconnectsClient(credentials=credentials.AnonymousCredentials(),) + client = InterconnectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -625,14 +649,12 @@ def test_get_rest_flattened(): 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 "interconnect_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = InterconnectsClient(credentials=credentials.AnonymousCredentials(),) + client = InterconnectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -648,7 +670,7 @@ def test_get_diagnostics_rest( transport: str = "rest", request_type=compute.GetDiagnosticsInterconnectRequest ): client = InterconnectsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -667,6 +689,7 @@ def test_get_diagnostics_rest( ] ), ) + # Wrap the value into a proper Response obj json_return_value = compute.InterconnectsGetDiagnosticsResponse.to_json( return_value @@ -675,11 +698,9 @@ def test_get_diagnostics_rest( response_value.status_code = 200 response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_diagnostics(request) # Establish that the response is the type that we expect. - assert isinstance(response, compute.InterconnectsGetDiagnosticsResponse) assert response.result == compute.InterconnectDiagnostics( arp_caches=[ @@ -693,7 +714,7 @@ def test_get_diagnostics_rest_from_dict(): def test_get_diagnostics_rest_flattened(): - client = InterconnectsClient(credentials=credentials.AnonymousCredentials(),) + client = InterconnectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -720,14 +741,12 @@ def test_get_diagnostics_rest_flattened(): 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 "interconnect_value" in http_call[1] + str(body) def test_get_diagnostics_rest_flattened_error(): - client = InterconnectsClient(credentials=credentials.AnonymousCredentials(),) + client = InterconnectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -743,7 +762,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertInterconnectRequest ): client = InterconnectsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -778,17 +797,16 @@ def test_insert_rest( 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" @@ -822,7 +840,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = InterconnectsClient(credentials=credentials.AnonymousCredentials(),) + client = InterconnectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -839,7 +857,6 @@ def test_insert_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. interconnect_resource = compute.Interconnect(admin_enabled=True) - client.insert( project="project_value", interconnect_resource=interconnect_resource, ) @@ -849,9 +866,7 @@ def test_insert_rest_flattened(): 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.Interconnect.to_json( interconnect_resource, including_default_value_fields=False, @@ -860,7 +875,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = InterconnectsClient(credentials=credentials.AnonymousCredentials(),) + client = InterconnectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -876,7 +891,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListInterconnectsRequest ): client = InterconnectsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -894,17 +909,16 @@ def test_list_rest( 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.InterconnectList.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.Interconnect(admin_enabled=True)] @@ -919,7 +933,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = InterconnectsClient(credentials=credentials.AnonymousCredentials(),) + client = InterconnectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -942,12 +956,11 @@ def test_list_rest_flattened(): 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 = InterconnectsClient(credentials=credentials.AnonymousCredentials(),) + client = InterconnectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -958,12 +971,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = InterconnectsClient(credentials=credentials.AnonymousCredentials(),) + client = InterconnectsClient(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.InterconnectList( items=[ @@ -981,7 +993,6 @@ def test_list_pager(): items=[compute.Interconnect(), compute.Interconnect(),], ), ) - # Two responses for two calls response = response + response @@ -1000,7 +1011,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.Interconnect) for i in results) pages = list(client.list(request={}).pages) @@ -1012,7 +1022,7 @@ def test_patch_rest( transport: str = "rest", request_type=compute.PatchInterconnectRequest ): client = InterconnectsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1047,17 +1057,16 @@ def test_patch_rest( 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" @@ -1091,7 +1100,7 @@ def test_patch_rest_from_dict(): def test_patch_rest_flattened(): - client = InterconnectsClient(credentials=credentials.AnonymousCredentials(),) + client = InterconnectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1108,7 +1117,6 @@ def test_patch_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. interconnect_resource = compute.Interconnect(admin_enabled=True) - client.patch( project="project_value", interconnect="interconnect_value", @@ -1120,11 +1128,8 @@ def test_patch_rest_flattened(): 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 "interconnect_value" in http_call[1] + str(body) - assert compute.Interconnect.to_json( interconnect_resource, including_default_value_fields=False, @@ -1133,7 +1138,7 @@ def test_patch_rest_flattened(): def test_patch_rest_flattened_error(): - client = InterconnectsClient(credentials=credentials.AnonymousCredentials(),) + client = InterconnectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1149,16 +1154,16 @@ def test_patch_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.InterconnectsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = InterconnectsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.InterconnectsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = InterconnectsClient( @@ -1168,7 +1173,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.InterconnectsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = InterconnectsClient( @@ -1179,7 +1184,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.InterconnectsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = InterconnectsClient(transport=transport) assert client.transport is transport @@ -1188,17 +1193,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.InterconnectsRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_interconnects_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.InterconnectsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1210,7 +1215,7 @@ def test_interconnects_base_transport(): ) as Transport: Transport.return_value = None transport = transports.InterconnectsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1228,15 +1233,40 @@ def test_interconnects_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_interconnects_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.interconnects.transports.InterconnectsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.InterconnectsTransport( + 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_interconnects_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.interconnects.transports.InterconnectsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.InterconnectsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1252,19 +1282,36 @@ def test_interconnects_base_transport_with_credentials_file(): def test_interconnects_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.interconnects.transports.InterconnectsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.InterconnectsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_interconnects_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + InterconnectsClient() + 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_interconnects_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) InterconnectsClient() adc.assert_called_once_with( scopes=( @@ -1276,7 +1323,7 @@ def test_interconnects_auth_adc(): def test_interconnects_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1288,7 +1335,7 @@ def test_interconnects_http_transport_client_cert_source_for_mtls(): def test_interconnects_host_no_port(): client = InterconnectsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1298,7 +1345,7 @@ def test_interconnects_host_no_port(): def test_interconnects_host_with_port(): client = InterconnectsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1308,7 +1355,6 @@ def test_interconnects_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1329,7 +1375,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = InterconnectsClient.common_folder_path(folder) assert expected == actual @@ -1348,7 +1393,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = InterconnectsClient.common_organization_path(organization) assert expected == actual @@ -1367,7 +1411,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = InterconnectsClient.common_project_path(project) assert expected == actual @@ -1387,7 +1430,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1414,7 +1456,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.InterconnectsTransport, "_prep_wrapped_messages" ) as prep: client = InterconnectsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1423,6 +1465,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = InterconnectsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_license_codes.py b/tests/unit/gapic/compute_v1/test_license_codes.py index ea01780d6..a0176fc5a 100644 --- a/tests/unit/gapic/compute_v1/test_license_codes.py +++ b/tests/unit/gapic/compute_v1/test_license_codes.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,30 +13,60 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials 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, +) 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 +# - 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", +) + +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(): @@ -83,7 +112,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [LicenseCodesClient,]) def test_license_codes_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -98,7 +127,7 @@ def test_license_codes_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [LicenseCodesClient,]) def test_license_codes_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -137,7 +166,7 @@ def test_license_codes_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(LicenseCodesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -371,7 +400,7 @@ def test_license_codes_client_client_options_credentials_file( def test_get_rest(transport: str = "rest", request_type=compute.GetLicenseCodeRequest): client = LicenseCodesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -394,17 +423,16 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetLicenseCodeRe state=compute.LicenseCode.State.DISABLED, transferable=True, ) + # Wrap the value into a proper Response obj json_return_value = compute.LicenseCode.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.LicenseCode) assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" @@ -416,7 +444,6 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetLicenseCodeRe assert response.name == "name_value" assert response.self_link == "self_link_value" assert response.state == compute.LicenseCode.State.DISABLED - assert response.transferable is True @@ -425,7 +452,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = LicenseCodesClient(credentials=credentials.AnonymousCredentials(),) + client = LicenseCodesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -450,14 +477,12 @@ def test_get_rest_flattened(): 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 "license_code_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = LicenseCodesClient(credentials=credentials.AnonymousCredentials(),) + client = LicenseCodesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -473,7 +498,7 @@ def test_test_iam_permissions_rest( transport: str = "rest", request_type=compute.TestIamPermissionsLicenseCodeRequest ): client = LicenseCodesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -486,17 +511,16 @@ def test_test_iam_permissions_rest( 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"] @@ -506,7 +530,7 @@ def test_test_iam_permissions_rest_from_dict(): def test_test_iam_permissions_rest_flattened(): - client = LicenseCodesClient(credentials=credentials.AnonymousCredentials(),) + client = LicenseCodesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -525,7 +549,6 @@ def test_test_iam_permissions_rest_flattened(): test_permissions_request_resource = compute.TestPermissionsRequest( permissions=["permissions_value"] ) - client.test_iam_permissions( project="project_value", resource="resource_value", @@ -537,11 +560,8 @@ def test_test_iam_permissions_rest_flattened(): 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.TestPermissionsRequest.to_json( test_permissions_request_resource, including_default_value_fields=False, @@ -550,7 +570,7 @@ def test_test_iam_permissions_rest_flattened(): def test_test_iam_permissions_rest_flattened_error(): - client = LicenseCodesClient(credentials=credentials.AnonymousCredentials(),) + client = LicenseCodesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -568,16 +588,16 @@ def test_test_iam_permissions_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.LicenseCodesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = LicenseCodesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.LicenseCodesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = LicenseCodesClient( @@ -587,7 +607,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.LicenseCodesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = LicenseCodesClient( @@ -598,7 +618,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.LicenseCodesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = LicenseCodesClient(transport=transport) assert client.transport is transport @@ -607,17 +627,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.LicenseCodesRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_license_codes_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.LicenseCodesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -629,7 +649,7 @@ def test_license_codes_base_transport(): ) as Transport: Transport.return_value = None transport = transports.LicenseCodesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -643,15 +663,41 @@ def test_license_codes_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_license_codes_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.license_codes.transports.LicenseCodesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LicenseCodesTransport( + 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.readonly", + "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_license_codes_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.license_codes.transports.LicenseCodesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.LicenseCodesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -668,19 +714,37 @@ def test_license_codes_base_transport_with_credentials_file(): def test_license_codes_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.license_codes.transports.LicenseCodesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.LicenseCodesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_license_codes_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + LicenseCodesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/compute.readonly", + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_license_codes_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) LicenseCodesClient() adc.assert_called_once_with( scopes=( @@ -693,7 +757,7 @@ def test_license_codes_auth_adc(): def test_license_codes_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -705,7 +769,7 @@ def test_license_codes_http_transport_client_cert_source_for_mtls(): def test_license_codes_host_no_port(): client = LicenseCodesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -715,7 +779,7 @@ def test_license_codes_host_no_port(): def test_license_codes_host_with_port(): client = LicenseCodesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -725,7 +789,6 @@ def test_license_codes_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -746,7 +809,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = LicenseCodesClient.common_folder_path(folder) assert expected == actual @@ -765,7 +827,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = LicenseCodesClient.common_organization_path(organization) assert expected == actual @@ -784,7 +845,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = LicenseCodesClient.common_project_path(project) assert expected == actual @@ -804,7 +864,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -831,7 +890,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.LicenseCodesTransport, "_prep_wrapped_messages" ) as prep: client = LicenseCodesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -840,6 +899,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = LicenseCodesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_licenses.py b/tests/unit/gapic/compute_v1/test_licenses.py index ec59233bb..3412a7815 100644 --- a/tests/unit/gapic/compute_v1/test_licenses.py +++ b/tests/unit/gapic/compute_v1/test_licenses.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,59 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -82,7 +109,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [LicensesClient,]) def test_licenses_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -97,7 +124,7 @@ def test_licenses_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [LicensesClient,]) def test_licenses_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -134,7 +161,7 @@ def test_licenses_client_get_transport_class(): def test_licenses_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(LicensesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -370,7 +397,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteLicenseRequest ): client = LicensesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -405,17 +432,16 @@ def test_delete_rest( 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" @@ -449,7 +475,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = LicensesClient(credentials=credentials.AnonymousCredentials(),) + client = LicensesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -474,14 +500,12 @@ def test_delete_rest_flattened(): 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 "license__value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = LicensesClient(credentials=credentials.AnonymousCredentials(),) + client = LicensesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -495,7 +519,7 @@ def test_delete_rest_flattened_error(): def test_get_rest(transport: str = "rest", request_type=compute.GetLicenseRequest): client = LicensesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -519,19 +543,17 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetLicenseReques self_link="self_link_value", transferable=True, ) + # Wrap the value into a proper Response obj json_return_value = compute.License.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.License) - assert response.charges_use_fee is True assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" @@ -543,7 +565,6 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetLicenseReques min_guest_cpu_count=2042 ) assert response.self_link == "self_link_value" - assert response.transferable is True @@ -552,7 +573,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = LicensesClient(credentials=credentials.AnonymousCredentials(),) + client = LicensesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -577,14 +598,12 @@ def test_get_rest_flattened(): 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 "license__value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = LicensesClient(credentials=credentials.AnonymousCredentials(),) + client = LicensesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -600,7 +619,7 @@ def test_get_iam_policy_rest( transport: str = "rest", request_type=compute.GetIamPolicyLicenseRequest ): client = LicensesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -626,17 +645,16 @@ def test_get_iam_policy_rest( 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( @@ -647,7 +665,6 @@ def test_get_iam_policy_rest( ] 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 @@ -658,7 +675,7 @@ def test_get_iam_policy_rest_from_dict(): def test_get_iam_policy_rest_flattened(): - client = LicensesClient(credentials=credentials.AnonymousCredentials(),) + client = LicensesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -683,14 +700,12 @@ def test_get_iam_policy_rest_flattened(): 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) def test_get_iam_policy_rest_flattened_error(): - client = LicensesClient(credentials=credentials.AnonymousCredentials(),) + client = LicensesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -706,7 +721,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertLicenseRequest ): client = LicensesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -741,17 +756,16 @@ def test_insert_rest( 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" @@ -785,7 +799,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = LicensesClient(credentials=credentials.AnonymousCredentials(),) + client = LicensesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -802,7 +816,6 @@ def test_insert_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. license_resource = compute.License(charges_use_fee=True) - client.insert( project="project_value", license_resource=license_resource, ) @@ -812,9 +825,7 @@ def test_insert_rest_flattened(): 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.License.to_json( license_resource, including_default_value_fields=False, @@ -823,7 +834,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = LicensesClient(credentials=credentials.AnonymousCredentials(),) + client = LicensesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -837,7 +848,7 @@ def test_insert_rest_flattened_error(): def test_list_rest(transport: str = "rest", request_type=compute.ListLicensesRequest): client = LicensesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -854,17 +865,16 @@ def test_list_rest(transport: str = "rest", request_type=compute.ListLicensesReq 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.LicensesListResponse.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.License(charges_use_fee=True)] @@ -878,7 +888,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = LicensesClient(credentials=credentials.AnonymousCredentials(),) + client = LicensesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -901,12 +911,11 @@ def test_list_rest_flattened(): 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 = LicensesClient(credentials=credentials.AnonymousCredentials(),) + client = LicensesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -917,12 +926,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = LicensesClient(credentials=credentials.AnonymousCredentials(),) + client = LicensesClient(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.LicensesListResponse( items=[compute.License(), compute.License(), compute.License(),], @@ -936,7 +944,6 @@ def test_list_pager(): items=[compute.License(), compute.License(),], ), ) - # Two responses for two calls response = response + response @@ -955,7 +962,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.License) for i in results) pages = list(client.list(request={}).pages) @@ -967,7 +973,7 @@ def test_set_iam_policy_rest( transport: str = "rest", request_type=compute.SetIamPolicyLicenseRequest ): client = LicensesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -993,17 +999,16 @@ def test_set_iam_policy_rest( 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( @@ -1014,7 +1019,6 @@ def test_set_iam_policy_rest( ] 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 @@ -1025,7 +1029,7 @@ def test_set_iam_policy_rest_from_dict(): def test_set_iam_policy_rest_flattened(): - client = LicensesClient(credentials=credentials.AnonymousCredentials(),) + client = LicensesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1044,7 +1048,6 @@ def test_set_iam_policy_rest_flattened(): global_set_policy_request_resource = compute.GlobalSetPolicyRequest( bindings=[compute.Binding(binding_id="binding_id_value")] ) - client.set_iam_policy( project="project_value", resource="resource_value", @@ -1056,11 +1059,8 @@ def test_set_iam_policy_rest_flattened(): 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.GlobalSetPolicyRequest.to_json( global_set_policy_request_resource, including_default_value_fields=False, @@ -1069,7 +1069,7 @@ def test_set_iam_policy_rest_flattened(): def test_set_iam_policy_rest_flattened_error(): - client = LicensesClient(credentials=credentials.AnonymousCredentials(),) + client = LicensesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1088,7 +1088,7 @@ def test_test_iam_permissions_rest( transport: str = "rest", request_type=compute.TestIamPermissionsLicenseRequest ): client = LicensesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1101,17 +1101,16 @@ def test_test_iam_permissions_rest( 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"] @@ -1121,7 +1120,7 @@ def test_test_iam_permissions_rest_from_dict(): def test_test_iam_permissions_rest_flattened(): - client = LicensesClient(credentials=credentials.AnonymousCredentials(),) + client = LicensesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1140,7 +1139,6 @@ def test_test_iam_permissions_rest_flattened(): test_permissions_request_resource = compute.TestPermissionsRequest( permissions=["permissions_value"] ) - client.test_iam_permissions( project="project_value", resource="resource_value", @@ -1152,11 +1150,8 @@ def test_test_iam_permissions_rest_flattened(): 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.TestPermissionsRequest.to_json( test_permissions_request_resource, including_default_value_fields=False, @@ -1165,7 +1160,7 @@ def test_test_iam_permissions_rest_flattened(): def test_test_iam_permissions_rest_flattened_error(): - client = LicensesClient(credentials=credentials.AnonymousCredentials(),) + client = LicensesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1183,16 +1178,16 @@ def test_test_iam_permissions_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.LicensesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = LicensesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.LicensesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = LicensesClient( @@ -1202,7 +1197,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.LicensesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = LicensesClient( @@ -1213,7 +1208,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.LicensesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = LicensesClient(transport=transport) assert client.transport is transport @@ -1222,17 +1217,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.LicensesRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_licenses_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.LicensesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1244,7 +1239,7 @@ def test_licenses_base_transport(): ) as Transport: Transport.return_value = None transport = transports.LicensesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1263,15 +1258,40 @@ def test_licenses_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_licenses_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.licenses.transports.LicensesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LicensesTransport( + 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_licenses_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.licenses.transports.LicensesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.LicensesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1287,19 +1307,36 @@ def test_licenses_base_transport_with_credentials_file(): def test_licenses_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.licenses.transports.LicensesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.LicensesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_licenses_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + LicensesClient() + 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_licenses_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) LicensesClient() adc.assert_called_once_with( scopes=( @@ -1311,7 +1348,7 @@ def test_licenses_auth_adc(): def test_licenses_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1323,7 +1360,7 @@ def test_licenses_http_transport_client_cert_source_for_mtls(): def test_licenses_host_no_port(): client = LicensesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1333,7 +1370,7 @@ def test_licenses_host_no_port(): def test_licenses_host_with_port(): client = LicensesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1343,7 +1380,6 @@ def test_licenses_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1364,7 +1400,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = LicensesClient.common_folder_path(folder) assert expected == actual @@ -1383,7 +1418,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = LicensesClient.common_organization_path(organization) assert expected == actual @@ -1402,7 +1436,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = LicensesClient.common_project_path(project) assert expected == actual @@ -1422,7 +1455,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1449,7 +1481,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.LicensesTransport, "_prep_wrapped_messages" ) as prep: client = LicensesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1458,6 +1490,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = LicensesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_machine_types.py b/tests/unit/gapic/compute_v1/test_machine_types.py index ce3fdb0b1..ed104fedb 100644 --- a/tests/unit/gapic/compute_v1/test_machine_types.py +++ b/tests/unit/gapic/compute_v1/test_machine_types.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -84,7 +113,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [MachineTypesClient,]) def test_machine_types_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -99,7 +128,7 @@ def test_machine_types_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [MachineTypesClient,]) def test_machine_types_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -138,7 +167,7 @@ def test_machine_types_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(MachineTypesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -374,7 +403,7 @@ def test_aggregated_list_rest( transport: str = "rest", request_type=compute.AggregatedListMachineTypesRequest ): client = MachineTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -403,17 +432,16 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.MachineTypeAggregatedList.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 == { @@ -437,7 +465,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = MachineTypesClient(credentials=credentials.AnonymousCredentials(),) + client = MachineTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -460,12 +488,11 @@ def test_aggregated_list_rest_flattened(): 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 = MachineTypesClient(credentials=credentials.AnonymousCredentials(),) + client = MachineTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -476,12 +503,11 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = MachineTypesClient(credentials=credentials.AnonymousCredentials(),) + client = MachineTypesClient(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.MachineTypeAggregatedList( items={ @@ -502,7 +528,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -524,7 +549,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -543,7 +567,7 @@ def test_aggregated_list_pager(): def test_get_rest(transport: str = "rest", request_type=compute.GetMachineTypeRequest): client = MachineTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -571,17 +595,16 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetMachineTypeRe self_link="self_link_value", zone="zone_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.MachineType.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.MachineType) assert response.accelerators == [compute.Accelerators(guest_accelerator_count=2452)] assert response.creation_timestamp == "creation_timestamp_value" @@ -590,7 +613,6 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetMachineTypeRe assert response.guest_cpus == 1090 assert response.id == "id_value" assert response.image_space_gb == 1430 - assert response.is_shared_cpu is True assert response.kind == "kind_value" assert response.maximum_persistent_disks == 2603 @@ -610,7 +632,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = MachineTypesClient(credentials=credentials.AnonymousCredentials(),) + client = MachineTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -637,16 +659,13 @@ def test_get_rest_flattened(): 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 "machine_type_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = MachineTypesClient(credentials=credentials.AnonymousCredentials(),) + client = MachineTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -663,7 +682,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListMachineTypesRequest ): client = MachineTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -685,17 +704,16 @@ def test_list_rest( 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.MachineTypeList.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 == [ @@ -714,7 +732,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = MachineTypesClient(credentials=credentials.AnonymousCredentials(),) + client = MachineTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -739,14 +757,12 @@ def test_list_rest_flattened(): 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) def test_list_rest_flattened_error(): - client = MachineTypesClient(credentials=credentials.AnonymousCredentials(),) + client = MachineTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -759,12 +775,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = MachineTypesClient(credentials=credentials.AnonymousCredentials(),) + client = MachineTypesClient(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.MachineTypeList( items=[ @@ -782,7 +797,6 @@ def test_list_pager(): items=[compute.MachineType(), compute.MachineType(),], ), ) - # Two responses for two calls response = response + response @@ -801,7 +815,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.MachineType) for i in results) pages = list(client.list(request={}).pages) @@ -812,16 +825,16 @@ def test_list_pager(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.MachineTypesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = MachineTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.MachineTypesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = MachineTypesClient( @@ -831,7 +844,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.MachineTypesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = MachineTypesClient( @@ -842,7 +855,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.MachineTypesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = MachineTypesClient(transport=transport) assert client.transport is transport @@ -851,17 +864,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.MachineTypesRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_machine_types_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.MachineTypesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -873,7 +886,7 @@ def test_machine_types_base_transport(): ) as Transport: Transport.return_value = None transport = transports.MachineTypesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -888,15 +901,41 @@ def test_machine_types_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_machine_types_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.machine_types.transports.MachineTypesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.MachineTypesTransport( + 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.readonly", + "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_machine_types_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.machine_types.transports.MachineTypesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.MachineTypesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -913,19 +952,37 @@ def test_machine_types_base_transport_with_credentials_file(): def test_machine_types_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.machine_types.transports.MachineTypesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.MachineTypesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_machine_types_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + MachineTypesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/compute.readonly", + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_machine_types_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) MachineTypesClient() adc.assert_called_once_with( scopes=( @@ -938,7 +995,7 @@ def test_machine_types_auth_adc(): def test_machine_types_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -950,7 +1007,7 @@ def test_machine_types_http_transport_client_cert_source_for_mtls(): def test_machine_types_host_no_port(): client = MachineTypesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -960,7 +1017,7 @@ def test_machine_types_host_no_port(): def test_machine_types_host_with_port(): client = MachineTypesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -970,7 +1027,6 @@ def test_machine_types_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -991,7 +1047,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = MachineTypesClient.common_folder_path(folder) assert expected == actual @@ -1010,7 +1065,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = MachineTypesClient.common_organization_path(organization) assert expected == actual @@ -1029,7 +1083,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = MachineTypesClient.common_project_path(project) assert expected == actual @@ -1049,7 +1102,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1076,7 +1128,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.MachineTypesTransport, "_prep_wrapped_messages" ) as prep: client = MachineTypesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1085,6 +1137,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = MachineTypesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_network_endpoint_groups.py b/tests/unit/gapic/compute_v1/test_network_endpoint_groups.py index 1cee30b2c..9f3cc9e56 100644 --- a/tests/unit/gapic/compute_v1/test_network_endpoint_groups.py +++ b/tests/unit/gapic/compute_v1/test_network_endpoint_groups.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,33 +13,63 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.compute_v1.services.network_endpoint_groups import ( NetworkEndpointGroupsClient, ) 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, +) 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 +# - 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", +) + +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(): @@ -90,7 +119,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [NetworkEndpointGroupsClient,]) def test_network_endpoint_groups_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -105,7 +134,7 @@ def test_network_endpoint_groups_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [NetworkEndpointGroupsClient,]) def test_network_endpoint_groups_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -152,7 +181,7 @@ def test_network_endpoint_groups_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(NetworkEndpointGroupsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -413,7 +442,7 @@ def test_aggregated_list_rest( request_type=compute.AggregatedListNetworkEndpointGroupsRequest, ): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -440,6 +469,7 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.NetworkEndpointGroupAggregatedList.to_json( return_value @@ -448,11 +478,9 @@ def test_aggregated_list_rest( 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 == { @@ -475,7 +503,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -501,13 +529,12 @@ def test_aggregated_list_rest_flattened(): 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 = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -521,13 +548,12 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + 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.NetworkEndpointGroupAggregatedList( items={ @@ -551,7 +577,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -575,7 +600,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -597,7 +621,7 @@ def test_attach_network_endpoints_rest( request_type=compute.AttachNetworkEndpointsNetworkEndpointGroupRequest, ): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -632,17 +656,16 @@ def test_attach_network_endpoints_rest( 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.attach_network_endpoints(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" @@ -677,7 +700,7 @@ def test_attach_network_endpoints_rest_from_dict(): def test_attach_network_endpoints_rest_flattened(): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -699,7 +722,6 @@ def test_attach_network_endpoints_rest_flattened(): compute.NetworkEndpoint(annotations={"key_value": "value_value"}) ] ) - client.attach_network_endpoints( project="project_value", zone="zone_value", @@ -712,13 +734,9 @@ def test_attach_network_endpoints_rest_flattened(): 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 "network_endpoint_group_value" in http_call[1] + str(body) - assert compute.NetworkEndpointGroupsAttachEndpointsRequest.to_json( network_endpoint_groups_attach_endpoints_request_resource, including_default_value_fields=False, @@ -728,7 +746,7 @@ def test_attach_network_endpoints_rest_flattened(): def test_attach_network_endpoints_rest_flattened_error(): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -751,7 +769,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteNetworkEndpointGroupRequest ): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -786,17 +804,16 @@ def test_delete_rest( 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" @@ -831,7 +848,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -859,17 +876,14 @@ def test_delete_rest_flattened(): 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 "network_endpoint_group_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -888,7 +902,7 @@ def test_detach_network_endpoints_rest( request_type=compute.DetachNetworkEndpointsNetworkEndpointGroupRequest, ): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -923,17 +937,16 @@ def test_detach_network_endpoints_rest( 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.detach_network_endpoints(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" @@ -968,7 +981,7 @@ def test_detach_network_endpoints_rest_from_dict(): def test_detach_network_endpoints_rest_flattened(): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -990,7 +1003,6 @@ def test_detach_network_endpoints_rest_flattened(): compute.NetworkEndpoint(annotations={"key_value": "value_value"}) ] ) - client.detach_network_endpoints( project="project_value", zone="zone_value", @@ -1003,13 +1015,9 @@ def test_detach_network_endpoints_rest_flattened(): 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 "network_endpoint_group_value" in http_call[1] + str(body) - assert compute.NetworkEndpointGroupsDetachEndpointsRequest.to_json( network_endpoint_groups_detach_endpoints_request_resource, including_default_value_fields=False, @@ -1019,7 +1027,7 @@ def test_detach_network_endpoints_rest_flattened(): def test_detach_network_endpoints_rest_flattened_error(): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1042,7 +1050,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetNetworkEndpointGroupRequest ): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1073,17 +1081,16 @@ def test_get_rest( subnetwork="subnetwork_value", zone="zone_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.NetworkEndpointGroup.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.NetworkEndpointGroup) assert response.annotations == {"key_value": "value_value"} assert response.app_engine == compute.NetworkEndpointGroupAppEngine( @@ -1119,7 +1126,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1147,17 +1154,14 @@ def test_get_rest_flattened(): 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 "network_endpoint_group_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1175,7 +1179,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertNetworkEndpointGroupRequest ): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1210,17 +1214,16 @@ def test_insert_rest( 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" @@ -1255,7 +1258,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1275,7 +1278,6 @@ def test_insert_rest_flattened(): network_endpoint_group_resource = compute.NetworkEndpointGroup( annotations={"key_value": "value_value"} ) - client.insert( project="project_value", zone="zone_value", @@ -1287,11 +1289,8 @@ def test_insert_rest_flattened(): 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.NetworkEndpointGroup.to_json( network_endpoint_group_resource, including_default_value_fields=False, @@ -1301,7 +1300,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1321,7 +1320,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListNetworkEndpointGroupsRequest ): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1341,17 +1340,16 @@ def test_list_rest( 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.NetworkEndpointGroupList.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 == [ @@ -1369,7 +1367,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1395,15 +1393,13 @@ def test_list_rest_flattened(): 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) def test_list_rest_flattened_error(): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1418,13 +1414,12 @@ def test_list_rest_flattened_error(): def test_list_pager(): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + 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.NetworkEndpointGroupList( items=[ @@ -1442,7 +1437,6 @@ def test_list_pager(): items=[compute.NetworkEndpointGroup(), compute.NetworkEndpointGroup(),], ), ) - # Two responses for two calls response = response + response @@ -1461,7 +1455,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.NetworkEndpointGroup) for i in results) pages = list(client.list(request={}).pages) @@ -1474,7 +1467,7 @@ def test_list_network_endpoints_rest( request_type=compute.ListNetworkEndpointsNetworkEndpointGroupsRequest, ): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1501,6 +1494,7 @@ def test_list_network_endpoints_rest( 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.NetworkEndpointGroupsListNetworkEndpoints.to_json( return_value @@ -1509,11 +1503,9 @@ def test_list_network_endpoints_rest( response_value.status_code = 200 response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_network_endpoints(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNetworkEndpointsPager) assert response.id == "id_value" assert response.items == [ @@ -1538,7 +1530,7 @@ def test_list_network_endpoints_rest_from_dict(): def test_list_network_endpoints_rest_flattened(): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1560,7 +1552,6 @@ def test_list_network_endpoints_rest_flattened(): network_endpoint_groups_list_endpoints_request_resource = compute.NetworkEndpointGroupsListEndpointsRequest( health_status=compute.NetworkEndpointGroupsListEndpointsRequest.HealthStatus.SHOW ) - client.list_network_endpoints( project="project_value", zone="zone_value", @@ -1573,13 +1564,9 @@ def test_list_network_endpoints_rest_flattened(): 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 "network_endpoint_group_value" in http_call[1] + str(body) - assert compute.NetworkEndpointGroupsListEndpointsRequest.to_json( network_endpoint_groups_list_endpoints_request_resource, including_default_value_fields=False, @@ -1589,7 +1576,7 @@ def test_list_network_endpoints_rest_flattened(): def test_list_network_endpoints_rest_flattened_error(): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1608,13 +1595,12 @@ def test_list_network_endpoints_rest_flattened_error(): def test_list_network_endpoints_pager(): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + 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.NetworkEndpointGroupsListNetworkEndpoints( items=[ @@ -1638,7 +1624,6 @@ def test_list_network_endpoints_pager(): ], ), ) - # Two responses for two calls response = response + response @@ -1660,7 +1645,6 @@ def test_list_network_endpoints_pager(): results = list(pager) assert len(results) == 6 - assert all( isinstance(i, compute.NetworkEndpointWithHealthStatus) for i in results ) @@ -1675,7 +1659,7 @@ def test_test_iam_permissions_rest( request_type=compute.TestIamPermissionsNetworkEndpointGroupRequest, ): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1688,17 +1672,16 @@ def test_test_iam_permissions_rest( 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"] @@ -1709,7 +1692,7 @@ def test_test_iam_permissions_rest_from_dict(): def test_test_iam_permissions_rest_flattened(): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1729,7 +1712,6 @@ def test_test_iam_permissions_rest_flattened(): test_permissions_request_resource = compute.TestPermissionsRequest( permissions=["permissions_value"] ) - client.test_iam_permissions( project="project_value", zone="zone_value", @@ -1742,13 +1724,9 @@ def test_test_iam_permissions_rest_flattened(): 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 "resource_value" in http_call[1] + str(body) - assert compute.TestPermissionsRequest.to_json( test_permissions_request_resource, including_default_value_fields=False, @@ -1758,7 +1736,7 @@ def test_test_iam_permissions_rest_flattened(): def test_test_iam_permissions_rest_flattened_error(): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1778,16 +1756,16 @@ def test_test_iam_permissions_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.NetworkEndpointGroupsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.NetworkEndpointGroupsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = NetworkEndpointGroupsClient( @@ -1797,7 +1775,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.NetworkEndpointGroupsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = NetworkEndpointGroupsClient( @@ -1808,7 +1786,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.NetworkEndpointGroupsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = NetworkEndpointGroupsClient(transport=transport) assert client.transport is transport @@ -1819,17 +1797,17 @@ def test_transport_instance(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_network_endpoint_groups_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.NetworkEndpointGroupsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1841,7 +1819,7 @@ def test_network_endpoint_groups_base_transport(): ) as Transport: Transport.return_value = None transport = transports.NetworkEndpointGroupsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1862,15 +1840,40 @@ def test_network_endpoint_groups_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_network_endpoint_groups_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.network_endpoint_groups.transports.NetworkEndpointGroupsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.NetworkEndpointGroupsTransport( + 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_network_endpoint_groups_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.network_endpoint_groups.transports.NetworkEndpointGroupsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.NetworkEndpointGroupsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1886,19 +1889,36 @@ def test_network_endpoint_groups_base_transport_with_credentials_file(): def test_network_endpoint_groups_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.network_endpoint_groups.transports.NetworkEndpointGroupsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.NetworkEndpointGroupsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_network_endpoint_groups_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + NetworkEndpointGroupsClient() + 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_network_endpoint_groups_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) NetworkEndpointGroupsClient() adc.assert_called_once_with( scopes=( @@ -1910,7 +1930,7 @@ def test_network_endpoint_groups_auth_adc(): def test_network_endpoint_groups_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1922,7 +1942,7 @@ def test_network_endpoint_groups_http_transport_client_cert_source_for_mtls(): def test_network_endpoint_groups_host_no_port(): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1932,7 +1952,7 @@ def test_network_endpoint_groups_host_no_port(): def test_network_endpoint_groups_host_with_port(): client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1942,7 +1962,6 @@ def test_network_endpoint_groups_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1963,7 +1982,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = NetworkEndpointGroupsClient.common_folder_path(folder) assert expected == actual @@ -1982,7 +2000,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = NetworkEndpointGroupsClient.common_organization_path(organization) assert expected == actual @@ -2001,7 +2018,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = NetworkEndpointGroupsClient.common_project_path(project) assert expected == actual @@ -2021,7 +2037,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2048,7 +2063,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.NetworkEndpointGroupsTransport, "_prep_wrapped_messages" ) as prep: client = NetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2057,6 +2072,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = NetworkEndpointGroupsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_networks.py b/tests/unit/gapic/compute_v1/test_networks.py index ba66e2ce9..67fe1caba 100644 --- a/tests/unit/gapic/compute_v1/test_networks.py +++ b/tests/unit/gapic/compute_v1/test_networks.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,59 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -82,7 +109,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [NetworksClient,]) def test_networks_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -97,7 +124,7 @@ def test_networks_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [NetworksClient,]) def test_networks_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -134,7 +161,7 @@ def test_networks_client_get_transport_class(): def test_networks_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(NetworksClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -370,7 +397,7 @@ def test_add_peering_rest( transport: str = "rest", request_type=compute.AddPeeringNetworkRequest ): client = NetworksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -405,17 +432,16 @@ def test_add_peering_rest( 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_peering(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" @@ -449,7 +475,7 @@ def test_add_peering_rest_from_dict(): def test_add_peering_rest_flattened(): - client = NetworksClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -468,7 +494,6 @@ def test_add_peering_rest_flattened(): networks_add_peering_request_resource = compute.NetworksAddPeeringRequest( auto_create_routes=True ) - client.add_peering( project="project_value", network="network_value", @@ -480,11 +505,8 @@ def test_add_peering_rest_flattened(): 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) - assert compute.NetworksAddPeeringRequest.to_json( networks_add_peering_request_resource, including_default_value_fields=False, @@ -493,7 +515,7 @@ def test_add_peering_rest_flattened(): def test_add_peering_rest_flattened_error(): - client = NetworksClient(credentials=credentials.AnonymousCredentials(),) + client = NetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -512,7 +534,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteNetworkRequest ): client = NetworksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -547,17 +569,16 @@ def test_delete_rest( 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" @@ -591,7 +612,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = NetworksClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -616,14 +637,12 @@ def test_delete_rest_flattened(): 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_delete_rest_flattened_error(): - client = NetworksClient(credentials=credentials.AnonymousCredentials(),) + client = NetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -637,7 +656,7 @@ def test_delete_rest_flattened_error(): def test_get_rest(transport: str = "rest", request_type=compute.GetNetworkRequest): client = NetworksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -664,19 +683,17 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetNetworkReques self_link="self_link_value", subnetworks=["subnetworks_value"], ) + # Wrap the value into a proper Response obj json_return_value = compute.Network.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.Network) - assert response.auto_create_subnetworks is True assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" @@ -699,7 +716,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = NetworksClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -724,14 +741,12 @@ def test_get_rest_flattened(): 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_rest_flattened_error(): - client = NetworksClient(credentials=credentials.AnonymousCredentials(),) + client = NetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -747,7 +762,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertNetworkRequest ): client = NetworksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -782,17 +797,16 @@ def test_insert_rest( 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" @@ -826,7 +840,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = NetworksClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -843,7 +857,6 @@ 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) - client.insert( project="project_value", network_resource=network_resource, ) @@ -853,9 +866,7 @@ def test_insert_rest_flattened(): 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.Network.to_json( network_resource, including_default_value_fields=False, @@ -864,7 +875,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = NetworksClient(credentials=credentials.AnonymousCredentials(),) + client = NetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -878,7 +889,7 @@ def test_insert_rest_flattened_error(): def test_list_rest(transport: str = "rest", request_type=compute.ListNetworksRequest): client = NetworksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -896,17 +907,16 @@ def test_list_rest(transport: str = "rest", request_type=compute.ListNetworksReq 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.NetworkList.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.Network(auto_create_subnetworks=True)] @@ -921,7 +931,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = NetworksClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -944,12 +954,11 @@ def test_list_rest_flattened(): 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 = NetworksClient(credentials=credentials.AnonymousCredentials(),) + client = NetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -960,12 +969,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = NetworksClient(credentials=credentials.AnonymousCredentials(),) + 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: # Set the response as a series of pages - response = ( compute.NetworkList( items=[compute.Network(), compute.Network(), compute.Network(),], @@ -975,7 +983,6 @@ def test_list_pager(): compute.NetworkList(items=[compute.Network(),], next_page_token="ghi",), compute.NetworkList(items=[compute.Network(), compute.Network(),],), ) - # Two responses for two calls response = response + response @@ -994,7 +1001,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.Network) for i in results) pages = list(client.list(request={}).pages) @@ -1006,7 +1012,7 @@ def test_list_peering_routes_rest( transport: str = "rest", request_type=compute.ListPeeringRoutesNetworksRequest ): client = NetworksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1024,17 +1030,16 @@ def test_list_peering_routes_rest( 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.ExchangedPeeringRoutesList.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_peering_routes(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPeeringRoutesPager) assert response.id == "id_value" assert response.items == [ @@ -1051,7 +1056,7 @@ def test_list_peering_routes_rest_from_dict(): def test_list_peering_routes_rest_flattened(): - client = NetworksClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -1076,14 +1081,12 @@ def test_list_peering_routes_rest_flattened(): 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_list_peering_routes_rest_flattened_error(): - client = NetworksClient(credentials=credentials.AnonymousCredentials(),) + client = NetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1096,12 +1099,11 @@ def test_list_peering_routes_rest_flattened_error(): def test_list_peering_routes_pager(): - client = NetworksClient(credentials=credentials.AnonymousCredentials(),) + 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: # Set the response as a series of pages - response = ( compute.ExchangedPeeringRoutesList( items=[ @@ -1122,7 +1124,6 @@ def test_list_peering_routes_pager(): ], ), ) - # Two responses for two calls response = response + response @@ -1143,7 +1144,6 @@ def test_list_peering_routes_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.ExchangedPeeringRoute) for i in results) pages = list(client.list_peering_routes(request={}).pages) @@ -1153,7 +1153,7 @@ def test_list_peering_routes_pager(): def test_patch_rest(transport: str = "rest", request_type=compute.PatchNetworkRequest): client = NetworksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1188,17 +1188,16 @@ def test_patch_rest(transport: str = "rest", request_type=compute.PatchNetworkRe 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" @@ -1232,7 +1231,7 @@ def test_patch_rest_from_dict(): def test_patch_rest_flattened(): - client = NetworksClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -1249,7 +1248,6 @@ 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) - client.patch( project="project_value", network="network_value", @@ -1261,11 +1259,8 @@ def test_patch_rest_flattened(): 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) - assert compute.Network.to_json( network_resource, including_default_value_fields=False, @@ -1274,7 +1269,7 @@ def test_patch_rest_flattened(): def test_patch_rest_flattened_error(): - client = NetworksClient(credentials=credentials.AnonymousCredentials(),) + client = NetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1291,7 +1286,7 @@ def test_remove_peering_rest( transport: str = "rest", request_type=compute.RemovePeeringNetworkRequest ): client = NetworksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1326,17 +1321,16 @@ def test_remove_peering_rest( 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_peering(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" @@ -1370,7 +1364,7 @@ def test_remove_peering_rest_from_dict(): def test_remove_peering_rest_flattened(): - client = NetworksClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -1389,7 +1383,6 @@ def test_remove_peering_rest_flattened(): networks_remove_peering_request_resource = compute.NetworksRemovePeeringRequest( name="name_value" ) - client.remove_peering( project="project_value", network="network_value", @@ -1401,11 +1394,8 @@ def test_remove_peering_rest_flattened(): 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) - assert compute.NetworksRemovePeeringRequest.to_json( networks_remove_peering_request_resource, including_default_value_fields=False, @@ -1414,7 +1404,7 @@ def test_remove_peering_rest_flattened(): def test_remove_peering_rest_flattened_error(): - client = NetworksClient(credentials=credentials.AnonymousCredentials(),) + client = NetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1433,7 +1423,7 @@ def test_switch_to_custom_mode_rest( transport: str = "rest", request_type=compute.SwitchToCustomModeNetworkRequest ): client = NetworksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1468,17 +1458,16 @@ def test_switch_to_custom_mode_rest( 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.switch_to_custom_mode(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" @@ -1512,7 +1501,7 @@ def test_switch_to_custom_mode_rest_from_dict(): def test_switch_to_custom_mode_rest_flattened(): - client = NetworksClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -1537,14 +1526,12 @@ def test_switch_to_custom_mode_rest_flattened(): 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_switch_to_custom_mode_rest_flattened_error(): - client = NetworksClient(credentials=credentials.AnonymousCredentials(),) + client = NetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1560,7 +1547,7 @@ def test_update_peering_rest( transport: str = "rest", request_type=compute.UpdatePeeringNetworkRequest ): client = NetworksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1595,17 +1582,16 @@ def test_update_peering_rest( 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.update_peering(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" @@ -1639,7 +1625,7 @@ def test_update_peering_rest_from_dict(): def test_update_peering_rest_flattened(): - client = NetworksClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -1658,7 +1644,6 @@ def test_update_peering_rest_flattened(): networks_update_peering_request_resource = compute.NetworksUpdatePeeringRequest( network_peering=compute.NetworkPeering(auto_create_routes=True) ) - client.update_peering( project="project_value", network="network_value", @@ -1670,11 +1655,8 @@ def test_update_peering_rest_flattened(): 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) - assert compute.NetworksUpdatePeeringRequest.to_json( networks_update_peering_request_resource, including_default_value_fields=False, @@ -1683,7 +1665,7 @@ def test_update_peering_rest_flattened(): def test_update_peering_rest_flattened_error(): - client = NetworksClient(credentials=credentials.AnonymousCredentials(),) + client = NetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1701,16 +1683,16 @@ def test_update_peering_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.NetworksRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = NetworksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.NetworksRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = NetworksClient( @@ -1720,7 +1702,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.NetworksRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = NetworksClient( @@ -1731,7 +1713,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.NetworksRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = NetworksClient(transport=transport) assert client.transport is transport @@ -1740,17 +1722,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.NetworksRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_networks_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.NetworksTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1762,7 +1744,7 @@ def test_networks_base_transport(): ) as Transport: Transport.return_value = None transport = transports.NetworksTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1784,15 +1766,40 @@ def test_networks_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_networks_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.networks.transports.NetworksTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.NetworksTransport( + 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_networks_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.networks.transports.NetworksTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.NetworksTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1808,19 +1815,36 @@ def test_networks_base_transport_with_credentials_file(): def test_networks_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.networks.transports.NetworksTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.NetworksTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_networks_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + NetworksClient() + 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_networks_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) NetworksClient() adc.assert_called_once_with( scopes=( @@ -1832,7 +1856,7 @@ def test_networks_auth_adc(): def test_networks_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1844,7 +1868,7 @@ def test_networks_http_transport_client_cert_source_for_mtls(): def test_networks_host_no_port(): client = NetworksClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1854,7 +1878,7 @@ def test_networks_host_no_port(): def test_networks_host_with_port(): client = NetworksClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1864,7 +1888,6 @@ def test_networks_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1885,7 +1908,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = NetworksClient.common_folder_path(folder) assert expected == actual @@ -1904,7 +1926,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = NetworksClient.common_organization_path(organization) assert expected == actual @@ -1923,7 +1944,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = NetworksClient.common_project_path(project) assert expected == actual @@ -1943,7 +1963,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1970,7 +1989,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.NetworksTransport, "_prep_wrapped_messages" ) as prep: client = NetworksClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1979,6 +1998,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = NetworksClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_node_groups.py b/tests/unit/gapic/compute_v1/test_node_groups.py index e94ca8628..c204aea49 100644 --- a/tests/unit/gapic/compute_v1/test_node_groups.py +++ b/tests/unit/gapic/compute_v1/test_node_groups.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -84,7 +113,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [NodeGroupsClient,]) def test_node_groups_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -99,7 +128,7 @@ def test_node_groups_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [NodeGroupsClient,]) def test_node_groups_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -138,7 +167,7 @@ def test_node_groups_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(NodeGroupsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -374,7 +403,7 @@ def test_add_nodes_rest( transport: str = "rest", request_type=compute.AddNodesNodeGroupRequest ): client = NodeGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -409,17 +438,16 @@ def test_add_nodes_rest( 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_nodes(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" @@ -453,7 +481,7 @@ def test_add_nodes_rest_from_dict(): def test_add_nodes_rest_flattened(): - client = NodeGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = NodeGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -472,7 +500,6 @@ def test_add_nodes_rest_flattened(): node_groups_add_nodes_request_resource = compute.NodeGroupsAddNodesRequest( additional_node_count=2214 ) - client.add_nodes( project="project_value", zone="zone_value", @@ -485,13 +512,9 @@ def test_add_nodes_rest_flattened(): 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 "node_group_value" in http_call[1] + str(body) - assert compute.NodeGroupsAddNodesRequest.to_json( node_groups_add_nodes_request_resource, including_default_value_fields=False, @@ -500,7 +523,7 @@ def test_add_nodes_rest_flattened(): def test_add_nodes_rest_flattened_error(): - client = NodeGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = NodeGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -520,7 +543,7 @@ def test_aggregated_list_rest( transport: str = "rest", request_type=compute.AggregatedListNodeGroupsRequest ): client = NodeGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -549,17 +572,16 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.NodeGroupAggregatedList.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 == { @@ -583,7 +605,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = NodeGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = NodeGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -606,12 +628,11 @@ def test_aggregated_list_rest_flattened(): 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 = NodeGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = NodeGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -622,12 +643,11 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = NodeGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = NodeGroupsClient(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.NodeGroupAggregatedList( items={ @@ -648,7 +668,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -670,7 +689,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -688,7 +706,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteNodeGroupRequest ): client = NodeGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -723,17 +741,16 @@ def test_delete_rest( 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" @@ -767,7 +784,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = NodeGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = NodeGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -792,16 +809,13 @@ def test_delete_rest_flattened(): 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 "node_group_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = NodeGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = NodeGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -818,7 +832,7 @@ def test_delete_nodes_rest( transport: str = "rest", request_type=compute.DeleteNodesNodeGroupRequest ): client = NodeGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -853,17 +867,16 @@ def test_delete_nodes_rest( 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_nodes(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" @@ -897,7 +910,7 @@ def test_delete_nodes_rest_from_dict(): def test_delete_nodes_rest_flattened(): - client = NodeGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = NodeGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -916,7 +929,6 @@ def test_delete_nodes_rest_flattened(): node_groups_delete_nodes_request_resource = compute.NodeGroupsDeleteNodesRequest( nodes=["nodes_value"] ) - client.delete_nodes( project="project_value", zone="zone_value", @@ -929,13 +941,9 @@ def test_delete_nodes_rest_flattened(): 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 "node_group_value" in http_call[1] + str(body) - assert compute.NodeGroupsDeleteNodesRequest.to_json( node_groups_delete_nodes_request_resource, including_default_value_fields=False, @@ -944,7 +952,7 @@ def test_delete_nodes_rest_flattened(): def test_delete_nodes_rest_flattened_error(): - client = NodeGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = NodeGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -962,7 +970,7 @@ def test_delete_nodes_rest_flattened_error(): def test_get_rest(transport: str = "rest", request_type=compute.GetNodeGroupRequest): client = NodeGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -990,17 +998,16 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetNodeGroupRequ status=compute.NodeGroup.Status.CREATING, zone="zone_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.NodeGroup.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.NodeGroup) assert response.autoscaling_policy == compute.NodeGroupAutoscalingPolicy( max_nodes=958 @@ -1027,7 +1034,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = NodeGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = NodeGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1052,16 +1059,13 @@ def test_get_rest_flattened(): 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 "node_group_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = NodeGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = NodeGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1078,7 +1082,7 @@ def test_get_iam_policy_rest( transport: str = "rest", request_type=compute.GetIamPolicyNodeGroupRequest ): client = NodeGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1104,17 +1108,16 @@ def test_get_iam_policy_rest( 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( @@ -1125,7 +1128,6 @@ def test_get_iam_policy_rest( ] 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 @@ -1136,7 +1138,7 @@ def test_get_iam_policy_rest_from_dict(): def test_get_iam_policy_rest_flattened(): - client = NodeGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = NodeGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1161,16 +1163,13 @@ def test_get_iam_policy_rest_flattened(): 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 "resource_value" in http_call[1] + str(body) def test_get_iam_policy_rest_flattened_error(): - client = NodeGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = NodeGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1187,7 +1186,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertNodeGroupRequest ): client = NodeGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1222,17 +1221,16 @@ def test_insert_rest( 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" @@ -1266,7 +1264,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = NodeGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = NodeGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1285,7 +1283,6 @@ def test_insert_rest_flattened(): node_group_resource = compute.NodeGroup( autoscaling_policy=compute.NodeGroupAutoscalingPolicy(max_nodes=958) ) - client.insert( project="project_value", zone="zone_value", @@ -1298,13 +1295,9 @@ def test_insert_rest_flattened(): 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 str(1911) in http_call[1] + str(body) - assert compute.NodeGroup.to_json( node_group_resource, including_default_value_fields=False, @@ -1313,7 +1306,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = NodeGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = NodeGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1331,7 +1324,7 @@ def test_insert_rest_flattened_error(): def test_list_rest(transport: str = "rest", request_type=compute.ListNodeGroupsRequest): client = NodeGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1353,17 +1346,16 @@ def test_list_rest(transport: str = "rest", request_type=compute.ListNodeGroupsR 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.NodeGroupList.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 == [ @@ -1382,7 +1374,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = NodeGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = NodeGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1407,14 +1399,12 @@ def test_list_rest_flattened(): 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) def test_list_rest_flattened_error(): - client = NodeGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = NodeGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1425,12 +1415,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = NodeGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = NodeGroupsClient(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.NodeGroupList( items=[compute.NodeGroup(), compute.NodeGroup(), compute.NodeGroup(),], @@ -1440,7 +1429,6 @@ def test_list_pager(): compute.NodeGroupList(items=[compute.NodeGroup(),], next_page_token="ghi",), compute.NodeGroupList(items=[compute.NodeGroup(), compute.NodeGroup(),],), ) - # Two responses for two calls response = response + response @@ -1459,7 +1447,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.NodeGroup) for i in results) pages = list(client.list(request={}).pages) @@ -1471,7 +1458,7 @@ def test_list_nodes_rest( transport: str = "rest", request_type=compute.ListNodesNodeGroupsRequest ): client = NodeGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1493,17 +1480,16 @@ def test_list_nodes_rest( 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.NodeGroupsListNodes.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_nodes(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNodesPager) assert response.id == "id_value" assert response.items == [ @@ -1522,7 +1508,7 @@ def test_list_nodes_rest_from_dict(): def test_list_nodes_rest_flattened(): - client = NodeGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = NodeGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1547,16 +1533,13 @@ def test_list_nodes_rest_flattened(): 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 "node_group_value" in http_call[1] + str(body) def test_list_nodes_rest_flattened_error(): - client = NodeGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = NodeGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1570,12 +1553,11 @@ def test_list_nodes_rest_flattened_error(): def test_list_nodes_pager(): - client = NodeGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = NodeGroupsClient(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.NodeGroupsListNodes( items=[ @@ -1593,7 +1575,6 @@ def test_list_nodes_pager(): items=[compute.NodeGroupNode(), compute.NodeGroupNode(),], ), ) - # Two responses for two calls response = response + response @@ -1612,7 +1593,6 @@ def test_list_nodes_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.NodeGroupNode) for i in results) pages = list(client.list_nodes(request={}).pages) @@ -1624,7 +1604,7 @@ def test_patch_rest( transport: str = "rest", request_type=compute.PatchNodeGroupRequest ): client = NodeGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1659,17 +1639,16 @@ def test_patch_rest( 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" @@ -1703,7 +1682,7 @@ def test_patch_rest_from_dict(): def test_patch_rest_flattened(): - client = NodeGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = NodeGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1722,7 +1701,6 @@ def test_patch_rest_flattened(): node_group_resource = compute.NodeGroup( autoscaling_policy=compute.NodeGroupAutoscalingPolicy(max_nodes=958) ) - client.patch( project="project_value", zone="zone_value", @@ -1735,13 +1713,9 @@ def test_patch_rest_flattened(): 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 "node_group_value" in http_call[1] + str(body) - assert compute.NodeGroup.to_json( node_group_resource, including_default_value_fields=False, @@ -1750,7 +1724,7 @@ def test_patch_rest_flattened(): def test_patch_rest_flattened_error(): - client = NodeGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = NodeGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1770,7 +1744,7 @@ def test_set_iam_policy_rest( transport: str = "rest", request_type=compute.SetIamPolicyNodeGroupRequest ): client = NodeGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1796,17 +1770,16 @@ def test_set_iam_policy_rest( 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( @@ -1817,7 +1790,6 @@ def test_set_iam_policy_rest( ] 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 @@ -1828,7 +1800,7 @@ def test_set_iam_policy_rest_from_dict(): def test_set_iam_policy_rest_flattened(): - client = NodeGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = NodeGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1847,7 +1819,6 @@ def test_set_iam_policy_rest_flattened(): zone_set_policy_request_resource = compute.ZoneSetPolicyRequest( bindings=[compute.Binding(binding_id="binding_id_value")] ) - client.set_iam_policy( project="project_value", zone="zone_value", @@ -1860,13 +1831,9 @@ def test_set_iam_policy_rest_flattened(): 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 "resource_value" in http_call[1] + str(body) - assert compute.ZoneSetPolicyRequest.to_json( zone_set_policy_request_resource, including_default_value_fields=False, @@ -1875,7 +1842,7 @@ def test_set_iam_policy_rest_flattened(): def test_set_iam_policy_rest_flattened_error(): - client = NodeGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = NodeGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1895,7 +1862,7 @@ def test_set_node_template_rest( transport: str = "rest", request_type=compute.SetNodeTemplateNodeGroupRequest ): client = NodeGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1930,17 +1897,16 @@ def test_set_node_template_rest( 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_node_template(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" @@ -1974,7 +1940,7 @@ def test_set_node_template_rest_from_dict(): def test_set_node_template_rest_flattened(): - client = NodeGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = NodeGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1993,7 +1959,6 @@ def test_set_node_template_rest_flattened(): node_groups_set_node_template_request_resource = compute.NodeGroupsSetNodeTemplateRequest( node_template="node_template_value" ) - client.set_node_template( project="project_value", zone="zone_value", @@ -2006,13 +1971,9 @@ def test_set_node_template_rest_flattened(): 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 "node_group_value" in http_call[1] + str(body) - assert compute.NodeGroupsSetNodeTemplateRequest.to_json( node_groups_set_node_template_request_resource, including_default_value_fields=False, @@ -2021,7 +1982,7 @@ def test_set_node_template_rest_flattened(): def test_set_node_template_rest_flattened_error(): - client = NodeGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = NodeGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2041,7 +2002,7 @@ def test_test_iam_permissions_rest( transport: str = "rest", request_type=compute.TestIamPermissionsNodeGroupRequest ): client = NodeGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2054,17 +2015,16 @@ def test_test_iam_permissions_rest( 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"] @@ -2074,7 +2034,7 @@ def test_test_iam_permissions_rest_from_dict(): def test_test_iam_permissions_rest_flattened(): - client = NodeGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = NodeGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -2093,7 +2053,6 @@ def test_test_iam_permissions_rest_flattened(): test_permissions_request_resource = compute.TestPermissionsRequest( permissions=["permissions_value"] ) - client.test_iam_permissions( project="project_value", zone="zone_value", @@ -2106,13 +2065,9 @@ def test_test_iam_permissions_rest_flattened(): 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 "resource_value" in http_call[1] + str(body) - assert compute.TestPermissionsRequest.to_json( test_permissions_request_resource, including_default_value_fields=False, @@ -2121,7 +2076,7 @@ def test_test_iam_permissions_rest_flattened(): def test_test_iam_permissions_rest_flattened_error(): - client = NodeGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = NodeGroupsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2140,16 +2095,16 @@ def test_test_iam_permissions_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.NodeGroupsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = NodeGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.NodeGroupsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = NodeGroupsClient( @@ -2159,7 +2114,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.NodeGroupsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = NodeGroupsClient( @@ -2170,7 +2125,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.NodeGroupsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = NodeGroupsClient(transport=transport) assert client.transport is transport @@ -2179,17 +2134,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.NodeGroupsRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_node_groups_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.NodeGroupsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2201,7 +2156,7 @@ def test_node_groups_base_transport(): ) as Transport: Transport.return_value = None transport = transports.NodeGroupsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2226,15 +2181,40 @@ def test_node_groups_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_node_groups_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.node_groups.transports.NodeGroupsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.NodeGroupsTransport( + 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_node_groups_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.node_groups.transports.NodeGroupsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.NodeGroupsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2250,19 +2230,36 @@ def test_node_groups_base_transport_with_credentials_file(): def test_node_groups_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.node_groups.transports.NodeGroupsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.NodeGroupsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_node_groups_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + NodeGroupsClient() + 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_node_groups_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) NodeGroupsClient() adc.assert_called_once_with( scopes=( @@ -2274,7 +2271,7 @@ def test_node_groups_auth_adc(): def test_node_groups_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -2286,7 +2283,7 @@ def test_node_groups_http_transport_client_cert_source_for_mtls(): def test_node_groups_host_no_port(): client = NodeGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -2296,7 +2293,7 @@ def test_node_groups_host_no_port(): def test_node_groups_host_with_port(): client = NodeGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -2306,7 +2303,6 @@ def test_node_groups_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2327,7 +2323,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = NodeGroupsClient.common_folder_path(folder) assert expected == actual @@ -2346,7 +2341,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = NodeGroupsClient.common_organization_path(organization) assert expected == actual @@ -2365,7 +2359,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = NodeGroupsClient.common_project_path(project) assert expected == actual @@ -2385,7 +2378,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2412,7 +2404,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.NodeGroupsTransport, "_prep_wrapped_messages" ) as prep: client = NodeGroupsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2421,6 +2413,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = NodeGroupsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_node_templates.py b/tests/unit/gapic/compute_v1/test_node_templates.py index 35348b22f..67768c82f 100644 --- a/tests/unit/gapic/compute_v1/test_node_templates.py +++ b/tests/unit/gapic/compute_v1/test_node_templates.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -87,7 +116,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [NodeTemplatesClient,]) def test_node_templates_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -102,7 +131,7 @@ def test_node_templates_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [NodeTemplatesClient,]) def test_node_templates_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -143,7 +172,7 @@ def test_node_templates_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(NodeTemplatesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -381,7 +410,7 @@ def test_aggregated_list_rest( transport: str = "rest", request_type=compute.AggregatedListNodeTemplatesRequest ): client = NodeTemplatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -410,17 +439,16 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.NodeTemplateAggregatedList.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 == { @@ -444,7 +472,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = NodeTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = NodeTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -467,12 +495,11 @@ def test_aggregated_list_rest_flattened(): 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 = NodeTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = NodeTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -483,12 +510,11 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = NodeTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = NodeTemplatesClient(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.NodeTemplateAggregatedList( items={ @@ -509,7 +535,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -533,7 +558,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -554,7 +578,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteNodeTemplateRequest ): client = NodeTemplatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -589,17 +613,16 @@ def test_delete_rest( 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" @@ -633,7 +656,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = NodeTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = NodeTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -660,16 +683,13 @@ def test_delete_rest_flattened(): 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 "node_template_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = NodeTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = NodeTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -684,7 +704,7 @@ def test_delete_rest_flattened_error(): def test_get_rest(transport: str = "rest", request_type=compute.GetNodeTemplateRequest): client = NodeTemplatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -716,17 +736,16 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetNodeTemplateR status=compute.NodeTemplate.Status.CREATING, status_message="status_message_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.NodeTemplate.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.NodeTemplate) assert response.accelerators == [compute.AcceleratorConfig(accelerator_count=1805)] assert ( @@ -758,7 +777,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = NodeTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = NodeTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -785,16 +804,13 @@ def test_get_rest_flattened(): 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 "node_template_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = NodeTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = NodeTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -811,7 +827,7 @@ def test_get_iam_policy_rest( transport: str = "rest", request_type=compute.GetIamPolicyNodeTemplateRequest ): client = NodeTemplatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -837,17 +853,16 @@ def test_get_iam_policy_rest( 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( @@ -858,7 +873,6 @@ def test_get_iam_policy_rest( ] 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 @@ -869,7 +883,7 @@ def test_get_iam_policy_rest_from_dict(): def test_get_iam_policy_rest_flattened(): - client = NodeTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = NodeTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -894,16 +908,13 @@ def test_get_iam_policy_rest_flattened(): 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) def test_get_iam_policy_rest_flattened_error(): - client = NodeTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = NodeTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -920,7 +931,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertNodeTemplateRequest ): client = NodeTemplatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -955,17 +966,16 @@ def test_insert_rest( 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" @@ -999,7 +1009,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = NodeTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = NodeTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1018,7 +1028,6 @@ def test_insert_rest_flattened(): node_template_resource = compute.NodeTemplate( accelerators=[compute.AcceleratorConfig(accelerator_count=1805)] ) - client.insert( project="project_value", region="region_value", @@ -1030,11 +1039,8 @@ def test_insert_rest_flattened(): 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.NodeTemplate.to_json( node_template_resource, including_default_value_fields=False, @@ -1043,7 +1049,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = NodeTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = NodeTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1062,7 +1068,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListNodeTemplatesRequest ): client = NodeTemplatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1084,17 +1090,16 @@ def test_list_rest( 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.NodeTemplateList.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 == [ @@ -1113,7 +1118,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = NodeTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = NodeTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1138,14 +1143,12 @@ def test_list_rest_flattened(): 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 = NodeTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = NodeTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1158,12 +1161,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = NodeTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = NodeTemplatesClient(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.NodeTemplateList( items=[ @@ -1181,7 +1183,6 @@ def test_list_pager(): items=[compute.NodeTemplate(), compute.NodeTemplate(),], ), ) - # Two responses for two calls response = response + response @@ -1200,7 +1201,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.NodeTemplate) for i in results) pages = list(client.list(request={}).pages) @@ -1212,7 +1212,7 @@ def test_set_iam_policy_rest( transport: str = "rest", request_type=compute.SetIamPolicyNodeTemplateRequest ): client = NodeTemplatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1238,17 +1238,16 @@ def test_set_iam_policy_rest( 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( @@ -1259,7 +1258,6 @@ def test_set_iam_policy_rest( ] 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 @@ -1270,7 +1268,7 @@ def test_set_iam_policy_rest_from_dict(): def test_set_iam_policy_rest_flattened(): - client = NodeTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = NodeTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1289,7 +1287,6 @@ def test_set_iam_policy_rest_flattened(): region_set_policy_request_resource = compute.RegionSetPolicyRequest( bindings=[compute.Binding(binding_id="binding_id_value")] ) - client.set_iam_policy( project="project_value", region="region_value", @@ -1302,13 +1299,9 @@ def test_set_iam_policy_rest_flattened(): 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.RegionSetPolicyRequest.to_json( region_set_policy_request_resource, including_default_value_fields=False, @@ -1317,7 +1310,7 @@ def test_set_iam_policy_rest_flattened(): def test_set_iam_policy_rest_flattened_error(): - client = NodeTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = NodeTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1337,7 +1330,7 @@ def test_test_iam_permissions_rest( transport: str = "rest", request_type=compute.TestIamPermissionsNodeTemplateRequest ): client = NodeTemplatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1350,17 +1343,16 @@ def test_test_iam_permissions_rest( 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"] @@ -1370,7 +1362,7 @@ def test_test_iam_permissions_rest_from_dict(): def test_test_iam_permissions_rest_flattened(): - client = NodeTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = NodeTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1389,7 +1381,6 @@ def test_test_iam_permissions_rest_flattened(): test_permissions_request_resource = compute.TestPermissionsRequest( permissions=["permissions_value"] ) - client.test_iam_permissions( project="project_value", region="region_value", @@ -1402,13 +1393,9 @@ def test_test_iam_permissions_rest_flattened(): 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.TestPermissionsRequest.to_json( test_permissions_request_resource, including_default_value_fields=False, @@ -1417,7 +1404,7 @@ def test_test_iam_permissions_rest_flattened(): def test_test_iam_permissions_rest_flattened_error(): - client = NodeTemplatesClient(credentials=credentials.AnonymousCredentials(),) + client = NodeTemplatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1436,16 +1423,16 @@ def test_test_iam_permissions_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.NodeTemplatesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = NodeTemplatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.NodeTemplatesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = NodeTemplatesClient( @@ -1455,7 +1442,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.NodeTemplatesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = NodeTemplatesClient( @@ -1466,7 +1453,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.NodeTemplatesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = NodeTemplatesClient(transport=transport) assert client.transport is transport @@ -1475,17 +1462,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.NodeTemplatesRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_node_templates_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.NodeTemplatesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1497,7 +1484,7 @@ def test_node_templates_base_transport(): ) as Transport: Transport.return_value = None transport = transports.NodeTemplatesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1517,15 +1504,40 @@ def test_node_templates_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_node_templates_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.node_templates.transports.NodeTemplatesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.NodeTemplatesTransport( + 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_node_templates_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.node_templates.transports.NodeTemplatesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.NodeTemplatesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1541,19 +1553,36 @@ def test_node_templates_base_transport_with_credentials_file(): def test_node_templates_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.node_templates.transports.NodeTemplatesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.NodeTemplatesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_node_templates_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + NodeTemplatesClient() + 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_node_templates_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) NodeTemplatesClient() adc.assert_called_once_with( scopes=( @@ -1565,7 +1594,7 @@ def test_node_templates_auth_adc(): def test_node_templates_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1577,7 +1606,7 @@ def test_node_templates_http_transport_client_cert_source_for_mtls(): def test_node_templates_host_no_port(): client = NodeTemplatesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1587,7 +1616,7 @@ def test_node_templates_host_no_port(): def test_node_templates_host_with_port(): client = NodeTemplatesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1597,7 +1626,6 @@ def test_node_templates_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1618,7 +1646,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = NodeTemplatesClient.common_folder_path(folder) assert expected == actual @@ -1637,7 +1664,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = NodeTemplatesClient.common_organization_path(organization) assert expected == actual @@ -1656,7 +1682,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = NodeTemplatesClient.common_project_path(project) assert expected == actual @@ -1676,7 +1701,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1703,7 +1727,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.NodeTemplatesTransport, "_prep_wrapped_messages" ) as prep: client = NodeTemplatesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1712,6 +1736,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = NodeTemplatesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_node_types.py b/tests/unit/gapic/compute_v1/test_node_types.py index 8d09b10bf..827058728 100644 --- a/tests/unit/gapic/compute_v1/test_node_types.py +++ b/tests/unit/gapic/compute_v1/test_node_types.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -82,7 +111,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [NodeTypesClient,]) def test_node_types_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -97,7 +126,7 @@ def test_node_types_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [NodeTypesClient,]) def test_node_types_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -136,7 +165,7 @@ def test_node_types_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(NodeTypesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -372,7 +401,7 @@ def test_aggregated_list_rest( transport: str = "rest", request_type=compute.AggregatedListNodeTypesRequest ): client = NodeTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -395,17 +424,16 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.NodeTypeAggregatedList.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 == { @@ -425,7 +453,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = NodeTypesClient(credentials=credentials.AnonymousCredentials(),) + client = NodeTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -448,12 +476,11 @@ def test_aggregated_list_rest_flattened(): 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 = NodeTypesClient(credentials=credentials.AnonymousCredentials(),) + client = NodeTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -464,12 +491,11 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = NodeTypesClient(credentials=credentials.AnonymousCredentials(),) + client = NodeTypesClient(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.NodeTypeAggregatedList( items={ @@ -490,7 +516,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -512,7 +537,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -528,7 +552,7 @@ def test_aggregated_list_pager(): def test_get_rest(transport: str = "rest", request_type=compute.GetNodeTypeRequest): client = NodeTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -552,17 +576,16 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetNodeTypeReque self_link="self_link_value", zone="zone_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.NodeType.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.NodeType) assert response.cpu_platform == "cpu_platform_value" assert response.creation_timestamp == "creation_timestamp_value" @@ -583,7 +606,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = NodeTypesClient(credentials=credentials.AnonymousCredentials(),) + client = NodeTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -608,16 +631,13 @@ def test_get_rest_flattened(): 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 "node_type_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = NodeTypesClient(credentials=credentials.AnonymousCredentials(),) + client = NodeTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -632,7 +652,7 @@ def test_get_rest_flattened_error(): def test_list_rest(transport: str = "rest", request_type=compute.ListNodeTypesRequest): client = NodeTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -650,17 +670,16 @@ def test_list_rest(transport: str = "rest", request_type=compute.ListNodeTypesRe 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.NodeTypeList.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.NodeType(cpu_platform="cpu_platform_value")] @@ -675,7 +694,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = NodeTypesClient(credentials=credentials.AnonymousCredentials(),) + client = NodeTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -700,14 +719,12 @@ def test_list_rest_flattened(): 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) def test_list_rest_flattened_error(): - client = NodeTypesClient(credentials=credentials.AnonymousCredentials(),) + client = NodeTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -718,12 +735,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = NodeTypesClient(credentials=credentials.AnonymousCredentials(),) + client = NodeTypesClient(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.NodeTypeList( items=[compute.NodeType(), compute.NodeType(), compute.NodeType(),], @@ -733,7 +749,6 @@ def test_list_pager(): compute.NodeTypeList(items=[compute.NodeType(),], next_page_token="ghi",), compute.NodeTypeList(items=[compute.NodeType(), compute.NodeType(),],), ) - # Two responses for two calls response = response + response @@ -752,7 +767,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.NodeType) for i in results) pages = list(client.list(request={}).pages) @@ -763,16 +777,16 @@ def test_list_pager(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.NodeTypesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = NodeTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.NodeTypesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = NodeTypesClient( @@ -782,7 +796,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.NodeTypesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = NodeTypesClient( @@ -793,7 +807,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.NodeTypesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = NodeTypesClient(transport=transport) assert client.transport is transport @@ -802,17 +816,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.NodeTypesRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_node_types_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.NodeTypesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -824,7 +838,7 @@ def test_node_types_base_transport(): ) as Transport: Transport.return_value = None transport = transports.NodeTypesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -839,15 +853,41 @@ def test_node_types_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_node_types_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.node_types.transports.NodeTypesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.NodeTypesTransport( + 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.readonly", + "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_node_types_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.node_types.transports.NodeTypesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.NodeTypesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -864,19 +904,37 @@ def test_node_types_base_transport_with_credentials_file(): def test_node_types_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.node_types.transports.NodeTypesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.NodeTypesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_node_types_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + NodeTypesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/compute.readonly", + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_node_types_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) NodeTypesClient() adc.assert_called_once_with( scopes=( @@ -889,7 +947,7 @@ def test_node_types_auth_adc(): def test_node_types_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -901,7 +959,7 @@ def test_node_types_http_transport_client_cert_source_for_mtls(): def test_node_types_host_no_port(): client = NodeTypesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -911,7 +969,7 @@ def test_node_types_host_no_port(): def test_node_types_host_with_port(): client = NodeTypesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -921,7 +979,6 @@ def test_node_types_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -942,7 +999,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = NodeTypesClient.common_folder_path(folder) assert expected == actual @@ -961,7 +1017,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = NodeTypesClient.common_organization_path(organization) assert expected == actual @@ -980,7 +1035,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = NodeTypesClient.common_project_path(project) assert expected == actual @@ -1000,7 +1054,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1027,7 +1080,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.NodeTypesTransport, "_prep_wrapped_messages" ) as prep: client = NodeTypesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1036,6 +1089,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = NodeTypesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_packet_mirrorings.py b/tests/unit/gapic/compute_v1/test_packet_mirrorings.py index 6d50f381e..b9e21e117 100644 --- a/tests/unit/gapic/compute_v1/test_packet_mirrorings.py +++ b/tests/unit/gapic/compute_v1/test_packet_mirrorings.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -88,7 +117,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [PacketMirroringsClient,]) def test_packet_mirrorings_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -103,7 +132,7 @@ def test_packet_mirrorings_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [PacketMirroringsClient,]) def test_packet_mirrorings_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -144,7 +173,7 @@ def test_packet_mirrorings_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(PacketMirroringsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -392,7 +421,7 @@ def test_aggregated_list_rest( transport: str = "rest", request_type=compute.AggregatedListPacketMirroringsRequest ): client = PacketMirroringsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -421,17 +450,16 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.PacketMirroringAggregatedList.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 == { @@ -457,7 +485,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = PacketMirroringsClient(credentials=credentials.AnonymousCredentials(),) + client = PacketMirroringsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -480,12 +508,11 @@ def test_aggregated_list_rest_flattened(): 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 = PacketMirroringsClient(credentials=credentials.AnonymousCredentials(),) + client = PacketMirroringsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -496,12 +523,11 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = PacketMirroringsClient(credentials=credentials.AnonymousCredentials(),) + client = PacketMirroringsClient(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.PacketMirroringAggregatedList( items={ @@ -523,7 +549,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -547,7 +572,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -568,7 +592,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeletePacketMirroringRequest ): client = PacketMirroringsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -603,17 +627,16 @@ def test_delete_rest( 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" @@ -647,7 +670,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = PacketMirroringsClient(credentials=credentials.AnonymousCredentials(),) + client = PacketMirroringsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -674,16 +697,13 @@ def test_delete_rest_flattened(): 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 "packet_mirroring_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = PacketMirroringsClient(credentials=credentials.AnonymousCredentials(),) + client = PacketMirroringsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -700,7 +720,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetPacketMirroringRequest ): client = PacketMirroringsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -735,17 +755,16 @@ def test_get_rest( region="region_value", self_link="self_link_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.PacketMirroring.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.PacketMirroring) assert response.collector_ilb == compute.PacketMirroringForwardingRuleInfo( canonical_url="canonical_url_value" @@ -779,7 +798,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = PacketMirroringsClient(credentials=credentials.AnonymousCredentials(),) + client = PacketMirroringsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -806,16 +825,13 @@ def test_get_rest_flattened(): 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 "packet_mirroring_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = PacketMirroringsClient(credentials=credentials.AnonymousCredentials(),) + client = PacketMirroringsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -832,7 +848,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertPacketMirroringRequest ): client = PacketMirroringsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -867,17 +883,16 @@ def test_insert_rest( 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" @@ -911,7 +926,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = PacketMirroringsClient(credentials=credentials.AnonymousCredentials(),) + client = PacketMirroringsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -932,7 +947,6 @@ def test_insert_rest_flattened(): canonical_url="canonical_url_value" ) ) - client.insert( project="project_value", region="region_value", @@ -944,11 +958,8 @@ def test_insert_rest_flattened(): 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.PacketMirroring.to_json( packet_mirroring_resource, including_default_value_fields=False, @@ -957,7 +968,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = PacketMirroringsClient(credentials=credentials.AnonymousCredentials(),) + client = PacketMirroringsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -978,7 +989,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListPacketMirroringsRequest ): client = PacketMirroringsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1002,17 +1013,16 @@ def test_list_rest( 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.PacketMirroringList.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 == [ @@ -1033,7 +1043,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = PacketMirroringsClient(credentials=credentials.AnonymousCredentials(),) + client = PacketMirroringsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1058,14 +1068,12 @@ def test_list_rest_flattened(): 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 = PacketMirroringsClient(credentials=credentials.AnonymousCredentials(),) + client = PacketMirroringsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1078,12 +1086,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = PacketMirroringsClient(credentials=credentials.AnonymousCredentials(),) + client = PacketMirroringsClient(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.PacketMirroringList( items=[ @@ -1101,7 +1108,6 @@ def test_list_pager(): items=[compute.PacketMirroring(), compute.PacketMirroring(),], ), ) - # Two responses for two calls response = response + response @@ -1120,7 +1126,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.PacketMirroring) for i in results) pages = list(client.list(request={}).pages) @@ -1132,7 +1137,7 @@ def test_patch_rest( transport: str = "rest", request_type=compute.PatchPacketMirroringRequest ): client = PacketMirroringsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1167,17 +1172,16 @@ def test_patch_rest( 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" @@ -1211,7 +1215,7 @@ def test_patch_rest_from_dict(): def test_patch_rest_flattened(): - client = PacketMirroringsClient(credentials=credentials.AnonymousCredentials(),) + client = PacketMirroringsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1232,7 +1236,6 @@ def test_patch_rest_flattened(): canonical_url="canonical_url_value" ) ) - client.patch( project="project_value", region="region_value", @@ -1245,13 +1248,9 @@ def test_patch_rest_flattened(): 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 "packet_mirroring_value" in http_call[1] + str(body) - assert compute.PacketMirroring.to_json( packet_mirroring_resource, including_default_value_fields=False, @@ -1260,7 +1259,7 @@ def test_patch_rest_flattened(): def test_patch_rest_flattened_error(): - client = PacketMirroringsClient(credentials=credentials.AnonymousCredentials(),) + client = PacketMirroringsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1283,7 +1282,7 @@ def test_test_iam_permissions_rest( request_type=compute.TestIamPermissionsPacketMirroringRequest, ): client = PacketMirroringsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1296,17 +1295,16 @@ def test_test_iam_permissions_rest( 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"] @@ -1316,7 +1314,7 @@ def test_test_iam_permissions_rest_from_dict(): def test_test_iam_permissions_rest_flattened(): - client = PacketMirroringsClient(credentials=credentials.AnonymousCredentials(),) + client = PacketMirroringsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1335,7 +1333,6 @@ def test_test_iam_permissions_rest_flattened(): test_permissions_request_resource = compute.TestPermissionsRequest( permissions=["permissions_value"] ) - client.test_iam_permissions( project="project_value", region="region_value", @@ -1348,13 +1345,9 @@ def test_test_iam_permissions_rest_flattened(): 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.TestPermissionsRequest.to_json( test_permissions_request_resource, including_default_value_fields=False, @@ -1363,7 +1356,7 @@ def test_test_iam_permissions_rest_flattened(): def test_test_iam_permissions_rest_flattened_error(): - client = PacketMirroringsClient(credentials=credentials.AnonymousCredentials(),) + client = PacketMirroringsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1382,16 +1375,16 @@ def test_test_iam_permissions_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.PacketMirroringsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = PacketMirroringsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.PacketMirroringsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = PacketMirroringsClient( @@ -1401,7 +1394,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.PacketMirroringsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = PacketMirroringsClient( @@ -1412,7 +1405,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.PacketMirroringsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = PacketMirroringsClient(transport=transport) assert client.transport is transport @@ -1421,17 +1414,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.PacketMirroringsRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_packet_mirrorings_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.PacketMirroringsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1443,7 +1436,7 @@ def test_packet_mirrorings_base_transport(): ) as Transport: Transport.return_value = None transport = transports.PacketMirroringsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1462,15 +1455,40 @@ def test_packet_mirrorings_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_packet_mirrorings_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.packet_mirrorings.transports.PacketMirroringsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PacketMirroringsTransport( + 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_packet_mirrorings_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.packet_mirrorings.transports.PacketMirroringsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.PacketMirroringsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1486,19 +1504,36 @@ def test_packet_mirrorings_base_transport_with_credentials_file(): def test_packet_mirrorings_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.packet_mirrorings.transports.PacketMirroringsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.PacketMirroringsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_packet_mirrorings_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + PacketMirroringsClient() + 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_packet_mirrorings_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) PacketMirroringsClient() adc.assert_called_once_with( scopes=( @@ -1510,7 +1545,7 @@ def test_packet_mirrorings_auth_adc(): def test_packet_mirrorings_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1522,7 +1557,7 @@ def test_packet_mirrorings_http_transport_client_cert_source_for_mtls(): def test_packet_mirrorings_host_no_port(): client = PacketMirroringsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1532,7 +1567,7 @@ def test_packet_mirrorings_host_no_port(): def test_packet_mirrorings_host_with_port(): client = PacketMirroringsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1542,7 +1577,6 @@ def test_packet_mirrorings_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1563,7 +1597,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = PacketMirroringsClient.common_folder_path(folder) assert expected == actual @@ -1582,7 +1615,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = PacketMirroringsClient.common_organization_path(organization) assert expected == actual @@ -1601,7 +1633,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = PacketMirroringsClient.common_project_path(project) assert expected == actual @@ -1621,7 +1652,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1648,7 +1678,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.PacketMirroringsTransport, "_prep_wrapped_messages" ) as prep: client = PacketMirroringsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1657,6 +1687,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = PacketMirroringsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_projects.py b/tests/unit/gapic/compute_v1/test_projects.py index 946e8d694..bff8cfd61 100644 --- a/tests/unit/gapic/compute_v1/test_projects.py +++ b/tests/unit/gapic/compute_v1/test_projects.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,59 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -82,7 +109,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [ProjectsClient,]) def test_projects_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -97,7 +124,7 @@ def test_projects_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [ProjectsClient,]) def test_projects_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -134,7 +161,7 @@ def test_projects_client_get_transport_class(): def test_projects_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(ProjectsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -370,7 +397,7 @@ def test_disable_xpn_host_rest( transport: str = "rest", request_type=compute.DisableXpnHostProjectRequest ): client = ProjectsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -405,17 +432,16 @@ def test_disable_xpn_host_rest( 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.disable_xpn_host(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" @@ -449,7 +475,7 @@ def test_disable_xpn_host_rest_from_dict(): def test_disable_xpn_host_rest_flattened(): - client = ProjectsClient(credentials=credentials.AnonymousCredentials(),) + client = ProjectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -472,12 +498,11 @@ def test_disable_xpn_host_rest_flattened(): 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_disable_xpn_host_rest_flattened_error(): - client = ProjectsClient(credentials=credentials.AnonymousCredentials(),) + client = ProjectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -491,7 +516,7 @@ def test_disable_xpn_resource_rest( transport: str = "rest", request_type=compute.DisableXpnResourceProjectRequest ): client = ProjectsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -526,17 +551,16 @@ def test_disable_xpn_resource_rest( 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.disable_xpn_resource(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" @@ -570,7 +594,7 @@ def test_disable_xpn_resource_rest_from_dict(): def test_disable_xpn_resource_rest_flattened(): - client = ProjectsClient(credentials=credentials.AnonymousCredentials(),) + client = ProjectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -589,7 +613,6 @@ def test_disable_xpn_resource_rest_flattened(): projects_disable_xpn_resource_request_resource = compute.ProjectsDisableXpnResourceRequest( xpn_resource=compute.XpnResourceId(id="id_value") ) - client.disable_xpn_resource( project="project_value", projects_disable_xpn_resource_request_resource=projects_disable_xpn_resource_request_resource, @@ -600,9 +623,7 @@ def test_disable_xpn_resource_rest_flattened(): 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.ProjectsDisableXpnResourceRequest.to_json( projects_disable_xpn_resource_request_resource, including_default_value_fields=False, @@ -611,7 +632,7 @@ def test_disable_xpn_resource_rest_flattened(): def test_disable_xpn_resource_rest_flattened_error(): - client = ProjectsClient(credentials=credentials.AnonymousCredentials(),) + client = ProjectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -629,7 +650,7 @@ def test_enable_xpn_host_rest( transport: str = "rest", request_type=compute.EnableXpnHostProjectRequest ): client = ProjectsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -664,17 +685,16 @@ def test_enable_xpn_host_rest( 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.enable_xpn_host(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" @@ -708,7 +728,7 @@ def test_enable_xpn_host_rest_from_dict(): def test_enable_xpn_host_rest_flattened(): - client = ProjectsClient(credentials=credentials.AnonymousCredentials(),) + client = ProjectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -731,12 +751,11 @@ def test_enable_xpn_host_rest_flattened(): 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_enable_xpn_host_rest_flattened_error(): - client = ProjectsClient(credentials=credentials.AnonymousCredentials(),) + client = ProjectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -750,7 +769,7 @@ def test_enable_xpn_resource_rest( transport: str = "rest", request_type=compute.EnableXpnResourceProjectRequest ): client = ProjectsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -785,17 +804,16 @@ def test_enable_xpn_resource_rest( 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.enable_xpn_resource(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" @@ -829,7 +847,7 @@ def test_enable_xpn_resource_rest_from_dict(): def test_enable_xpn_resource_rest_flattened(): - client = ProjectsClient(credentials=credentials.AnonymousCredentials(),) + client = ProjectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -848,7 +866,6 @@ def test_enable_xpn_resource_rest_flattened(): projects_enable_xpn_resource_request_resource = compute.ProjectsEnableXpnResourceRequest( xpn_resource=compute.XpnResourceId(id="id_value") ) - client.enable_xpn_resource( project="project_value", projects_enable_xpn_resource_request_resource=projects_enable_xpn_resource_request_resource, @@ -859,9 +876,7 @@ def test_enable_xpn_resource_rest_flattened(): 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.ProjectsEnableXpnResourceRequest.to_json( projects_enable_xpn_resource_request_resource, including_default_value_fields=False, @@ -870,7 +885,7 @@ def test_enable_xpn_resource_rest_flattened(): def test_enable_xpn_resource_rest_flattened_error(): - client = ProjectsClient(credentials=credentials.AnonymousCredentials(),) + client = ProjectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -886,7 +901,7 @@ def test_enable_xpn_resource_rest_flattened_error(): def test_get_rest(transport: str = "rest", request_type=compute.GetProjectRequest): client = ProjectsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -913,17 +928,16 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetProjectReques ), xpn_project_status=compute.Project.XpnProjectStatus.HOST, ) + # Wrap the value into a proper Response obj json_return_value = compute.Project.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.Project) assert response.common_instance_metadata == compute.Metadata( fingerprint="fingerprint_value" @@ -949,7 +963,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = ProjectsClient(credentials=credentials.AnonymousCredentials(),) + client = ProjectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -972,12 +986,11 @@ def test_get_rest_flattened(): 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_get_rest_flattened_error(): - client = ProjectsClient(credentials=credentials.AnonymousCredentials(),) + client = ProjectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -991,7 +1004,7 @@ def test_get_xpn_host_rest( transport: str = "rest", request_type=compute.GetXpnHostProjectRequest ): client = ProjectsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1018,17 +1031,16 @@ def test_get_xpn_host_rest( ), xpn_project_status=compute.Project.XpnProjectStatus.HOST, ) + # Wrap the value into a proper Response obj json_return_value = compute.Project.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_xpn_host(request) # Establish that the response is the type that we expect. - assert isinstance(response, compute.Project) assert response.common_instance_metadata == compute.Metadata( fingerprint="fingerprint_value" @@ -1054,7 +1066,7 @@ def test_get_xpn_host_rest_from_dict(): def test_get_xpn_host_rest_flattened(): - client = ProjectsClient(credentials=credentials.AnonymousCredentials(),) + client = ProjectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1077,12 +1089,11 @@ def test_get_xpn_host_rest_flattened(): 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_get_xpn_host_rest_flattened_error(): - client = ProjectsClient(credentials=credentials.AnonymousCredentials(),) + client = ProjectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1096,7 +1107,7 @@ def test_get_xpn_resources_rest( transport: str = "rest", request_type=compute.GetXpnResourcesProjectsRequest ): client = ProjectsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1111,17 +1122,16 @@ def test_get_xpn_resources_rest( next_page_token="next_page_token_value", resources=[compute.XpnResourceId(id="id_value")], ) + # Wrap the value into a proper Response obj json_return_value = compute.ProjectsGetXpnResources.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_xpn_resources(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GetXpnResourcesPager) assert response.kind == "kind_value" assert response.next_page_token == "next_page_token_value" @@ -1133,7 +1143,7 @@ def test_get_xpn_resources_rest_from_dict(): def test_get_xpn_resources_rest_flattened(): - client = ProjectsClient(credentials=credentials.AnonymousCredentials(),) + client = ProjectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1156,12 +1166,11 @@ def test_get_xpn_resources_rest_flattened(): 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_get_xpn_resources_rest_flattened_error(): - client = ProjectsClient(credentials=credentials.AnonymousCredentials(),) + client = ProjectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1172,12 +1181,11 @@ def test_get_xpn_resources_rest_flattened_error(): def test_get_xpn_resources_pager(): - client = ProjectsClient(credentials=credentials.AnonymousCredentials(),) + client = ProjectsClient(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.ProjectsGetXpnResources( resources=[ @@ -1195,7 +1203,6 @@ def test_get_xpn_resources_pager(): resources=[compute.XpnResourceId(), compute.XpnResourceId(),], ), ) - # Two responses for two calls response = response + response @@ -1214,7 +1221,6 @@ def test_get_xpn_resources_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.XpnResourceId) for i in results) pages = list(client.get_xpn_resources(request={}).pages) @@ -1226,7 +1232,7 @@ def test_list_xpn_hosts_rest( transport: str = "rest", request_type=compute.ListXpnHostsProjectsRequest ): client = ProjectsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1250,17 +1256,16 @@ def test_list_xpn_hosts_rest( 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.XpnHostList.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_xpn_hosts(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListXpnHostsPager) assert response.id == "id_value" assert response.items == [ @@ -1279,7 +1284,7 @@ def test_list_xpn_hosts_rest_from_dict(): def test_list_xpn_hosts_rest_flattened(): - client = ProjectsClient(credentials=credentials.AnonymousCredentials(),) + client = ProjectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1298,7 +1303,6 @@ def test_list_xpn_hosts_rest_flattened(): projects_list_xpn_hosts_request_resource = compute.ProjectsListXpnHostsRequest( organization="organization_value" ) - client.list_xpn_hosts( project="project_value", projects_list_xpn_hosts_request_resource=projects_list_xpn_hosts_request_resource, @@ -1309,9 +1313,7 @@ def test_list_xpn_hosts_rest_flattened(): 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.ProjectsListXpnHostsRequest.to_json( projects_list_xpn_hosts_request_resource, including_default_value_fields=False, @@ -1320,7 +1322,7 @@ def test_list_xpn_hosts_rest_flattened(): def test_list_xpn_hosts_rest_flattened_error(): - client = ProjectsClient(credentials=credentials.AnonymousCredentials(),) + client = ProjectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1335,12 +1337,11 @@ def test_list_xpn_hosts_rest_flattened_error(): def test_list_xpn_hosts_pager(): - client = ProjectsClient(credentials=credentials.AnonymousCredentials(),) + client = ProjectsClient(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.XpnHostList( items=[compute.Project(), compute.Project(), compute.Project(),], @@ -1350,7 +1351,6 @@ def test_list_xpn_hosts_pager(): compute.XpnHostList(items=[compute.Project(),], next_page_token="ghi",), compute.XpnHostList(items=[compute.Project(), compute.Project(),],), ) - # Two responses for two calls response = response + response @@ -1369,7 +1369,6 @@ def test_list_xpn_hosts_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.Project) for i in results) pages = list(client.list_xpn_hosts(request={}).pages) @@ -1381,7 +1380,7 @@ def test_move_disk_rest( transport: str = "rest", request_type=compute.MoveDiskProjectRequest ): client = ProjectsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1416,17 +1415,16 @@ def test_move_disk_rest( 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_disk(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" @@ -1460,7 +1458,7 @@ def test_move_disk_rest_from_dict(): def test_move_disk_rest_flattened(): - client = ProjectsClient(credentials=credentials.AnonymousCredentials(),) + client = ProjectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1479,7 +1477,6 @@ def test_move_disk_rest_flattened(): disk_move_request_resource = compute.DiskMoveRequest( destination_zone="destination_zone_value" ) - client.move_disk( project="project_value", disk_move_request_resource=disk_move_request_resource, @@ -1490,9 +1487,7 @@ def test_move_disk_rest_flattened(): 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.DiskMoveRequest.to_json( disk_move_request_resource, including_default_value_fields=False, @@ -1501,7 +1496,7 @@ def test_move_disk_rest_flattened(): def test_move_disk_rest_flattened_error(): - client = ProjectsClient(credentials=credentials.AnonymousCredentials(),) + client = ProjectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1519,7 +1514,7 @@ def test_move_instance_rest( transport: str = "rest", request_type=compute.MoveInstanceProjectRequest ): client = ProjectsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1554,17 +1549,16 @@ def test_move_instance_rest( 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_instance(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" @@ -1598,7 +1592,7 @@ def test_move_instance_rest_from_dict(): def test_move_instance_rest_flattened(): - client = ProjectsClient(credentials=credentials.AnonymousCredentials(),) + client = ProjectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1617,7 +1611,6 @@ def test_move_instance_rest_flattened(): instance_move_request_resource = compute.InstanceMoveRequest( destination_zone="destination_zone_value" ) - client.move_instance( project="project_value", instance_move_request_resource=instance_move_request_resource, @@ -1628,9 +1621,7 @@ def test_move_instance_rest_flattened(): 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.InstanceMoveRequest.to_json( instance_move_request_resource, including_default_value_fields=False, @@ -1639,7 +1630,7 @@ def test_move_instance_rest_flattened(): def test_move_instance_rest_flattened_error(): - client = ProjectsClient(credentials=credentials.AnonymousCredentials(),) + client = ProjectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1658,7 +1649,7 @@ def test_set_common_instance_metadata_rest( request_type=compute.SetCommonInstanceMetadataProjectRequest, ): client = ProjectsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1693,17 +1684,16 @@ def test_set_common_instance_metadata_rest( 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_common_instance_metadata(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" @@ -1737,7 +1727,7 @@ def test_set_common_instance_metadata_rest_from_dict(): def test_set_common_instance_metadata_rest_flattened(): - client = ProjectsClient(credentials=credentials.AnonymousCredentials(),) + client = ProjectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1754,7 +1744,6 @@ def test_set_common_instance_metadata_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. metadata_resource = compute.Metadata(fingerprint="fingerprint_value") - client.set_common_instance_metadata( project="project_value", metadata_resource=metadata_resource, ) @@ -1764,9 +1753,7 @@ def test_set_common_instance_metadata_rest_flattened(): 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.Metadata.to_json( metadata_resource, including_default_value_fields=False, @@ -1775,7 +1762,7 @@ def test_set_common_instance_metadata_rest_flattened(): def test_set_common_instance_metadata_rest_flattened_error(): - client = ProjectsClient(credentials=credentials.AnonymousCredentials(),) + client = ProjectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1791,7 +1778,7 @@ def test_set_default_network_tier_rest( transport: str = "rest", request_type=compute.SetDefaultNetworkTierProjectRequest ): client = ProjectsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1826,17 +1813,16 @@ def test_set_default_network_tier_rest( 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_default_network_tier(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" @@ -1870,7 +1856,7 @@ def test_set_default_network_tier_rest_from_dict(): def test_set_default_network_tier_rest_flattened(): - client = ProjectsClient(credentials=credentials.AnonymousCredentials(),) + client = ProjectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1889,7 +1875,6 @@ def test_set_default_network_tier_rest_flattened(): projects_set_default_network_tier_request_resource = compute.ProjectsSetDefaultNetworkTierRequest( network_tier=compute.ProjectsSetDefaultNetworkTierRequest.NetworkTier.PREMIUM ) - client.set_default_network_tier( project="project_value", projects_set_default_network_tier_request_resource=projects_set_default_network_tier_request_resource, @@ -1900,9 +1885,7 @@ def test_set_default_network_tier_rest_flattened(): 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.ProjectsSetDefaultNetworkTierRequest.to_json( projects_set_default_network_tier_request_resource, including_default_value_fields=False, @@ -1911,7 +1894,7 @@ def test_set_default_network_tier_rest_flattened(): def test_set_default_network_tier_rest_flattened_error(): - client = ProjectsClient(credentials=credentials.AnonymousCredentials(),) + client = ProjectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1929,7 +1912,7 @@ def test_set_usage_export_bucket_rest( transport: str = "rest", request_type=compute.SetUsageExportBucketProjectRequest ): client = ProjectsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1964,17 +1947,16 @@ def test_set_usage_export_bucket_rest( 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_usage_export_bucket(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" @@ -2008,7 +1990,7 @@ def test_set_usage_export_bucket_rest_from_dict(): def test_set_usage_export_bucket_rest_flattened(): - client = ProjectsClient(credentials=credentials.AnonymousCredentials(),) + client = ProjectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -2027,7 +2009,6 @@ def test_set_usage_export_bucket_rest_flattened(): usage_export_location_resource = compute.UsageExportLocation( bucket_name="bucket_name_value" ) - client.set_usage_export_bucket( project="project_value", usage_export_location_resource=usage_export_location_resource, @@ -2038,9 +2019,7 @@ def test_set_usage_export_bucket_rest_flattened(): 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.UsageExportLocation.to_json( usage_export_location_resource, including_default_value_fields=False, @@ -2049,7 +2028,7 @@ def test_set_usage_export_bucket_rest_flattened(): def test_set_usage_export_bucket_rest_flattened_error(): - client = ProjectsClient(credentials=credentials.AnonymousCredentials(),) + client = ProjectsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2066,16 +2045,16 @@ def test_set_usage_export_bucket_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ProjectsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ProjectsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.ProjectsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ProjectsClient( @@ -2085,7 +2064,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ProjectsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ProjectsClient( @@ -2096,7 +2075,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ProjectsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ProjectsClient(transport=transport) assert client.transport is transport @@ -2105,17 +2084,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.ProjectsRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_projects_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ProjectsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2127,7 +2106,7 @@ def test_projects_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ProjectsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2152,15 +2131,40 @@ def test_projects_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_projects_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.projects.transports.ProjectsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProjectsTransport( + 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_projects_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.projects.transports.ProjectsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ProjectsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2176,19 +2180,36 @@ def test_projects_base_transport_with_credentials_file(): def test_projects_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.projects.transports.ProjectsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ProjectsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_projects_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ProjectsClient() + 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_projects_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) ProjectsClient() adc.assert_called_once_with( scopes=( @@ -2200,7 +2221,7 @@ def test_projects_auth_adc(): def test_projects_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -2212,7 +2233,7 @@ def test_projects_http_transport_client_cert_source_for_mtls(): def test_projects_host_no_port(): client = ProjectsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -2222,7 +2243,7 @@ def test_projects_host_no_port(): def test_projects_host_with_port(): client = ProjectsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -2232,7 +2253,6 @@ def test_projects_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2253,7 +2273,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = ProjectsClient.common_folder_path(folder) assert expected == actual @@ -2272,7 +2291,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = ProjectsClient.common_organization_path(organization) assert expected == actual @@ -2291,7 +2309,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = ProjectsClient.common_project_path(project) assert expected == actual @@ -2311,7 +2328,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2338,7 +2354,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ProjectsTransport, "_prep_wrapped_messages" ) as prep: client = ProjectsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2347,6 +2363,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ProjectsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_region_autoscalers.py b/tests/unit/gapic/compute_v1/test_region_autoscalers.py index dd7c822ff..d22537abe 100644 --- a/tests/unit/gapic/compute_v1/test_region_autoscalers.py +++ b/tests/unit/gapic/compute_v1/test_region_autoscalers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -88,7 +117,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [RegionAutoscalersClient,]) def test_region_autoscalers_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -103,7 +132,7 @@ def test_region_autoscalers_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [RegionAutoscalersClient,]) def test_region_autoscalers_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -144,7 +173,7 @@ def test_region_autoscalers_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(RegionAutoscalersClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -392,7 +421,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteRegionAutoscalerRequest ): client = RegionAutoscalersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -427,17 +456,16 @@ def test_delete_rest( 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" @@ -471,7 +499,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = RegionAutoscalersClient(credentials=credentials.AnonymousCredentials(),) + client = RegionAutoscalersClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -498,16 +526,13 @@ def test_delete_rest_flattened(): 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 "autoscaler_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = RegionAutoscalersClient(credentials=credentials.AnonymousCredentials(),) + client = RegionAutoscalersClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -524,7 +549,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetRegionAutoscalerRequest ): client = RegionAutoscalersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -549,17 +574,16 @@ def test_get_rest( target="target_value", zone="zone_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.Autoscaler.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.Autoscaler) assert response.autoscaling_policy == compute.AutoscalingPolicy( cool_down_period_sec=2112 @@ -585,7 +609,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = RegionAutoscalersClient(credentials=credentials.AnonymousCredentials(),) + client = RegionAutoscalersClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -612,16 +636,13 @@ def test_get_rest_flattened(): 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 "autoscaler_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = RegionAutoscalersClient(credentials=credentials.AnonymousCredentials(),) + client = RegionAutoscalersClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -638,7 +659,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertRegionAutoscalerRequest ): client = RegionAutoscalersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -673,17 +694,16 @@ def test_insert_rest( 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" @@ -717,7 +737,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = RegionAutoscalersClient(credentials=credentials.AnonymousCredentials(),) + client = RegionAutoscalersClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -736,7 +756,6 @@ def test_insert_rest_flattened(): autoscaler_resource = compute.Autoscaler( autoscaling_policy=compute.AutoscalingPolicy(cool_down_period_sec=2112) ) - client.insert( project="project_value", region="region_value", @@ -748,11 +767,8 @@ def test_insert_rest_flattened(): 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.Autoscaler.to_json( autoscaler_resource, including_default_value_fields=False, @@ -761,7 +777,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = RegionAutoscalersClient(credentials=credentials.AnonymousCredentials(),) + client = RegionAutoscalersClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -780,7 +796,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListRegionAutoscalersRequest ): client = RegionAutoscalersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -804,17 +820,16 @@ def test_list_rest( 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.RegionAutoscalerList.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 == [ @@ -833,7 +848,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = RegionAutoscalersClient(credentials=credentials.AnonymousCredentials(),) + client = RegionAutoscalersClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -858,14 +873,12 @@ def test_list_rest_flattened(): 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 = RegionAutoscalersClient(credentials=credentials.AnonymousCredentials(),) + client = RegionAutoscalersClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -878,12 +891,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = RegionAutoscalersClient(credentials=credentials.AnonymousCredentials(),) + client = RegionAutoscalersClient(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.RegionAutoscalerList( items=[ @@ -901,7 +913,6 @@ def test_list_pager(): items=[compute.Autoscaler(), compute.Autoscaler(),], ), ) - # Two responses for two calls response = response + response @@ -920,7 +931,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.Autoscaler) for i in results) pages = list(client.list(request={}).pages) @@ -932,7 +942,7 @@ def test_patch_rest( transport: str = "rest", request_type=compute.PatchRegionAutoscalerRequest ): client = RegionAutoscalersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -967,17 +977,16 @@ def test_patch_rest( 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" @@ -1011,7 +1020,7 @@ def test_patch_rest_from_dict(): def test_patch_rest_flattened(): - client = RegionAutoscalersClient(credentials=credentials.AnonymousCredentials(),) + client = RegionAutoscalersClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1030,7 +1039,6 @@ def test_patch_rest_flattened(): autoscaler_resource = compute.Autoscaler( autoscaling_policy=compute.AutoscalingPolicy(cool_down_period_sec=2112) ) - client.patch( project="project_value", region="region_value", @@ -1042,11 +1050,8 @@ def test_patch_rest_flattened(): 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.Autoscaler.to_json( autoscaler_resource, including_default_value_fields=False, @@ -1055,7 +1060,7 @@ def test_patch_rest_flattened(): def test_patch_rest_flattened_error(): - client = RegionAutoscalersClient(credentials=credentials.AnonymousCredentials(),) + client = RegionAutoscalersClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1074,7 +1079,7 @@ def test_update_rest( transport: str = "rest", request_type=compute.UpdateRegionAutoscalerRequest ): client = RegionAutoscalersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1109,17 +1114,16 @@ def test_update_rest( 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.update(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" @@ -1153,7 +1157,7 @@ def test_update_rest_from_dict(): def test_update_rest_flattened(): - client = RegionAutoscalersClient(credentials=credentials.AnonymousCredentials(),) + client = RegionAutoscalersClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1172,7 +1176,6 @@ def test_update_rest_flattened(): autoscaler_resource = compute.Autoscaler( autoscaling_policy=compute.AutoscalingPolicy(cool_down_period_sec=2112) ) - client.update( project="project_value", region="region_value", @@ -1184,11 +1187,8 @@ def test_update_rest_flattened(): 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.Autoscaler.to_json( autoscaler_resource, including_default_value_fields=False, @@ -1197,7 +1197,7 @@ def test_update_rest_flattened(): def test_update_rest_flattened_error(): - client = RegionAutoscalersClient(credentials=credentials.AnonymousCredentials(),) + client = RegionAutoscalersClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1215,16 +1215,16 @@ def test_update_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.RegionAutoscalersRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionAutoscalersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.RegionAutoscalersRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionAutoscalersClient( @@ -1234,7 +1234,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.RegionAutoscalersRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionAutoscalersClient( @@ -1245,7 +1245,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.RegionAutoscalersRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = RegionAutoscalersClient(transport=transport) assert client.transport is transport @@ -1256,17 +1256,17 @@ def test_transport_instance(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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_autoscalers_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.RegionAutoscalersTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1278,7 +1278,7 @@ def test_region_autoscalers_base_transport(): ) as Transport: Transport.return_value = None transport = transports.RegionAutoscalersTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1296,15 +1296,40 @@ def test_region_autoscalers_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_region_autoscalers_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.region_autoscalers.transports.RegionAutoscalersTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionAutoscalersTransport( + 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_autoscalers_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_autoscalers.transports.RegionAutoscalersTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionAutoscalersTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1320,19 +1345,36 @@ def test_region_autoscalers_base_transport_with_credentials_file(): def test_region_autoscalers_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.region_autoscalers.transports.RegionAutoscalersTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionAutoscalersTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_region_autoscalers_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RegionAutoscalersClient() + 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_autoscalers_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) RegionAutoscalersClient() adc.assert_called_once_with( scopes=( @@ -1344,7 +1386,7 @@ def test_region_autoscalers_auth_adc(): def test_region_autoscalers_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1356,7 +1398,7 @@ def test_region_autoscalers_http_transport_client_cert_source_for_mtls(): def test_region_autoscalers_host_no_port(): client = RegionAutoscalersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1366,7 +1408,7 @@ def test_region_autoscalers_host_no_port(): def test_region_autoscalers_host_with_port(): client = RegionAutoscalersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1376,7 +1418,6 @@ def test_region_autoscalers_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1397,7 +1438,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = RegionAutoscalersClient.common_folder_path(folder) assert expected == actual @@ -1416,7 +1456,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = RegionAutoscalersClient.common_organization_path(organization) assert expected == actual @@ -1435,7 +1474,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = RegionAutoscalersClient.common_project_path(project) assert expected == actual @@ -1455,7 +1493,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1482,7 +1519,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.RegionAutoscalersTransport, "_prep_wrapped_messages" ) as prep: client = RegionAutoscalersClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1491,6 +1528,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = RegionAutoscalersClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_region_backend_services.py b/tests/unit/gapic/compute_v1/test_region_backend_services.py index 98be11a11..edde9feb2 100644 --- a/tests/unit/gapic/compute_v1/test_region_backend_services.py +++ b/tests/unit/gapic/compute_v1/test_region_backend_services.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,33 +13,63 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.compute_v1.services.region_backend_services import ( RegionBackendServicesClient, ) 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, +) 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 +# - 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", +) + +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(): @@ -90,7 +119,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [RegionBackendServicesClient,]) def test_region_backend_services_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -105,7 +134,7 @@ def test_region_backend_services_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [RegionBackendServicesClient,]) def test_region_backend_services_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -152,7 +181,7 @@ def test_region_backend_services_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(RegionBackendServicesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -412,7 +441,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteRegionBackendServiceRequest ): client = RegionBackendServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -447,17 +476,16 @@ def test_delete_rest( 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" @@ -492,7 +520,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): client = RegionBackendServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -520,17 +548,14 @@ def test_delete_rest_flattened(): 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 "backend_service_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): client = RegionBackendServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -548,7 +573,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetRegionBackendServiceRequest ): client = RegionBackendServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -606,17 +631,16 @@ def test_get_rest( session_affinity=compute.BackendService.SessionAffinity.CLIENT_IP, timeout_sec=1185, ) + # Wrap the value into a proper Response obj json_return_value = compute.BackendService.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.BackendService) assert response.affinity_cookie_ttl_sec == 2432 assert response.backends == [ @@ -638,7 +662,6 @@ def test_get_rest( assert response.custom_request_headers == ["custom_request_headers_value"] assert response.custom_response_headers == ["custom_response_headers_value"] assert response.description == "description_value" - assert response.enable_c_d_n is True assert response.failover_policy == compute.BackendServiceFailoverPolicy( disable_connection_drain_on_failover=True @@ -681,7 +704,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): client = RegionBackendServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -709,17 +732,14 @@ def test_get_rest_flattened(): 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 "backend_service_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): client = RegionBackendServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -737,7 +757,7 @@ def test_get_health_rest( transport: str = "rest", request_type=compute.GetHealthRegionBackendServiceRequest ): client = RegionBackendServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -754,17 +774,16 @@ def test_get_health_rest( ], kind="kind_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.BackendServiceGroupHealth.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_health(request) # Establish that the response is the type that we expect. - assert isinstance(response, compute.BackendServiceGroupHealth) assert response.annotations == {"key_value": "value_value"} assert response.health_status == [ @@ -779,7 +798,7 @@ def test_get_health_rest_from_dict(): def test_get_health_rest_flattened(): client = RegionBackendServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -799,7 +818,6 @@ def test_get_health_rest_flattened(): resource_group_reference_resource = compute.ResourceGroupReference( group="group_value" ) - client.get_health( project="project_value", region="region_value", @@ -812,13 +830,9 @@ def test_get_health_rest_flattened(): 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 "backend_service_value" in http_call[1] + str(body) - assert compute.ResourceGroupReference.to_json( resource_group_reference_resource, including_default_value_fields=False, @@ -828,7 +842,7 @@ def test_get_health_rest_flattened(): def test_get_health_rest_flattened_error(): client = RegionBackendServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -849,7 +863,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertRegionBackendServiceRequest ): client = RegionBackendServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -884,17 +898,16 @@ def test_insert_rest( 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" @@ -929,7 +942,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): client = RegionBackendServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -947,7 +960,6 @@ def test_insert_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. backend_service_resource = compute.BackendService(affinity_cookie_ttl_sec=2432) - client.insert( project="project_value", region="region_value", @@ -959,11 +971,8 @@ def test_insert_rest_flattened(): 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.BackendService.to_json( backend_service_resource, including_default_value_fields=False, @@ -973,7 +982,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): client = RegionBackendServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -993,7 +1002,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListRegionBackendServicesRequest ): client = RegionBackendServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1011,17 +1020,16 @@ def test_list_rest( 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.BackendServiceList.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.BackendService(affinity_cookie_ttl_sec=2432)] @@ -1037,7 +1045,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): client = RegionBackendServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1063,15 +1071,13 @@ def test_list_rest_flattened(): 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 = RegionBackendServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1086,13 +1092,12 @@ def test_list_rest_flattened_error(): def test_list_pager(): client = RegionBackendServicesClient( - credentials=credentials.AnonymousCredentials(), + 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.BackendServiceList( items=[ @@ -1110,7 +1115,6 @@ def test_list_pager(): items=[compute.BackendService(), compute.BackendService(),], ), ) - # Two responses for two calls response = response + response @@ -1129,7 +1133,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.BackendService) for i in results) pages = list(client.list(request={}).pages) @@ -1141,7 +1144,7 @@ def test_patch_rest( transport: str = "rest", request_type=compute.PatchRegionBackendServiceRequest ): client = RegionBackendServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1176,17 +1179,16 @@ def test_patch_rest( 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" @@ -1221,7 +1223,7 @@ def test_patch_rest_from_dict(): def test_patch_rest_flattened(): client = RegionBackendServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1239,7 +1241,6 @@ def test_patch_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. backend_service_resource = compute.BackendService(affinity_cookie_ttl_sec=2432) - client.patch( project="project_value", region="region_value", @@ -1252,13 +1253,9 @@ def test_patch_rest_flattened(): 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 "backend_service_value" in http_call[1] + str(body) - assert compute.BackendService.to_json( backend_service_resource, including_default_value_fields=False, @@ -1268,7 +1265,7 @@ def test_patch_rest_flattened(): def test_patch_rest_flattened_error(): client = RegionBackendServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1289,7 +1286,7 @@ def test_update_rest( transport: str = "rest", request_type=compute.UpdateRegionBackendServiceRequest ): client = RegionBackendServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1324,17 +1321,16 @@ def test_update_rest( 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.update(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" @@ -1369,7 +1365,7 @@ def test_update_rest_from_dict(): def test_update_rest_flattened(): client = RegionBackendServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1387,7 +1383,6 @@ def test_update_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. backend_service_resource = compute.BackendService(affinity_cookie_ttl_sec=2432) - client.update( project="project_value", region="region_value", @@ -1400,13 +1395,9 @@ def test_update_rest_flattened(): 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 "backend_service_value" in http_call[1] + str(body) - assert compute.BackendService.to_json( backend_service_resource, including_default_value_fields=False, @@ -1416,7 +1407,7 @@ def test_update_rest_flattened(): def test_update_rest_flattened_error(): client = RegionBackendServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1436,16 +1427,16 @@ def test_update_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.RegionBackendServicesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionBackendServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.RegionBackendServicesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionBackendServicesClient( @@ -1455,7 +1446,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.RegionBackendServicesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionBackendServicesClient( @@ -1466,7 +1457,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.RegionBackendServicesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = RegionBackendServicesClient(transport=transport) assert client.transport is transport @@ -1477,17 +1468,17 @@ def test_transport_instance(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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_backend_services_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.RegionBackendServicesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1499,7 +1490,7 @@ def test_region_backend_services_base_transport(): ) as Transport: Transport.return_value = None transport = transports.RegionBackendServicesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1518,15 +1509,40 @@ def test_region_backend_services_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_region_backend_services_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.region_backend_services.transports.RegionBackendServicesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionBackendServicesTransport( + 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_backend_services_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_backend_services.transports.RegionBackendServicesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionBackendServicesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1542,19 +1558,36 @@ def test_region_backend_services_base_transport_with_credentials_file(): def test_region_backend_services_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.region_backend_services.transports.RegionBackendServicesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionBackendServicesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_region_backend_services_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RegionBackendServicesClient() + 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_backend_services_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) RegionBackendServicesClient() adc.assert_called_once_with( scopes=( @@ -1566,7 +1599,7 @@ def test_region_backend_services_auth_adc(): def test_region_backend_services_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1578,7 +1611,7 @@ def test_region_backend_services_http_transport_client_cert_source_for_mtls(): def test_region_backend_services_host_no_port(): client = RegionBackendServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1588,7 +1621,7 @@ def test_region_backend_services_host_no_port(): def test_region_backend_services_host_with_port(): client = RegionBackendServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1598,7 +1631,6 @@ def test_region_backend_services_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1619,7 +1651,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = RegionBackendServicesClient.common_folder_path(folder) assert expected == actual @@ -1638,7 +1669,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = RegionBackendServicesClient.common_organization_path(organization) assert expected == actual @@ -1657,7 +1687,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = RegionBackendServicesClient.common_project_path(project) assert expected == actual @@ -1677,7 +1706,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1704,7 +1732,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.RegionBackendServicesTransport, "_prep_wrapped_messages" ) as prep: client = RegionBackendServicesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1713,6 +1741,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = RegionBackendServicesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_region_commitments.py b/tests/unit/gapic/compute_v1/test_region_commitments.py index ae9d3bd8e..77220fc2c 100644 --- a/tests/unit/gapic/compute_v1/test_region_commitments.py +++ b/tests/unit/gapic/compute_v1/test_region_commitments.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -88,7 +117,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [RegionCommitmentsClient,]) def test_region_commitments_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -103,7 +132,7 @@ def test_region_commitments_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [RegionCommitmentsClient,]) def test_region_commitments_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -144,7 +173,7 @@ def test_region_commitments_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(RegionCommitmentsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -392,7 +421,7 @@ def test_aggregated_list_rest( transport: str = "rest", request_type=compute.AggregatedListRegionCommitmentsRequest ): client = RegionCommitmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -419,17 +448,16 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.CommitmentAggregatedList.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 == { @@ -453,7 +481,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = RegionCommitmentsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionCommitmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -476,12 +504,11 @@ def test_aggregated_list_rest_flattened(): 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 = RegionCommitmentsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionCommitmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -492,12 +519,11 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = RegionCommitmentsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionCommitmentsClient(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.CommitmentAggregatedList( items={ @@ -518,7 +544,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -540,7 +565,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -561,7 +585,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetRegionCommitmentRequest ): client = RegionCommitmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -591,17 +615,16 @@ def test_get_rest( status=compute.Commitment.Status.ACTIVE, status_message="status_message_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.Commitment.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.Commitment) assert response.category == compute.Commitment.Category.CATEGORY_UNSPECIFIED assert response.creation_timestamp == "creation_timestamp_value" @@ -630,7 +653,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = RegionCommitmentsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionCommitmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -657,16 +680,13 @@ def test_get_rest_flattened(): 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 "commitment_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = RegionCommitmentsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionCommitmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -683,7 +703,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertRegionCommitmentRequest ): client = RegionCommitmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -718,17 +738,16 @@ def test_insert_rest( 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" @@ -762,7 +781,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = RegionCommitmentsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionCommitmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -781,7 +800,6 @@ def test_insert_rest_flattened(): commitment_resource = compute.Commitment( category=compute.Commitment.Category.CATEGORY_UNSPECIFIED ) - client.insert( project="project_value", region="region_value", @@ -793,11 +811,8 @@ def test_insert_rest_flattened(): 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.Commitment.to_json( commitment_resource, including_default_value_fields=False, @@ -806,7 +821,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = RegionCommitmentsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionCommitmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -825,7 +840,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListRegionCommitmentsRequest ): client = RegionCommitmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -847,17 +862,16 @@ def test_list_rest( 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.CommitmentList.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 == [ @@ -874,7 +888,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = RegionCommitmentsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionCommitmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -899,14 +913,12 @@ def test_list_rest_flattened(): 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 = RegionCommitmentsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionCommitmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -919,12 +931,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = RegionCommitmentsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionCommitmentsClient(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.CommitmentList( items=[ @@ -942,7 +953,6 @@ def test_list_pager(): items=[compute.Commitment(), compute.Commitment(),], ), ) - # Two responses for two calls response = response + response @@ -961,7 +971,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.Commitment) for i in results) pages = list(client.list(request={}).pages) @@ -972,16 +981,16 @@ def test_list_pager(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.RegionCommitmentsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionCommitmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.RegionCommitmentsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionCommitmentsClient( @@ -991,7 +1000,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.RegionCommitmentsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionCommitmentsClient( @@ -1002,7 +1011,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.RegionCommitmentsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = RegionCommitmentsClient(transport=transport) assert client.transport is transport @@ -1013,17 +1022,17 @@ def test_transport_instance(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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_commitments_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.RegionCommitmentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1035,7 +1044,7 @@ def test_region_commitments_base_transport(): ) as Transport: Transport.return_value = None transport = transports.RegionCommitmentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1051,15 +1060,40 @@ def test_region_commitments_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_region_commitments_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.region_commitments.transports.RegionCommitmentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionCommitmentsTransport( + 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_commitments_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_commitments.transports.RegionCommitmentsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionCommitmentsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1075,19 +1109,36 @@ def test_region_commitments_base_transport_with_credentials_file(): def test_region_commitments_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.region_commitments.transports.RegionCommitmentsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionCommitmentsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_region_commitments_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RegionCommitmentsClient() + 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_commitments_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) RegionCommitmentsClient() adc.assert_called_once_with( scopes=( @@ -1099,7 +1150,7 @@ def test_region_commitments_auth_adc(): def test_region_commitments_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1111,7 +1162,7 @@ def test_region_commitments_http_transport_client_cert_source_for_mtls(): def test_region_commitments_host_no_port(): client = RegionCommitmentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1121,7 +1172,7 @@ def test_region_commitments_host_no_port(): def test_region_commitments_host_with_port(): client = RegionCommitmentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1131,7 +1182,6 @@ def test_region_commitments_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1152,7 +1202,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = RegionCommitmentsClient.common_folder_path(folder) assert expected == actual @@ -1171,7 +1220,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = RegionCommitmentsClient.common_organization_path(organization) assert expected == actual @@ -1190,7 +1238,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = RegionCommitmentsClient.common_project_path(project) assert expected == actual @@ -1210,7 +1257,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1237,7 +1283,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.RegionCommitmentsTransport, "_prep_wrapped_messages" ) as prep: client = RegionCommitmentsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1246,6 +1292,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = RegionCommitmentsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_region_disk_types.py b/tests/unit/gapic/compute_v1/test_region_disk_types.py index 77acd6b82..3b431f16a 100644 --- a/tests/unit/gapic/compute_v1/test_region_disk_types.py +++ b/tests/unit/gapic/compute_v1/test_region_disk_types.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -87,7 +116,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [RegionDiskTypesClient,]) def test_region_disk_types_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -102,7 +131,7 @@ def test_region_disk_types_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [RegionDiskTypesClient,]) def test_region_disk_types_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -143,7 +172,7 @@ def test_region_disk_types_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(RegionDiskTypesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -391,7 +420,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetRegionDiskTypeRequest ): client = RegionDiskTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -414,17 +443,16 @@ def test_get_rest( valid_disk_size="valid_disk_size_value", zone="zone_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.DiskType.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.DiskType) assert response.creation_timestamp == "creation_timestamp_value" assert response.default_disk_size_gb == "default_disk_size_gb_value" @@ -444,7 +472,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = RegionDiskTypesClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDiskTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -469,16 +497,13 @@ def test_get_rest_flattened(): 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 "disk_type_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = RegionDiskTypesClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDiskTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -495,7 +520,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListRegionDiskTypesRequest ): client = RegionDiskTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -513,17 +538,16 @@ def test_list_rest( 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.RegionDiskTypeList.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 == [ @@ -540,7 +564,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = RegionDiskTypesClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDiskTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -565,14 +589,12 @@ def test_list_rest_flattened(): 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 = RegionDiskTypesClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDiskTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -585,12 +607,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = RegionDiskTypesClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDiskTypesClient(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.RegionDiskTypeList( items=[compute.DiskType(), compute.DiskType(), compute.DiskType(),], @@ -604,7 +625,6 @@ def test_list_pager(): items=[compute.DiskType(), compute.DiskType(),], ), ) - # Two responses for two calls response = response + response @@ -623,7 +643,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.DiskType) for i in results) pages = list(client.list(request={}).pages) @@ -634,16 +653,16 @@ def test_list_pager(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.RegionDiskTypesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionDiskTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.RegionDiskTypesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionDiskTypesClient( @@ -653,7 +672,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.RegionDiskTypesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionDiskTypesClient( @@ -664,7 +683,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.RegionDiskTypesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = RegionDiskTypesClient(transport=transport) assert client.transport is transport @@ -673,17 +692,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.RegionDiskTypesRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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_disk_types_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.RegionDiskTypesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -695,7 +714,7 @@ def test_region_disk_types_base_transport(): ) as Transport: Transport.return_value = None transport = transports.RegionDiskTypesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -709,15 +728,41 @@ def test_region_disk_types_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_region_disk_types_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.region_disk_types.transports.RegionDiskTypesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionDiskTypesTransport( + 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.readonly", + "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_disk_types_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_disk_types.transports.RegionDiskTypesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionDiskTypesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -734,19 +779,37 @@ def test_region_disk_types_base_transport_with_credentials_file(): def test_region_disk_types_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.region_disk_types.transports.RegionDiskTypesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionDiskTypesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_region_disk_types_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RegionDiskTypesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/compute.readonly", + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_region_disk_types_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) RegionDiskTypesClient() adc.assert_called_once_with( scopes=( @@ -759,7 +822,7 @@ def test_region_disk_types_auth_adc(): def test_region_disk_types_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -771,7 +834,7 @@ def test_region_disk_types_http_transport_client_cert_source_for_mtls(): def test_region_disk_types_host_no_port(): client = RegionDiskTypesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -781,7 +844,7 @@ def test_region_disk_types_host_no_port(): def test_region_disk_types_host_with_port(): client = RegionDiskTypesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -791,7 +854,6 @@ def test_region_disk_types_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -812,7 +874,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = RegionDiskTypesClient.common_folder_path(folder) assert expected == actual @@ -831,7 +892,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = RegionDiskTypesClient.common_organization_path(organization) assert expected == actual @@ -850,7 +910,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = RegionDiskTypesClient.common_project_path(project) assert expected == actual @@ -870,7 +929,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -897,7 +955,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.RegionDiskTypesTransport, "_prep_wrapped_messages" ) as prep: client = RegionDiskTypesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -906,6 +964,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = RegionDiskTypesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_region_disks.py b/tests/unit/gapic/compute_v1/test_region_disks.py index ca54bfd47..8a24d33e6 100644 --- a/tests/unit/gapic/compute_v1/test_region_disks.py +++ b/tests/unit/gapic/compute_v1/test_region_disks.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -84,7 +113,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [RegionDisksClient,]) def test_region_disks_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -99,7 +128,7 @@ def test_region_disks_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [RegionDisksClient,]) def test_region_disks_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -138,7 +167,7 @@ def test_region_disks_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(RegionDisksClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -374,7 +403,7 @@ def test_add_resource_policies_rest( transport: str = "rest", request_type=compute.AddResourcePoliciesRegionDiskRequest ): client = RegionDisksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -409,17 +438,16 @@ def test_add_resource_policies_rest( 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_resource_policies(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" @@ -453,7 +481,7 @@ def test_add_resource_policies_rest_from_dict(): def test_add_resource_policies_rest_flattened(): - client = RegionDisksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -472,7 +500,6 @@ def test_add_resource_policies_rest_flattened(): region_disks_add_resource_policies_request_resource = compute.RegionDisksAddResourcePoliciesRequest( resource_policies=["resource_policies_value"] ) - client.add_resource_policies( project="project_value", region="region_value", @@ -485,13 +512,9 @@ def test_add_resource_policies_rest_flattened(): 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 "disk_value" in http_call[1] + str(body) - assert compute.RegionDisksAddResourcePoliciesRequest.to_json( region_disks_add_resource_policies_request_resource, including_default_value_fields=False, @@ -500,7 +523,7 @@ def test_add_resource_policies_rest_flattened(): def test_add_resource_policies_rest_flattened_error(): - client = RegionDisksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -520,7 +543,7 @@ def test_create_snapshot_rest( transport: str = "rest", request_type=compute.CreateSnapshotRegionDiskRequest ): client = RegionDisksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -555,17 +578,16 @@ def test_create_snapshot_rest( 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.create_snapshot(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" @@ -599,7 +621,7 @@ def test_create_snapshot_rest_from_dict(): def test_create_snapshot_rest_flattened(): - client = RegionDisksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -616,7 +638,6 @@ def test_create_snapshot_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. snapshot_resource = compute.Snapshot(auto_created=True) - client.create_snapshot( project="project_value", region="region_value", @@ -629,13 +650,9 @@ def test_create_snapshot_rest_flattened(): 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 "disk_value" in http_call[1] + str(body) - assert compute.Snapshot.to_json( snapshot_resource, including_default_value_fields=False, @@ -644,7 +661,7 @@ def test_create_snapshot_rest_flattened(): def test_create_snapshot_rest_flattened_error(): - client = RegionDisksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -662,7 +679,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteRegionDiskRequest ): client = RegionDisksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -697,17 +714,16 @@ def test_delete_rest( 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" @@ -741,7 +757,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = RegionDisksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -766,16 +782,13 @@ def test_delete_rest_flattened(): 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 "disk_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = RegionDisksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -790,7 +803,7 @@ def test_delete_rest_flattened_error(): def test_get_rest(transport: str = "rest", request_type=compute.GetRegionDiskRequest): client = RegionDisksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -844,17 +857,16 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetRegionDiskReq users=["users_value"], zone="zone_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.Disk.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.Disk) assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" @@ -905,7 +917,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = RegionDisksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -930,16 +942,13 @@ def test_get_rest_flattened(): 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 "disk_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = RegionDisksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -956,7 +965,7 @@ def test_get_iam_policy_rest( transport: str = "rest", request_type=compute.GetIamPolicyRegionDiskRequest ): client = RegionDisksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -982,17 +991,16 @@ def test_get_iam_policy_rest( 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( @@ -1003,7 +1011,6 @@ def test_get_iam_policy_rest( ] 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 @@ -1014,7 +1021,7 @@ def test_get_iam_policy_rest_from_dict(): def test_get_iam_policy_rest_flattened(): - client = RegionDisksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1039,16 +1046,13 @@ def test_get_iam_policy_rest_flattened(): 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) def test_get_iam_policy_rest_flattened_error(): - client = RegionDisksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1065,7 +1069,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertRegionDiskRequest ): client = RegionDisksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1100,17 +1104,16 @@ def test_insert_rest( 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" @@ -1144,7 +1147,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = RegionDisksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1161,7 +1164,6 @@ def test_insert_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. disk_resource = compute.Disk(creation_timestamp="creation_timestamp_value") - client.insert( project="project_value", region="region_value", disk_resource=disk_resource, ) @@ -1171,11 +1173,8 @@ def test_insert_rest_flattened(): 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.Disk.to_json( disk_resource, including_default_value_fields=False, @@ -1184,7 +1183,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = RegionDisksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1201,7 +1200,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListRegionDisksRequest ): client = RegionDisksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1219,17 +1218,16 @@ def test_list_rest( 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.DiskList.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 == [ @@ -1246,7 +1244,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = RegionDisksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1271,14 +1269,12 @@ def test_list_rest_flattened(): 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 = RegionDisksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1291,12 +1287,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = RegionDisksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDisksClient(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.DiskList( items=[compute.Disk(), compute.Disk(), compute.Disk(),], @@ -1306,7 +1301,6 @@ def test_list_pager(): compute.DiskList(items=[compute.Disk(),], next_page_token="ghi",), compute.DiskList(items=[compute.Disk(), compute.Disk(),],), ) - # Two responses for two calls response = response + response @@ -1325,7 +1319,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.Disk) for i in results) pages = list(client.list(request={}).pages) @@ -1338,7 +1331,7 @@ def test_remove_resource_policies_rest( request_type=compute.RemoveResourcePoliciesRegionDiskRequest, ): client = RegionDisksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1373,17 +1366,16 @@ def test_remove_resource_policies_rest( 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_resource_policies(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" @@ -1417,7 +1409,7 @@ def test_remove_resource_policies_rest_from_dict(): def test_remove_resource_policies_rest_flattened(): - client = RegionDisksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1436,7 +1428,6 @@ def test_remove_resource_policies_rest_flattened(): region_disks_remove_resource_policies_request_resource = compute.RegionDisksRemoveResourcePoliciesRequest( resource_policies=["resource_policies_value"] ) - client.remove_resource_policies( project="project_value", region="region_value", @@ -1449,13 +1440,9 @@ def test_remove_resource_policies_rest_flattened(): 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 "disk_value" in http_call[1] + str(body) - assert compute.RegionDisksRemoveResourcePoliciesRequest.to_json( region_disks_remove_resource_policies_request_resource, including_default_value_fields=False, @@ -1464,7 +1451,7 @@ def test_remove_resource_policies_rest_flattened(): def test_remove_resource_policies_rest_flattened_error(): - client = RegionDisksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1484,7 +1471,7 @@ def test_resize_rest( transport: str = "rest", request_type=compute.ResizeRegionDiskRequest ): client = RegionDisksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1519,17 +1506,16 @@ def test_resize_rest( 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.resize(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" @@ -1563,7 +1549,7 @@ def test_resize_rest_from_dict(): def test_resize_rest_flattened(): - client = RegionDisksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1582,7 +1568,6 @@ def test_resize_rest_flattened(): region_disks_resize_request_resource = compute.RegionDisksResizeRequest( size_gb="size_gb_value" ) - client.resize( project="project_value", region="region_value", @@ -1595,13 +1580,9 @@ def test_resize_rest_flattened(): 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 "disk_value" in http_call[1] + str(body) - assert compute.RegionDisksResizeRequest.to_json( region_disks_resize_request_resource, including_default_value_fields=False, @@ -1610,7 +1591,7 @@ def test_resize_rest_flattened(): def test_resize_rest_flattened_error(): - client = RegionDisksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1630,7 +1611,7 @@ def test_set_iam_policy_rest( transport: str = "rest", request_type=compute.SetIamPolicyRegionDiskRequest ): client = RegionDisksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1656,17 +1637,16 @@ def test_set_iam_policy_rest( 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( @@ -1677,7 +1657,6 @@ def test_set_iam_policy_rest( ] 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 @@ -1688,7 +1667,7 @@ def test_set_iam_policy_rest_from_dict(): def test_set_iam_policy_rest_flattened(): - client = RegionDisksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1707,7 +1686,6 @@ def test_set_iam_policy_rest_flattened(): region_set_policy_request_resource = compute.RegionSetPolicyRequest( bindings=[compute.Binding(binding_id="binding_id_value")] ) - client.set_iam_policy( project="project_value", region="region_value", @@ -1720,13 +1698,9 @@ def test_set_iam_policy_rest_flattened(): 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.RegionSetPolicyRequest.to_json( region_set_policy_request_resource, including_default_value_fields=False, @@ -1735,7 +1709,7 @@ def test_set_iam_policy_rest_flattened(): def test_set_iam_policy_rest_flattened_error(): - client = RegionDisksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1755,7 +1729,7 @@ def test_set_labels_rest( transport: str = "rest", request_type=compute.SetLabelsRegionDiskRequest ): client = RegionDisksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1790,17 +1764,16 @@ def test_set_labels_rest( 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" @@ -1834,7 +1807,7 @@ def test_set_labels_rest_from_dict(): def test_set_labels_rest_flattened(): - client = RegionDisksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1853,7 +1826,6 @@ def test_set_labels_rest_flattened(): region_set_labels_request_resource = compute.RegionSetLabelsRequest( label_fingerprint="label_fingerprint_value" ) - client.set_labels( project="project_value", region="region_value", @@ -1866,13 +1838,9 @@ def test_set_labels_rest_flattened(): 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, @@ -1881,7 +1849,7 @@ def test_set_labels_rest_flattened(): def test_set_labels_rest_flattened_error(): - client = RegionDisksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1901,7 +1869,7 @@ def test_test_iam_permissions_rest( transport: str = "rest", request_type=compute.TestIamPermissionsRegionDiskRequest ): client = RegionDisksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1914,17 +1882,16 @@ def test_test_iam_permissions_rest( 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"] @@ -1934,7 +1901,7 @@ def test_test_iam_permissions_rest_from_dict(): def test_test_iam_permissions_rest_flattened(): - client = RegionDisksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1953,7 +1920,6 @@ def test_test_iam_permissions_rest_flattened(): test_permissions_request_resource = compute.TestPermissionsRequest( permissions=["permissions_value"] ) - client.test_iam_permissions( project="project_value", region="region_value", @@ -1966,13 +1932,9 @@ def test_test_iam_permissions_rest_flattened(): 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.TestPermissionsRequest.to_json( test_permissions_request_resource, including_default_value_fields=False, @@ -1981,7 +1943,7 @@ def test_test_iam_permissions_rest_flattened(): def test_test_iam_permissions_rest_flattened_error(): - client = RegionDisksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionDisksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2000,16 +1962,16 @@ def test_test_iam_permissions_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.RegionDisksRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionDisksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.RegionDisksRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionDisksClient( @@ -2019,7 +1981,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.RegionDisksRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionDisksClient( @@ -2030,7 +1992,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.RegionDisksRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = RegionDisksClient(transport=transport) assert client.transport is transport @@ -2039,17 +2001,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.RegionDisksRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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_disks_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.RegionDisksTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2061,7 +2023,7 @@ def test_region_disks_base_transport(): ) as Transport: Transport.return_value = None transport = transports.RegionDisksTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2085,15 +2047,40 @@ def test_region_disks_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_region_disks_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.region_disks.transports.RegionDisksTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionDisksTransport( + 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_disks_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_disks.transports.RegionDisksTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionDisksTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2109,19 +2096,36 @@ def test_region_disks_base_transport_with_credentials_file(): def test_region_disks_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.region_disks.transports.RegionDisksTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionDisksTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_region_disks_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RegionDisksClient() + 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_disks_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) RegionDisksClient() adc.assert_called_once_with( scopes=( @@ -2133,7 +2137,7 @@ def test_region_disks_auth_adc(): def test_region_disks_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -2145,7 +2149,7 @@ def test_region_disks_http_transport_client_cert_source_for_mtls(): def test_region_disks_host_no_port(): client = RegionDisksClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -2155,7 +2159,7 @@ def test_region_disks_host_no_port(): def test_region_disks_host_with_port(): client = RegionDisksClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -2165,7 +2169,6 @@ def test_region_disks_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2186,7 +2189,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = RegionDisksClient.common_folder_path(folder) assert expected == actual @@ -2205,7 +2207,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = RegionDisksClient.common_organization_path(organization) assert expected == actual @@ -2224,7 +2225,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = RegionDisksClient.common_project_path(project) assert expected == actual @@ -2244,7 +2244,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2271,7 +2270,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.RegionDisksTransport, "_prep_wrapped_messages" ) as prep: client = RegionDisksClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2280,6 +2279,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = RegionDisksClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_region_health_check_services.py b/tests/unit/gapic/compute_v1/test_region_health_check_services.py index 4778db294..9d710d512 100644 --- a/tests/unit/gapic/compute_v1/test_region_health_check_services.py +++ b/tests/unit/gapic/compute_v1/test_region_health_check_services.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,33 +13,63 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.compute_v1.services.region_health_check_services import ( RegionHealthCheckServicesClient, ) 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, +) 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 +# - 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", +) + +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(): @@ -92,7 +121,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [RegionHealthCheckServicesClient,]) def test_region_health_check_services_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -107,7 +136,7 @@ def test_region_health_check_services_client_from_service_account_info(client_cl @pytest.mark.parametrize("client_class", [RegionHealthCheckServicesClient,]) def test_region_health_check_services_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -156,7 +185,7 @@ def test_region_health_check_services_client_client_options( with mock.patch.object( RegionHealthCheckServicesClient, "get_transport_class" ) as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -418,7 +447,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteRegionHealthCheckServiceRequest ): client = RegionHealthCheckServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -453,17 +482,16 @@ def test_delete_rest( 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" @@ -498,7 +526,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): client = RegionHealthCheckServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -526,17 +554,14 @@ def test_delete_rest_flattened(): 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 "health_check_service_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): client = RegionHealthCheckServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -554,7 +579,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetRegionHealthCheckServiceRequest ): client = RegionHealthCheckServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -578,17 +603,16 @@ def test_get_rest( region="region_value", self_link="self_link_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.HealthCheckService.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.HealthCheckService) assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" @@ -613,7 +637,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): client = RegionHealthCheckServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -641,17 +665,14 @@ def test_get_rest_flattened(): 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 "health_check_service_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): client = RegionHealthCheckServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -669,7 +690,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertRegionHealthCheckServiceRequest ): client = RegionHealthCheckServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -704,17 +725,16 @@ def test_insert_rest( 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" @@ -749,7 +769,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): client = RegionHealthCheckServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -769,7 +789,6 @@ def test_insert_rest_flattened(): health_check_service_resource = compute.HealthCheckService( creation_timestamp="creation_timestamp_value" ) - client.insert( project="project_value", region="region_value", @@ -781,11 +800,8 @@ def test_insert_rest_flattened(): 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.HealthCheckService.to_json( health_check_service_resource, including_default_value_fields=False, @@ -795,7 +811,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): client = RegionHealthCheckServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -815,7 +831,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListRegionHealthCheckServicesRequest ): client = RegionHealthCheckServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -837,17 +853,16 @@ def test_list_rest( 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.HealthCheckServicesList.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 == [ @@ -865,7 +880,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): client = RegionHealthCheckServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -891,15 +906,13 @@ def test_list_rest_flattened(): 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 = RegionHealthCheckServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -914,13 +927,12 @@ def test_list_rest_flattened_error(): def test_list_pager(): client = RegionHealthCheckServicesClient( - credentials=credentials.AnonymousCredentials(), + 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.HealthCheckServicesList( items=[ @@ -938,7 +950,6 @@ def test_list_pager(): items=[compute.HealthCheckService(), compute.HealthCheckService(),], ), ) - # Two responses for two calls response = response + response @@ -957,7 +968,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.HealthCheckService) for i in results) pages = list(client.list(request={}).pages) @@ -969,7 +979,7 @@ def test_patch_rest( transport: str = "rest", request_type=compute.PatchRegionHealthCheckServiceRequest ): client = RegionHealthCheckServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1004,17 +1014,16 @@ def test_patch_rest( 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" @@ -1049,7 +1058,7 @@ def test_patch_rest_from_dict(): def test_patch_rest_flattened(): client = RegionHealthCheckServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1069,7 +1078,6 @@ def test_patch_rest_flattened(): health_check_service_resource = compute.HealthCheckService( creation_timestamp="creation_timestamp_value" ) - client.patch( project="project_value", region="region_value", @@ -1082,13 +1090,9 @@ def test_patch_rest_flattened(): 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 "health_check_service_value" in http_call[1] + str(body) - assert compute.HealthCheckService.to_json( health_check_service_resource, including_default_value_fields=False, @@ -1098,7 +1102,7 @@ def test_patch_rest_flattened(): def test_patch_rest_flattened_error(): client = RegionHealthCheckServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1118,16 +1122,16 @@ def test_patch_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.RegionHealthCheckServicesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionHealthCheckServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.RegionHealthCheckServicesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionHealthCheckServicesClient( @@ -1137,7 +1141,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.RegionHealthCheckServicesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionHealthCheckServicesClient( @@ -1148,7 +1152,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.RegionHealthCheckServicesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = RegionHealthCheckServicesClient(transport=transport) assert client.transport is transport @@ -1159,17 +1163,17 @@ def test_transport_instance(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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_health_check_services_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.RegionHealthCheckServicesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1181,7 +1185,7 @@ def test_region_health_check_services_base_transport(): ) as Transport: Transport.return_value = None transport = transports.RegionHealthCheckServicesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1198,15 +1202,40 @@ def test_region_health_check_services_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_region_health_check_services_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.region_health_check_services.transports.RegionHealthCheckServicesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionHealthCheckServicesTransport( + 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_health_check_services_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_health_check_services.transports.RegionHealthCheckServicesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionHealthCheckServicesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1222,19 +1251,36 @@ def test_region_health_check_services_base_transport_with_credentials_file(): def test_region_health_check_services_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.region_health_check_services.transports.RegionHealthCheckServicesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionHealthCheckServicesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_region_health_check_services_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RegionHealthCheckServicesClient() + 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_health_check_services_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) RegionHealthCheckServicesClient() adc.assert_called_once_with( scopes=( @@ -1246,7 +1292,7 @@ def test_region_health_check_services_auth_adc(): def test_region_health_check_services_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1258,7 +1304,7 @@ def test_region_health_check_services_http_transport_client_cert_source_for_mtls def test_region_health_check_services_host_no_port(): client = RegionHealthCheckServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1268,7 +1314,7 @@ def test_region_health_check_services_host_no_port(): def test_region_health_check_services_host_with_port(): client = RegionHealthCheckServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1278,7 +1324,6 @@ def test_region_health_check_services_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1301,7 +1346,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = RegionHealthCheckServicesClient.common_folder_path(folder) assert expected == actual @@ -1320,7 +1364,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = RegionHealthCheckServicesClient.common_organization_path(organization) assert expected == actual @@ -1339,7 +1382,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = RegionHealthCheckServicesClient.common_project_path(project) assert expected == actual @@ -1359,7 +1401,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1386,7 +1427,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.RegionHealthCheckServicesTransport, "_prep_wrapped_messages" ) as prep: client = RegionHealthCheckServicesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1395,6 +1436,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = RegionHealthCheckServicesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_region_health_checks.py b/tests/unit/gapic/compute_v1/test_region_health_checks.py index 0b034e671..6287e072d 100644 --- a/tests/unit/gapic/compute_v1/test_region_health_checks.py +++ b/tests/unit/gapic/compute_v1/test_region_health_checks.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,33 +13,63 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.compute_v1.services.region_health_checks import ( RegionHealthChecksClient, ) 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, +) 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 +# - 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", +) + +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(): @@ -90,7 +119,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [RegionHealthChecksClient,]) def test_region_health_checks_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -105,7 +134,7 @@ def test_region_health_checks_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [RegionHealthChecksClient,]) def test_region_health_checks_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -146,7 +175,7 @@ def test_region_health_checks_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(RegionHealthChecksClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -394,7 +423,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteRegionHealthCheckRequest ): client = RegionHealthChecksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -429,17 +458,16 @@ def test_delete_rest( 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" @@ -473,7 +501,9 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = RegionHealthChecksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionHealthChecksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -500,16 +530,15 @@ def test_delete_rest_flattened(): 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 "health_check_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = RegionHealthChecksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionHealthChecksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -526,7 +555,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetRegionHealthCheckRequest ): client = RegionHealthChecksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -559,17 +588,16 @@ def test_get_rest( type_=compute.HealthCheck.Type.GRPC, unhealthy_threshold=2046, ) + # Wrap the value into a proper Response obj json_return_value = compute.HealthCheck.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.HealthCheck) assert response.check_interval_sec == 1884 assert response.creation_timestamp == "creation_timestamp_value" @@ -599,7 +627,9 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = RegionHealthChecksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionHealthChecksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -626,16 +656,15 @@ def test_get_rest_flattened(): 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 "health_check_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = RegionHealthChecksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionHealthChecksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -652,7 +681,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertRegionHealthCheckRequest ): client = RegionHealthChecksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -687,17 +716,16 @@ def test_insert_rest( 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" @@ -731,7 +759,9 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = RegionHealthChecksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionHealthChecksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -748,7 +778,6 @@ def test_insert_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. health_check_resource = compute.HealthCheck(check_interval_sec=1884) - client.insert( project="project_value", region="region_value", @@ -760,11 +789,8 @@ def test_insert_rest_flattened(): 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.HealthCheck.to_json( health_check_resource, including_default_value_fields=False, @@ -773,7 +799,9 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = RegionHealthChecksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionHealthChecksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -790,7 +818,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListRegionHealthChecksRequest ): client = RegionHealthChecksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -808,17 +836,16 @@ def test_list_rest( 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.HealthCheckList.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.HealthCheck(check_interval_sec=1884)] @@ -833,7 +860,9 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = RegionHealthChecksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionHealthChecksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -858,14 +887,14 @@ def test_list_rest_flattened(): 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 = RegionHealthChecksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionHealthChecksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -878,12 +907,13 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = RegionHealthChecksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionHealthChecksClient( + 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.HealthCheckList( items=[ @@ -901,7 +931,6 @@ def test_list_pager(): items=[compute.HealthCheck(), compute.HealthCheck(),], ), ) - # Two responses for two calls response = response + response @@ -920,7 +949,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.HealthCheck) for i in results) pages = list(client.list(request={}).pages) @@ -932,7 +960,7 @@ def test_patch_rest( transport: str = "rest", request_type=compute.PatchRegionHealthCheckRequest ): client = RegionHealthChecksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -967,17 +995,16 @@ def test_patch_rest( 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" @@ -1011,7 +1038,9 @@ def test_patch_rest_from_dict(): def test_patch_rest_flattened(): - client = RegionHealthChecksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionHealthChecksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1028,7 +1057,6 @@ def test_patch_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. health_check_resource = compute.HealthCheck(check_interval_sec=1884) - client.patch( project="project_value", region="region_value", @@ -1041,13 +1069,9 @@ def test_patch_rest_flattened(): 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 "health_check_value" in http_call[1] + str(body) - assert compute.HealthCheck.to_json( health_check_resource, including_default_value_fields=False, @@ -1056,7 +1080,9 @@ def test_patch_rest_flattened(): def test_patch_rest_flattened_error(): - client = RegionHealthChecksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionHealthChecksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1074,7 +1100,7 @@ def test_update_rest( transport: str = "rest", request_type=compute.UpdateRegionHealthCheckRequest ): client = RegionHealthChecksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1109,17 +1135,16 @@ def test_update_rest( 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.update(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" @@ -1153,7 +1178,9 @@ def test_update_rest_from_dict(): def test_update_rest_flattened(): - client = RegionHealthChecksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionHealthChecksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1170,7 +1197,6 @@ def test_update_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. health_check_resource = compute.HealthCheck(check_interval_sec=1884) - client.update( project="project_value", region="region_value", @@ -1183,13 +1209,9 @@ def test_update_rest_flattened(): 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 "health_check_value" in http_call[1] + str(body) - assert compute.HealthCheck.to_json( health_check_resource, including_default_value_fields=False, @@ -1198,7 +1220,9 @@ def test_update_rest_flattened(): def test_update_rest_flattened_error(): - client = RegionHealthChecksClient(credentials=credentials.AnonymousCredentials(),) + client = RegionHealthChecksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1215,16 +1239,16 @@ def test_update_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.RegionHealthChecksRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionHealthChecksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.RegionHealthChecksRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionHealthChecksClient( @@ -1234,7 +1258,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.RegionHealthChecksRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionHealthChecksClient( @@ -1245,7 +1269,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.RegionHealthChecksRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = RegionHealthChecksClient(transport=transport) assert client.transport is transport @@ -1256,17 +1280,17 @@ def test_transport_instance(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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_health_checks_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.RegionHealthChecksTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1278,7 +1302,7 @@ def test_region_health_checks_base_transport(): ) as Transport: Transport.return_value = None transport = transports.RegionHealthChecksTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1296,15 +1320,40 @@ def test_region_health_checks_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_region_health_checks_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.region_health_checks.transports.RegionHealthChecksTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionHealthChecksTransport( + 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_health_checks_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_health_checks.transports.RegionHealthChecksTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionHealthChecksTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1320,19 +1369,36 @@ def test_region_health_checks_base_transport_with_credentials_file(): def test_region_health_checks_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.region_health_checks.transports.RegionHealthChecksTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionHealthChecksTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_region_health_checks_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RegionHealthChecksClient() + 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_health_checks_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) RegionHealthChecksClient() adc.assert_called_once_with( scopes=( @@ -1344,7 +1410,7 @@ def test_region_health_checks_auth_adc(): def test_region_health_checks_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1356,7 +1422,7 @@ def test_region_health_checks_http_transport_client_cert_source_for_mtls(): def test_region_health_checks_host_no_port(): client = RegionHealthChecksClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1366,7 +1432,7 @@ def test_region_health_checks_host_no_port(): def test_region_health_checks_host_with_port(): client = RegionHealthChecksClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1376,7 +1442,6 @@ def test_region_health_checks_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1397,7 +1462,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = RegionHealthChecksClient.common_folder_path(folder) assert expected == actual @@ -1416,7 +1480,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = RegionHealthChecksClient.common_organization_path(organization) assert expected == actual @@ -1435,7 +1498,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = RegionHealthChecksClient.common_project_path(project) assert expected == actual @@ -1455,7 +1517,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1482,7 +1543,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.RegionHealthChecksTransport, "_prep_wrapped_messages" ) as prep: client = RegionHealthChecksClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1491,6 +1552,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = RegionHealthChecksClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_region_instance_group_managers.py b/tests/unit/gapic/compute_v1/test_region_instance_group_managers.py index b69df2d45..bf3a0c609 100644 --- a/tests/unit/gapic/compute_v1/test_region_instance_group_managers.py +++ b/tests/unit/gapic/compute_v1/test_region_instance_group_managers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,33 +13,63 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.compute_v1.services.region_instance_group_managers import ( RegionInstanceGroupManagersClient, ) 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, +) 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 +# - 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", +) + +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(): @@ -92,7 +121,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [RegionInstanceGroupManagersClient,]) def test_region_instance_group_managers_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -107,7 +136,7 @@ def test_region_instance_group_managers_client_from_service_account_info(client_ @pytest.mark.parametrize("client_class", [RegionInstanceGroupManagersClient,]) def test_region_instance_group_managers_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -156,7 +185,7 @@ def test_region_instance_group_managers_client_client_options( with mock.patch.object( RegionInstanceGroupManagersClient, "get_transport_class" ) as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -419,7 +448,7 @@ def test_abandon_instances_rest( request_type=compute.AbandonInstancesRegionInstanceGroupManagerRequest, ): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -454,17 +483,16 @@ def test_abandon_instances_rest( 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.abandon_instances(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" @@ -499,7 +527,7 @@ def test_abandon_instances_rest_from_dict(): def test_abandon_instances_rest_flattened(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -519,7 +547,6 @@ def test_abandon_instances_rest_flattened(): region_instance_group_managers_abandon_instances_request_resource = compute.RegionInstanceGroupManagersAbandonInstancesRequest( instances=["instances_value"] ) - client.abandon_instances( project="project_value", region="region_value", @@ -532,13 +559,9 @@ def test_abandon_instances_rest_flattened(): 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 "instance_group_manager_value" in http_call[1] + str(body) - assert compute.RegionInstanceGroupManagersAbandonInstancesRequest.to_json( region_instance_group_managers_abandon_instances_request_resource, including_default_value_fields=False, @@ -548,7 +571,7 @@ def test_abandon_instances_rest_flattened(): def test_abandon_instances_rest_flattened_error(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -570,7 +593,7 @@ def test_apply_updates_to_instances_rest( request_type=compute.ApplyUpdatesToInstancesRegionInstanceGroupManagerRequest, ): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -605,17 +628,16 @@ def test_apply_updates_to_instances_rest( 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.apply_updates_to_instances(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" @@ -650,7 +672,7 @@ def test_apply_updates_to_instances_rest_from_dict(): def test_apply_updates_to_instances_rest_flattened(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -670,7 +692,6 @@ def test_apply_updates_to_instances_rest_flattened(): region_instance_group_managers_apply_updates_request_resource = compute.RegionInstanceGroupManagersApplyUpdatesRequest( all_instances=True ) - client.apply_updates_to_instances( project="project_value", region="region_value", @@ -683,13 +704,9 @@ def test_apply_updates_to_instances_rest_flattened(): 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 "instance_group_manager_value" in http_call[1] + str(body) - assert compute.RegionInstanceGroupManagersApplyUpdatesRequest.to_json( region_instance_group_managers_apply_updates_request_resource, including_default_value_fields=False, @@ -699,7 +716,7 @@ def test_apply_updates_to_instances_rest_flattened(): def test_apply_updates_to_instances_rest_flattened_error(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -721,7 +738,7 @@ def test_create_instances_rest( request_type=compute.CreateInstancesRegionInstanceGroupManagerRequest, ): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -756,17 +773,16 @@ def test_create_instances_rest( 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.create_instances(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" @@ -801,7 +817,7 @@ def test_create_instances_rest_from_dict(): def test_create_instances_rest_flattened(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -821,7 +837,6 @@ def test_create_instances_rest_flattened(): region_instance_group_managers_create_instances_request_resource = compute.RegionInstanceGroupManagersCreateInstancesRequest( instances=[compute.PerInstanceConfig(fingerprint="fingerprint_value")] ) - client.create_instances( project="project_value", region="region_value", @@ -834,13 +849,9 @@ def test_create_instances_rest_flattened(): 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 "instance_group_manager_value" in http_call[1] + str(body) - assert compute.RegionInstanceGroupManagersCreateInstancesRequest.to_json( region_instance_group_managers_create_instances_request_resource, including_default_value_fields=False, @@ -850,7 +861,7 @@ def test_create_instances_rest_flattened(): def test_create_instances_rest_flattened_error(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -872,7 +883,7 @@ def test_delete_rest( request_type=compute.DeleteRegionInstanceGroupManagerRequest, ): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -907,17 +918,16 @@ def test_delete_rest( 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" @@ -952,7 +962,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -980,17 +990,14 @@ def test_delete_rest_flattened(): 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 "instance_group_manager_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1009,7 +1016,7 @@ def test_delete_instances_rest( request_type=compute.DeleteInstancesRegionInstanceGroupManagerRequest, ): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1044,17 +1051,16 @@ def test_delete_instances_rest( 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_instances(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" @@ -1089,7 +1095,7 @@ def test_delete_instances_rest_from_dict(): def test_delete_instances_rest_flattened(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1109,7 +1115,6 @@ def test_delete_instances_rest_flattened(): region_instance_group_managers_delete_instances_request_resource = compute.RegionInstanceGroupManagersDeleteInstancesRequest( instances=["instances_value"] ) - client.delete_instances( project="project_value", region="region_value", @@ -1122,13 +1127,9 @@ def test_delete_instances_rest_flattened(): 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 "instance_group_manager_value" in http_call[1] + str(body) - assert compute.RegionInstanceGroupManagersDeleteInstancesRequest.to_json( region_instance_group_managers_delete_instances_request_resource, including_default_value_fields=False, @@ -1138,7 +1139,7 @@ def test_delete_instances_rest_flattened(): def test_delete_instances_rest_flattened_error(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1160,7 +1161,7 @@ def test_delete_per_instance_configs_rest( request_type=compute.DeletePerInstanceConfigsRegionInstanceGroupManagerRequest, ): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1195,17 +1196,16 @@ def test_delete_per_instance_configs_rest( 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_per_instance_configs(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" @@ -1240,7 +1240,7 @@ def test_delete_per_instance_configs_rest_from_dict(): def test_delete_per_instance_configs_rest_flattened(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1260,7 +1260,6 @@ def test_delete_per_instance_configs_rest_flattened(): region_instance_group_manager_delete_instance_config_req_resource = compute.RegionInstanceGroupManagerDeleteInstanceConfigReq( names=["names_value"] ) - client.delete_per_instance_configs( project="project_value", region="region_value", @@ -1273,13 +1272,9 @@ def test_delete_per_instance_configs_rest_flattened(): 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 "instance_group_manager_value" in http_call[1] + str(body) - assert compute.RegionInstanceGroupManagerDeleteInstanceConfigReq.to_json( region_instance_group_manager_delete_instance_config_req_resource, including_default_value_fields=False, @@ -1289,7 +1284,7 @@ def test_delete_per_instance_configs_rest_flattened(): def test_delete_per_instance_configs_rest_flattened_error(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1310,7 +1305,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetRegionInstanceGroupManagerRequest ): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1364,17 +1359,16 @@ def test_get_rest( ], zone="zone_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.InstanceGroupManager.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.InstanceGroupManager) assert response.auto_healing_policies == [ compute.InstanceGroupManagerAutoHealingPolicy(health_check="health_check_value") @@ -1426,7 +1420,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1454,17 +1448,14 @@ def test_get_rest_flattened(): 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 "instance_group_manager_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1483,7 +1474,7 @@ def test_insert_rest( request_type=compute.InsertRegionInstanceGroupManagerRequest, ): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1518,17 +1509,16 @@ def test_insert_rest( 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" @@ -1563,7 +1553,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1587,7 +1577,6 @@ def test_insert_rest_flattened(): ) ] ) - client.insert( project="project_value", region="region_value", @@ -1599,11 +1588,8 @@ def test_insert_rest_flattened(): 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.InstanceGroupManager.to_json( instance_group_manager_resource, including_default_value_fields=False, @@ -1613,7 +1599,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1637,7 +1623,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListRegionInstanceGroupManagersRequest ): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1663,17 +1649,16 @@ def test_list_rest( 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.RegionInstanceGroupManagerList.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 == [ @@ -1697,7 +1682,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1723,15 +1708,13 @@ def test_list_rest_flattened(): 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 = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1746,13 +1729,12 @@ def test_list_rest_flattened_error(): def test_list_pager(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + 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.RegionInstanceGroupManagerList( items=[ @@ -1770,7 +1752,6 @@ def test_list_pager(): items=[compute.InstanceGroupManager(), compute.InstanceGroupManager(),], ), ) - # Two responses for two calls response = response + response @@ -1791,7 +1772,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.InstanceGroupManager) for i in results) pages = list(client.list(request={}).pages) @@ -1804,7 +1784,7 @@ def test_list_errors_rest( request_type=compute.ListErrorsRegionInstanceGroupManagersRequest, ): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1824,6 +1804,7 @@ def test_list_errors_rest( ], next_page_token="next_page_token_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.RegionInstanceGroupManagersListErrorsResponse.to_json( return_value @@ -1832,11 +1813,9 @@ def test_list_errors_rest( response_value.status_code = 200 response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_errors(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListErrorsPager) assert response.items == [ compute.InstanceManagedByIgmError( @@ -1854,7 +1833,7 @@ def test_list_errors_rest_from_dict(): def test_list_errors_rest_flattened(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1884,17 +1863,14 @@ def test_list_errors_rest_flattened(): 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 "instance_group_manager_value" in http_call[1] + str(body) def test_list_errors_rest_flattened_error(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1910,13 +1886,12 @@ def test_list_errors_rest_flattened_error(): def test_list_errors_pager(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + 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.RegionInstanceGroupManagersListErrorsResponse( items=[ @@ -1939,7 +1914,6 @@ def test_list_errors_pager(): ], ), ) - # Two responses for two calls response = response + response @@ -1961,7 +1935,6 @@ def test_list_errors_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.InstanceManagedByIgmError) for i in results) pages = list(client.list_errors(request={}).pages) @@ -1974,7 +1947,7 @@ def test_list_managed_instances_rest( request_type=compute.ListManagedInstancesRegionInstanceGroupManagersRequest, ): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1992,6 +1965,7 @@ def test_list_managed_instances_rest( ], next_page_token="next_page_token_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.RegionInstanceGroupManagersListInstancesResponse.to_json( return_value @@ -2000,11 +1974,9 @@ def test_list_managed_instances_rest( response_value.status_code = 200 response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_managed_instances(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListManagedInstancesPager) assert response.managed_instances == [ compute.ManagedInstance( @@ -2020,7 +1992,7 @@ def test_list_managed_instances_rest_from_dict(): def test_list_managed_instances_rest_flattened(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -2050,17 +2022,14 @@ def test_list_managed_instances_rest_flattened(): 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 "instance_group_manager_value" in http_call[1] + str(body) def test_list_managed_instances_rest_flattened_error(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2076,13 +2045,12 @@ def test_list_managed_instances_rest_flattened_error(): def test_list_managed_instances_pager(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + 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.RegionInstanceGroupManagersListInstancesResponse( managed_instances=[ @@ -2105,7 +2073,6 @@ def test_list_managed_instances_pager(): ], ), ) - # Two responses for two calls response = response + response @@ -2127,7 +2094,6 @@ def test_list_managed_instances_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.ManagedInstance) for i in results) pages = list(client.list_managed_instances(request={}).pages) @@ -2140,7 +2106,7 @@ def test_list_per_instance_configs_rest( request_type=compute.ListPerInstanceConfigsRegionInstanceGroupManagersRequest, ): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2155,6 +2121,7 @@ def test_list_per_instance_configs_rest( 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.RegionInstanceGroupManagersListInstanceConfigsResp.to_json( return_value @@ -2163,11 +2130,9 @@ def test_list_per_instance_configs_rest( response_value.status_code = 200 response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_per_instance_configs(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPerInstanceConfigsPager) assert response.items == [ compute.PerInstanceConfig(fingerprint="fingerprint_value") @@ -2182,7 +2147,7 @@ def test_list_per_instance_configs_rest_from_dict(): def test_list_per_instance_configs_rest_flattened(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -2212,17 +2177,14 @@ def test_list_per_instance_configs_rest_flattened(): 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 "instance_group_manager_value" in http_call[1] + str(body) def test_list_per_instance_configs_rest_flattened_error(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2238,13 +2200,12 @@ def test_list_per_instance_configs_rest_flattened_error(): def test_list_per_instance_configs_pager(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + 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.RegionInstanceGroupManagersListInstanceConfigsResp( items=[ @@ -2264,7 +2225,6 @@ def test_list_per_instance_configs_pager(): items=[compute.PerInstanceConfig(), compute.PerInstanceConfig(),], ), ) - # Two responses for two calls response = response + response @@ -2286,7 +2246,6 @@ def test_list_per_instance_configs_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.PerInstanceConfig) for i in results) pages = list(client.list_per_instance_configs(request={}).pages) @@ -2298,7 +2257,7 @@ def test_patch_rest( transport: str = "rest", request_type=compute.PatchRegionInstanceGroupManagerRequest ): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2333,17 +2292,16 @@ def test_patch_rest( 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" @@ -2378,7 +2336,7 @@ def test_patch_rest_from_dict(): def test_patch_rest_flattened(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -2402,7 +2360,6 @@ def test_patch_rest_flattened(): ) ] ) - client.patch( project="project_value", region="region_value", @@ -2415,13 +2372,9 @@ def test_patch_rest_flattened(): 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 "instance_group_manager_value" in http_call[1] + str(body) - assert compute.InstanceGroupManager.to_json( instance_group_manager_resource, including_default_value_fields=False, @@ -2431,7 +2384,7 @@ def test_patch_rest_flattened(): def test_patch_rest_flattened_error(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2457,7 +2410,7 @@ def test_patch_per_instance_configs_rest( request_type=compute.PatchPerInstanceConfigsRegionInstanceGroupManagerRequest, ): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2492,17 +2445,16 @@ def test_patch_per_instance_configs_rest( 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_per_instance_configs(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" @@ -2537,7 +2489,7 @@ def test_patch_per_instance_configs_rest_from_dict(): def test_patch_per_instance_configs_rest_flattened(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -2559,7 +2511,6 @@ def test_patch_per_instance_configs_rest_flattened(): compute.PerInstanceConfig(fingerprint="fingerprint_value") ] ) - client.patch_per_instance_configs( project="project_value", region="region_value", @@ -2572,13 +2523,9 @@ def test_patch_per_instance_configs_rest_flattened(): 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 "instance_group_manager_value" in http_call[1] + str(body) - assert compute.RegionInstanceGroupManagerPatchInstanceConfigReq.to_json( region_instance_group_manager_patch_instance_config_req_resource, including_default_value_fields=False, @@ -2588,7 +2535,7 @@ def test_patch_per_instance_configs_rest_flattened(): def test_patch_per_instance_configs_rest_flattened_error(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2612,7 +2559,7 @@ def test_recreate_instances_rest( request_type=compute.RecreateInstancesRegionInstanceGroupManagerRequest, ): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2647,17 +2594,16 @@ def test_recreate_instances_rest( 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.recreate_instances(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" @@ -2692,7 +2638,7 @@ def test_recreate_instances_rest_from_dict(): def test_recreate_instances_rest_flattened(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -2712,7 +2658,6 @@ def test_recreate_instances_rest_flattened(): region_instance_group_managers_recreate_request_resource = compute.RegionInstanceGroupManagersRecreateRequest( instances=["instances_value"] ) - client.recreate_instances( project="project_value", region="region_value", @@ -2725,13 +2670,9 @@ def test_recreate_instances_rest_flattened(): 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 "instance_group_manager_value" in http_call[1] + str(body) - assert compute.RegionInstanceGroupManagersRecreateRequest.to_json( region_instance_group_managers_recreate_request_resource, including_default_value_fields=False, @@ -2741,7 +2682,7 @@ def test_recreate_instances_rest_flattened(): def test_recreate_instances_rest_flattened_error(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2763,7 +2704,7 @@ def test_resize_rest( request_type=compute.ResizeRegionInstanceGroupManagerRequest, ): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2798,17 +2739,16 @@ def test_resize_rest( 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.resize(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" @@ -2843,7 +2783,7 @@ def test_resize_rest_from_dict(): def test_resize_rest_flattened(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -2872,19 +2812,15 @@ def test_resize_rest_flattened(): 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 "instance_group_manager_value" in http_call[1] + str(body) - assert str(443) in http_call[1] + str(body) def test_resize_rest_flattened_error(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2904,7 +2840,7 @@ def test_set_instance_template_rest( request_type=compute.SetInstanceTemplateRegionInstanceGroupManagerRequest, ): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2939,17 +2875,16 @@ def test_set_instance_template_rest( 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_instance_template(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" @@ -2984,7 +2919,7 @@ def test_set_instance_template_rest_from_dict(): def test_set_instance_template_rest_flattened(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -3004,7 +2939,6 @@ def test_set_instance_template_rest_flattened(): region_instance_group_managers_set_template_request_resource = compute.RegionInstanceGroupManagersSetTemplateRequest( instance_template="instance_template_value" ) - client.set_instance_template( project="project_value", region="region_value", @@ -3017,13 +2951,9 @@ def test_set_instance_template_rest_flattened(): 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 "instance_group_manager_value" in http_call[1] + str(body) - assert compute.RegionInstanceGroupManagersSetTemplateRequest.to_json( region_instance_group_managers_set_template_request_resource, including_default_value_fields=False, @@ -3033,7 +2963,7 @@ def test_set_instance_template_rest_flattened(): def test_set_instance_template_rest_flattened_error(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -3055,7 +2985,7 @@ def test_set_target_pools_rest( request_type=compute.SetTargetPoolsRegionInstanceGroupManagerRequest, ): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3090,17 +3020,16 @@ def test_set_target_pools_rest( 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_target_pools(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" @@ -3135,7 +3064,7 @@ def test_set_target_pools_rest_from_dict(): def test_set_target_pools_rest_flattened(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -3155,7 +3084,6 @@ def test_set_target_pools_rest_flattened(): region_instance_group_managers_set_target_pools_request_resource = compute.RegionInstanceGroupManagersSetTargetPoolsRequest( fingerprint="fingerprint_value" ) - client.set_target_pools( project="project_value", region="region_value", @@ -3168,13 +3096,9 @@ def test_set_target_pools_rest_flattened(): 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 "instance_group_manager_value" in http_call[1] + str(body) - assert compute.RegionInstanceGroupManagersSetTargetPoolsRequest.to_json( region_instance_group_managers_set_target_pools_request_resource, including_default_value_fields=False, @@ -3184,7 +3108,7 @@ def test_set_target_pools_rest_flattened(): def test_set_target_pools_rest_flattened_error(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -3206,7 +3130,7 @@ def test_update_per_instance_configs_rest( request_type=compute.UpdatePerInstanceConfigsRegionInstanceGroupManagerRequest, ): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3241,17 +3165,16 @@ def test_update_per_instance_configs_rest( 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.update_per_instance_configs(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" @@ -3286,7 +3209,7 @@ def test_update_per_instance_configs_rest_from_dict(): def test_update_per_instance_configs_rest_flattened(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -3308,7 +3231,6 @@ def test_update_per_instance_configs_rest_flattened(): compute.PerInstanceConfig(fingerprint="fingerprint_value") ] ) - client.update_per_instance_configs( project="project_value", region="region_value", @@ -3321,13 +3243,9 @@ def test_update_per_instance_configs_rest_flattened(): 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 "instance_group_manager_value" in http_call[1] + str(body) - assert compute.RegionInstanceGroupManagerUpdateInstanceConfigReq.to_json( region_instance_group_manager_update_instance_config_req_resource, including_default_value_fields=False, @@ -3337,7 +3255,7 @@ def test_update_per_instance_configs_rest_flattened(): def test_update_per_instance_configs_rest_flattened_error(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -3359,16 +3277,16 @@ def test_update_per_instance_configs_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.RegionInstanceGroupManagersRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.RegionInstanceGroupManagersRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionInstanceGroupManagersClient( @@ -3378,7 +3296,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.RegionInstanceGroupManagersRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionInstanceGroupManagersClient( @@ -3389,7 +3307,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.RegionInstanceGroupManagersRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = RegionInstanceGroupManagersClient(transport=transport) assert client.transport is transport @@ -3400,17 +3318,17 @@ def test_transport_instance(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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_instance_group_managers_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.RegionInstanceGroupManagersTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -3422,7 +3340,7 @@ def test_region_instance_group_managers_base_transport(): ) as Transport: Transport.return_value = None transport = transports.RegionInstanceGroupManagersTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -3453,15 +3371,40 @@ def test_region_instance_group_managers_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_region_instance_group_managers_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.region_instance_group_managers.transports.RegionInstanceGroupManagersTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionInstanceGroupManagersTransport( + 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_instance_group_managers_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_instance_group_managers.transports.RegionInstanceGroupManagersTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionInstanceGroupManagersTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -3477,19 +3420,36 @@ def test_region_instance_group_managers_base_transport_with_credentials_file(): def test_region_instance_group_managers_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.region_instance_group_managers.transports.RegionInstanceGroupManagersTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionInstanceGroupManagersTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_region_instance_group_managers_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RegionInstanceGroupManagersClient() + 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_instance_group_managers_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) RegionInstanceGroupManagersClient() adc.assert_called_once_with( scopes=( @@ -3501,7 +3461,7 @@ def test_region_instance_group_managers_auth_adc(): def test_region_instance_group_managers_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -3513,7 +3473,7 @@ def test_region_instance_group_managers_http_transport_client_cert_source_for_mt def test_region_instance_group_managers_host_no_port(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -3523,7 +3483,7 @@ def test_region_instance_group_managers_host_no_port(): def test_region_instance_group_managers_host_with_port(): client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -3533,7 +3493,6 @@ def test_region_instance_group_managers_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -3556,7 +3515,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = RegionInstanceGroupManagersClient.common_folder_path(folder) assert expected == actual @@ -3575,7 +3533,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = RegionInstanceGroupManagersClient.common_organization_path(organization) assert expected == actual @@ -3594,7 +3551,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = RegionInstanceGroupManagersClient.common_project_path(project) assert expected == actual @@ -3614,7 +3570,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -3641,7 +3596,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.RegionInstanceGroupManagersTransport, "_prep_wrapped_messages" ) as prep: client = RegionInstanceGroupManagersClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -3650,6 +3605,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = RegionInstanceGroupManagersClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_region_instance_groups.py b/tests/unit/gapic/compute_v1/test_region_instance_groups.py index db2cb7dc9..855764bf3 100644 --- a/tests/unit/gapic/compute_v1/test_region_instance_groups.py +++ b/tests/unit/gapic/compute_v1/test_region_instance_groups.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,33 +13,63 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.compute_v1.services.region_instance_groups import ( RegionInstanceGroupsClient, ) 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, +) 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 +# - 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", +) + +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(): @@ -90,7 +119,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [RegionInstanceGroupsClient,]) def test_region_instance_groups_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -105,7 +134,7 @@ def test_region_instance_groups_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [RegionInstanceGroupsClient,]) def test_region_instance_groups_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -152,7 +181,7 @@ def test_region_instance_groups_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(RegionInstanceGroupsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -412,7 +441,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetRegionInstanceGroupRequest ): client = RegionInstanceGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -437,17 +466,16 @@ def test_get_rest( subnetwork="subnetwork_value", zone="zone_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.InstanceGroup.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.InstanceGroup) assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" @@ -469,7 +497,9 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = RegionInstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionInstanceGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -496,16 +526,15 @@ def test_get_rest_flattened(): 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 "instance_group_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = RegionInstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionInstanceGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -522,7 +551,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListRegionInstanceGroupsRequest ): client = RegionInstanceGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -542,17 +571,16 @@ def test_list_rest( 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.RegionInstanceGroupList.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 == [ @@ -569,7 +597,9 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = RegionInstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionInstanceGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -594,14 +624,14 @@ def test_list_rest_flattened(): 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 = RegionInstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionInstanceGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -614,12 +644,13 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = RegionInstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionInstanceGroupsClient( + 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.RegionInstanceGroupList( items=[ @@ -637,7 +668,6 @@ def test_list_pager(): items=[compute.InstanceGroup(), compute.InstanceGroup(),], ), ) - # Two responses for two calls response = response + response @@ -656,7 +686,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.InstanceGroup) for i in results) pages = list(client.list(request={}).pages) @@ -669,7 +698,7 @@ def test_list_instances_rest( request_type=compute.ListInstancesRegionInstanceGroupsRequest, ): client = RegionInstanceGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -687,6 +716,7 @@ def test_list_instances_rest( 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.RegionInstanceGroupsListInstances.to_json( return_value @@ -695,11 +725,9 @@ def test_list_instances_rest( response_value.status_code = 200 response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_instances(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInstancesPager) assert response.id == "id_value" assert response.items == [compute.InstanceWithNamedPorts(instance="instance_value")] @@ -714,7 +742,9 @@ def test_list_instances_rest_from_dict(): def test_list_instances_rest_flattened(): - client = RegionInstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionInstanceGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -735,7 +765,6 @@ def test_list_instances_rest_flattened(): region_instance_groups_list_instances_request_resource = compute.RegionInstanceGroupsListInstancesRequest( instance_state=compute.RegionInstanceGroupsListInstancesRequest.InstanceState.ALL ) - client.list_instances( project="project_value", region="region_value", @@ -748,13 +777,9 @@ def test_list_instances_rest_flattened(): 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 "instance_group_value" in http_call[1] + str(body) - assert compute.RegionInstanceGroupsListInstancesRequest.to_json( region_instance_groups_list_instances_request_resource, including_default_value_fields=False, @@ -763,7 +788,9 @@ def test_list_instances_rest_flattened(): def test_list_instances_rest_flattened_error(): - client = RegionInstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionInstanceGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -780,12 +807,13 @@ def test_list_instances_rest_flattened_error(): def test_list_instances_pager(): - client = RegionInstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionInstanceGroupsClient( + 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.RegionInstanceGroupsListInstances( items=[ @@ -806,7 +834,6 @@ def test_list_instances_pager(): ], ), ) - # Two responses for two calls response = response + response @@ -827,7 +854,6 @@ def test_list_instances_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.InstanceWithNamedPorts) for i in results) pages = list(client.list_instances(request={}).pages) @@ -840,7 +866,7 @@ def test_set_named_ports_rest( request_type=compute.SetNamedPortsRegionInstanceGroupRequest, ): client = RegionInstanceGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -875,17 +901,16 @@ def test_set_named_ports_rest( 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_named_ports(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" @@ -919,7 +944,9 @@ def test_set_named_ports_rest_from_dict(): def test_set_named_ports_rest_flattened(): - client = RegionInstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionInstanceGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -938,7 +965,6 @@ def test_set_named_ports_rest_flattened(): region_instance_groups_set_named_ports_request_resource = compute.RegionInstanceGroupsSetNamedPortsRequest( fingerprint="fingerprint_value" ) - client.set_named_ports( project="project_value", region="region_value", @@ -951,13 +977,9 @@ def test_set_named_ports_rest_flattened(): 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 "instance_group_value" in http_call[1] + str(body) - assert compute.RegionInstanceGroupsSetNamedPortsRequest.to_json( region_instance_groups_set_named_ports_request_resource, including_default_value_fields=False, @@ -966,7 +988,9 @@ def test_set_named_ports_rest_flattened(): def test_set_named_ports_rest_flattened_error(): - client = RegionInstanceGroupsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionInstanceGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -985,16 +1009,16 @@ def test_set_named_ports_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.RegionInstanceGroupsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionInstanceGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.RegionInstanceGroupsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionInstanceGroupsClient( @@ -1004,7 +1028,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.RegionInstanceGroupsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionInstanceGroupsClient( @@ -1015,7 +1039,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.RegionInstanceGroupsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = RegionInstanceGroupsClient(transport=transport) assert client.transport is transport @@ -1026,17 +1050,17 @@ def test_transport_instance(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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_instance_groups_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.RegionInstanceGroupsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1048,7 +1072,7 @@ def test_region_instance_groups_base_transport(): ) as Transport: Transport.return_value = None transport = transports.RegionInstanceGroupsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1064,15 +1088,40 @@ def test_region_instance_groups_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_region_instance_groups_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.region_instance_groups.transports.RegionInstanceGroupsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionInstanceGroupsTransport( + 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_instance_groups_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_instance_groups.transports.RegionInstanceGroupsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionInstanceGroupsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1088,19 +1137,36 @@ def test_region_instance_groups_base_transport_with_credentials_file(): def test_region_instance_groups_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.region_instance_groups.transports.RegionInstanceGroupsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionInstanceGroupsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_region_instance_groups_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RegionInstanceGroupsClient() + 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_instance_groups_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) RegionInstanceGroupsClient() adc.assert_called_once_with( scopes=( @@ -1112,7 +1178,7 @@ def test_region_instance_groups_auth_adc(): def test_region_instance_groups_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1124,7 +1190,7 @@ def test_region_instance_groups_http_transport_client_cert_source_for_mtls(): def test_region_instance_groups_host_no_port(): client = RegionInstanceGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1134,7 +1200,7 @@ def test_region_instance_groups_host_no_port(): def test_region_instance_groups_host_with_port(): client = RegionInstanceGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1144,7 +1210,6 @@ def test_region_instance_groups_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1165,7 +1230,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = RegionInstanceGroupsClient.common_folder_path(folder) assert expected == actual @@ -1184,7 +1248,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = RegionInstanceGroupsClient.common_organization_path(organization) assert expected == actual @@ -1203,7 +1266,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = RegionInstanceGroupsClient.common_project_path(project) assert expected == actual @@ -1223,7 +1285,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1250,7 +1311,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.RegionInstanceGroupsTransport, "_prep_wrapped_messages" ) as prep: client = RegionInstanceGroupsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1259,6 +1320,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = RegionInstanceGroupsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_region_network_endpoint_groups.py b/tests/unit/gapic/compute_v1/test_region_network_endpoint_groups.py index cf6909987..5afc043ad 100644 --- a/tests/unit/gapic/compute_v1/test_region_network_endpoint_groups.py +++ b/tests/unit/gapic/compute_v1/test_region_network_endpoint_groups.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,33 +13,63 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.compute_v1.services.region_network_endpoint_groups import ( RegionNetworkEndpointGroupsClient, ) 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, +) 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 +# - 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", +) + +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(): @@ -92,7 +121,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [RegionNetworkEndpointGroupsClient,]) def test_region_network_endpoint_groups_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -107,7 +136,7 @@ def test_region_network_endpoint_groups_client_from_service_account_info(client_ @pytest.mark.parametrize("client_class", [RegionNetworkEndpointGroupsClient,]) def test_region_network_endpoint_groups_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -156,7 +185,7 @@ def test_region_network_endpoint_groups_client_client_options( with mock.patch.object( RegionNetworkEndpointGroupsClient, "get_transport_class" ) as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -419,7 +448,7 @@ def test_delete_rest( request_type=compute.DeleteRegionNetworkEndpointGroupRequest, ): client = RegionNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -454,17 +483,16 @@ def test_delete_rest( 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" @@ -499,7 +527,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): client = RegionNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -527,17 +555,14 @@ def test_delete_rest_flattened(): 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 "network_endpoint_group_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): client = RegionNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -555,7 +580,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetRegionNetworkEndpointGroupRequest ): client = RegionNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -586,17 +611,16 @@ def test_get_rest( subnetwork="subnetwork_value", zone="zone_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.NetworkEndpointGroup.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.NetworkEndpointGroup) assert response.annotations == {"key_value": "value_value"} assert response.app_engine == compute.NetworkEndpointGroupAppEngine( @@ -632,7 +656,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): client = RegionNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -660,17 +684,14 @@ def test_get_rest_flattened(): 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 "network_endpoint_group_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): client = RegionNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -689,7 +710,7 @@ def test_insert_rest( request_type=compute.InsertRegionNetworkEndpointGroupRequest, ): client = RegionNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -724,17 +745,16 @@ def test_insert_rest( 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" @@ -769,7 +789,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): client = RegionNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -789,7 +809,6 @@ def test_insert_rest_flattened(): network_endpoint_group_resource = compute.NetworkEndpointGroup( annotations={"key_value": "value_value"} ) - client.insert( project="project_value", region="region_value", @@ -801,11 +820,8 @@ def test_insert_rest_flattened(): 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.NetworkEndpointGroup.to_json( network_endpoint_group_resource, including_default_value_fields=False, @@ -815,7 +831,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): client = RegionNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -835,7 +851,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListRegionNetworkEndpointGroupsRequest ): client = RegionNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -855,17 +871,16 @@ def test_list_rest( 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.NetworkEndpointGroupList.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 == [ @@ -883,7 +898,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): client = RegionNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -909,15 +924,13 @@ def test_list_rest_flattened(): 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 = RegionNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -932,13 +945,12 @@ def test_list_rest_flattened_error(): def test_list_pager(): client = RegionNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + 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.NetworkEndpointGroupList( items=[ @@ -956,7 +968,6 @@ def test_list_pager(): items=[compute.NetworkEndpointGroup(), compute.NetworkEndpointGroup(),], ), ) - # Two responses for two calls response = response + response @@ -975,7 +986,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.NetworkEndpointGroup) for i in results) pages = list(client.list(request={}).pages) @@ -986,16 +996,16 @@ def test_list_pager(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.RegionNetworkEndpointGroupsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.RegionNetworkEndpointGroupsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionNetworkEndpointGroupsClient( @@ -1005,7 +1015,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.RegionNetworkEndpointGroupsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionNetworkEndpointGroupsClient( @@ -1016,7 +1026,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.RegionNetworkEndpointGroupsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = RegionNetworkEndpointGroupsClient(transport=transport) assert client.transport is transport @@ -1027,17 +1037,17 @@ def test_transport_instance(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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_network_endpoint_groups_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.RegionNetworkEndpointGroupsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1049,7 +1059,7 @@ def test_region_network_endpoint_groups_base_transport(): ) as Transport: Transport.return_value = None transport = transports.RegionNetworkEndpointGroupsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1065,15 +1075,40 @@ def test_region_network_endpoint_groups_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_region_network_endpoint_groups_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.region_network_endpoint_groups.transports.RegionNetworkEndpointGroupsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionNetworkEndpointGroupsTransport( + 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_network_endpoint_groups_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_network_endpoint_groups.transports.RegionNetworkEndpointGroupsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionNetworkEndpointGroupsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1089,19 +1124,36 @@ def test_region_network_endpoint_groups_base_transport_with_credentials_file(): def test_region_network_endpoint_groups_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.region_network_endpoint_groups.transports.RegionNetworkEndpointGroupsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionNetworkEndpointGroupsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_region_network_endpoint_groups_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RegionNetworkEndpointGroupsClient() + 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_network_endpoint_groups_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) RegionNetworkEndpointGroupsClient() adc.assert_called_once_with( scopes=( @@ -1113,7 +1165,7 @@ def test_region_network_endpoint_groups_auth_adc(): def test_region_network_endpoint_groups_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1125,7 +1177,7 @@ def test_region_network_endpoint_groups_http_transport_client_cert_source_for_mt def test_region_network_endpoint_groups_host_no_port(): client = RegionNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1135,7 +1187,7 @@ def test_region_network_endpoint_groups_host_no_port(): def test_region_network_endpoint_groups_host_with_port(): client = RegionNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1145,7 +1197,6 @@ def test_region_network_endpoint_groups_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1168,7 +1219,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = RegionNetworkEndpointGroupsClient.common_folder_path(folder) assert expected == actual @@ -1187,7 +1237,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = RegionNetworkEndpointGroupsClient.common_organization_path(organization) assert expected == actual @@ -1206,7 +1255,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = RegionNetworkEndpointGroupsClient.common_project_path(project) assert expected == actual @@ -1226,7 +1274,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1253,7 +1300,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.RegionNetworkEndpointGroupsTransport, "_prep_wrapped_messages" ) as prep: client = RegionNetworkEndpointGroupsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1262,6 +1309,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = RegionNetworkEndpointGroupsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_region_notification_endpoints.py b/tests/unit/gapic/compute_v1/test_region_notification_endpoints.py index 009a6c7bd..ab5f0e2b4 100644 --- a/tests/unit/gapic/compute_v1/test_region_notification_endpoints.py +++ b/tests/unit/gapic/compute_v1/test_region_notification_endpoints.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,33 +13,63 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.compute_v1.services.region_notification_endpoints import ( RegionNotificationEndpointsClient, ) 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, +) 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 +# - 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", +) + +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(): @@ -92,7 +121,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [RegionNotificationEndpointsClient,]) def test_region_notification_endpoints_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -107,7 +136,7 @@ def test_region_notification_endpoints_client_from_service_account_info(client_c @pytest.mark.parametrize("client_class", [RegionNotificationEndpointsClient,]) def test_region_notification_endpoints_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -156,7 +185,7 @@ def test_region_notification_endpoints_client_client_options( with mock.patch.object( RegionNotificationEndpointsClient, "get_transport_class" ) as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -419,7 +448,7 @@ def test_delete_rest( request_type=compute.DeleteRegionNotificationEndpointRequest, ): client = RegionNotificationEndpointsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -454,17 +483,16 @@ def test_delete_rest( 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" @@ -499,7 +527,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): client = RegionNotificationEndpointsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -527,17 +555,14 @@ def test_delete_rest_flattened(): 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 "notification_endpoint_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): client = RegionNotificationEndpointsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -555,7 +580,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetRegionNotificationEndpointRequest ): client = RegionNotificationEndpointsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -577,17 +602,16 @@ def test_get_rest( region="region_value", self_link="self_link_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.NotificationEndpoint.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.NotificationEndpoint) assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" @@ -607,7 +631,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): client = RegionNotificationEndpointsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -635,17 +659,14 @@ def test_get_rest_flattened(): 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 "notification_endpoint_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): client = RegionNotificationEndpointsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -664,7 +685,7 @@ def test_insert_rest( request_type=compute.InsertRegionNotificationEndpointRequest, ): client = RegionNotificationEndpointsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -699,17 +720,16 @@ def test_insert_rest( 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" @@ -744,7 +764,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): client = RegionNotificationEndpointsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -764,7 +784,6 @@ def test_insert_rest_flattened(): notification_endpoint_resource = compute.NotificationEndpoint( creation_timestamp="creation_timestamp_value" ) - client.insert( project="project_value", region="region_value", @@ -776,11 +795,8 @@ def test_insert_rest_flattened(): 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.NotificationEndpoint.to_json( notification_endpoint_resource, including_default_value_fields=False, @@ -790,7 +806,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): client = RegionNotificationEndpointsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -810,7 +826,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListRegionNotificationEndpointsRequest ): client = RegionNotificationEndpointsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -832,17 +848,16 @@ def test_list_rest( 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.NotificationEndpointList.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 == [ @@ -860,7 +875,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): client = RegionNotificationEndpointsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -886,15 +901,13 @@ def test_list_rest_flattened(): 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 = RegionNotificationEndpointsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -909,13 +922,12 @@ def test_list_rest_flattened_error(): def test_list_pager(): client = RegionNotificationEndpointsClient( - credentials=credentials.AnonymousCredentials(), + 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.NotificationEndpointList( items=[ @@ -933,7 +945,6 @@ def test_list_pager(): items=[compute.NotificationEndpoint(), compute.NotificationEndpoint(),], ), ) - # Two responses for two calls response = response + response @@ -952,7 +963,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.NotificationEndpoint) for i in results) pages = list(client.list(request={}).pages) @@ -963,16 +973,16 @@ def test_list_pager(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.RegionNotificationEndpointsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionNotificationEndpointsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.RegionNotificationEndpointsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionNotificationEndpointsClient( @@ -982,7 +992,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.RegionNotificationEndpointsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionNotificationEndpointsClient( @@ -993,7 +1003,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.RegionNotificationEndpointsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = RegionNotificationEndpointsClient(transport=transport) assert client.transport is transport @@ -1004,17 +1014,17 @@ def test_transport_instance(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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_notification_endpoints_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.RegionNotificationEndpointsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1026,7 +1036,7 @@ def test_region_notification_endpoints_base_transport(): ) as Transport: Transport.return_value = None transport = transports.RegionNotificationEndpointsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1042,15 +1052,40 @@ def test_region_notification_endpoints_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_region_notification_endpoints_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.region_notification_endpoints.transports.RegionNotificationEndpointsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionNotificationEndpointsTransport( + 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_notification_endpoints_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_notification_endpoints.transports.RegionNotificationEndpointsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionNotificationEndpointsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1066,19 +1101,36 @@ def test_region_notification_endpoints_base_transport_with_credentials_file(): def test_region_notification_endpoints_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.region_notification_endpoints.transports.RegionNotificationEndpointsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionNotificationEndpointsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_region_notification_endpoints_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RegionNotificationEndpointsClient() + 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_notification_endpoints_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) RegionNotificationEndpointsClient() adc.assert_called_once_with( scopes=( @@ -1090,7 +1142,7 @@ def test_region_notification_endpoints_auth_adc(): def test_region_notification_endpoints_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1102,7 +1154,7 @@ def test_region_notification_endpoints_http_transport_client_cert_source_for_mtl def test_region_notification_endpoints_host_no_port(): client = RegionNotificationEndpointsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1112,7 +1164,7 @@ def test_region_notification_endpoints_host_no_port(): def test_region_notification_endpoints_host_with_port(): client = RegionNotificationEndpointsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1122,7 +1174,6 @@ def test_region_notification_endpoints_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1145,7 +1196,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = RegionNotificationEndpointsClient.common_folder_path(folder) assert expected == actual @@ -1164,7 +1214,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = RegionNotificationEndpointsClient.common_organization_path(organization) assert expected == actual @@ -1183,7 +1232,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = RegionNotificationEndpointsClient.common_project_path(project) assert expected == actual @@ -1203,7 +1251,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1230,7 +1277,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.RegionNotificationEndpointsTransport, "_prep_wrapped_messages" ) as prep: client = RegionNotificationEndpointsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1239,6 +1286,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = RegionNotificationEndpointsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_region_operations.py b/tests/unit/gapic/compute_v1/test_region_operations.py index 30d83bbe8..d4dbfe848 100644 --- a/tests/unit/gapic/compute_v1/test_region_operations.py +++ b/tests/unit/gapic/compute_v1/test_region_operations.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -88,7 +117,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [RegionOperationsClient,]) def test_region_operations_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -103,7 +132,7 @@ def test_region_operations_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [RegionOperationsClient,]) def test_region_operations_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -144,7 +173,7 @@ def test_region_operations_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(RegionOperationsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -392,7 +421,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteRegionOperationRequest ): client = RegionOperationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -403,17 +432,16 @@ def test_delete_rest( with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. return_value = compute.DeleteRegionOperationResponse() + # Wrap the value into a proper Response obj json_return_value = compute.DeleteRegionOperationResponse.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.DeleteRegionOperationResponse) @@ -422,7 +450,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = RegionOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionOperationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -447,16 +475,13 @@ def test_delete_rest_flattened(): 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 "operation_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = RegionOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionOperationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -473,7 +498,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetRegionOperationRequest ): client = RegionOperationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -508,17 +533,16 @@ def test_get_rest( 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.get(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" @@ -552,7 +576,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = RegionOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionOperationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -577,16 +601,13 @@ def test_get_rest_flattened(): 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 "operation_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = RegionOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionOperationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -603,7 +624,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListRegionOperationsRequest ): client = RegionOperationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -621,17 +642,16 @@ def test_list_rest( 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.OperationList.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 == [ @@ -648,7 +668,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = RegionOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionOperationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -673,14 +693,12 @@ def test_list_rest_flattened(): 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 = RegionOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionOperationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -693,12 +711,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = RegionOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionOperationsClient(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.OperationList( items=[compute.Operation(), compute.Operation(), compute.Operation(),], @@ -708,7 +725,6 @@ def test_list_pager(): compute.OperationList(items=[compute.Operation(),], next_page_token="ghi",), compute.OperationList(items=[compute.Operation(), compute.Operation(),],), ) - # Two responses for two calls response = response + response @@ -727,7 +743,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.Operation) for i in results) pages = list(client.list(request={}).pages) @@ -739,7 +754,7 @@ def test_wait_rest( transport: str = "rest", request_type=compute.WaitRegionOperationRequest ): client = RegionOperationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -774,17 +789,16 @@ def test_wait_rest( 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.wait(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" @@ -818,7 +832,7 @@ def test_wait_rest_from_dict(): def test_wait_rest_flattened(): - client = RegionOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionOperationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -843,16 +857,13 @@ def test_wait_rest_flattened(): 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 "operation_value" in http_call[1] + str(body) def test_wait_rest_flattened_error(): - client = RegionOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionOperationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -868,16 +879,16 @@ def test_wait_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.RegionOperationsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionOperationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.RegionOperationsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionOperationsClient( @@ -887,7 +898,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.RegionOperationsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionOperationsClient( @@ -898,7 +909,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.RegionOperationsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = RegionOperationsClient(transport=transport) assert client.transport is transport @@ -907,17 +918,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.RegionOperationsRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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_operations_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.RegionOperationsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -929,7 +940,7 @@ def test_region_operations_base_transport(): ) as Transport: Transport.return_value = None transport = transports.RegionOperationsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -945,15 +956,40 @@ def test_region_operations_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_region_operations_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.region_operations.transports.RegionOperationsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionOperationsTransport( + 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_operations_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_operations.transports.RegionOperationsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionOperationsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -969,19 +1005,36 @@ def test_region_operations_base_transport_with_credentials_file(): def test_region_operations_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.region_operations.transports.RegionOperationsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionOperationsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_region_operations_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RegionOperationsClient() + 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_operations_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) RegionOperationsClient() adc.assert_called_once_with( scopes=( @@ -993,7 +1046,7 @@ def test_region_operations_auth_adc(): def test_region_operations_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1005,7 +1058,7 @@ def test_region_operations_http_transport_client_cert_source_for_mtls(): def test_region_operations_host_no_port(): client = RegionOperationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1015,7 +1068,7 @@ def test_region_operations_host_no_port(): def test_region_operations_host_with_port(): client = RegionOperationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1025,7 +1078,6 @@ def test_region_operations_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1046,7 +1098,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = RegionOperationsClient.common_folder_path(folder) assert expected == actual @@ -1065,7 +1116,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = RegionOperationsClient.common_organization_path(organization) assert expected == actual @@ -1084,7 +1134,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = RegionOperationsClient.common_project_path(project) assert expected == actual @@ -1104,7 +1153,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1131,7 +1179,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.RegionOperationsTransport, "_prep_wrapped_messages" ) as prep: client = RegionOperationsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1140,6 +1188,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = RegionOperationsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_region_ssl_certificates.py b/tests/unit/gapic/compute_v1/test_region_ssl_certificates.py index e95440e9d..e2e60bb87 100644 --- a/tests/unit/gapic/compute_v1/test_region_ssl_certificates.py +++ b/tests/unit/gapic/compute_v1/test_region_ssl_certificates.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,33 +13,63 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.compute_v1.services.region_ssl_certificates import ( RegionSslCertificatesClient, ) 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, +) 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 +# - 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", +) + +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(): @@ -90,7 +119,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [RegionSslCertificatesClient,]) def test_region_ssl_certificates_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -105,7 +134,7 @@ def test_region_ssl_certificates_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [RegionSslCertificatesClient,]) def test_region_ssl_certificates_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -152,7 +181,7 @@ def test_region_ssl_certificates_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(RegionSslCertificatesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -412,7 +441,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteRegionSslCertificateRequest ): client = RegionSslCertificatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -447,17 +476,16 @@ def test_delete_rest( 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" @@ -492,7 +520,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): client = RegionSslCertificatesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -520,17 +548,14 @@ def test_delete_rest_flattened(): 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 "ssl_certificate_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): client = RegionSslCertificatesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -548,7 +573,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetRegionSslCertificateRequest ): client = RegionSslCertificatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -578,17 +603,16 @@ def test_get_rest( subject_alternative_names=["subject_alternative_names_value"], type_=compute.SslCertificate.Type.MANAGED, ) + # Wrap the value into a proper Response obj json_return_value = compute.SslCertificate.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.SslCertificate) assert response.certificate == "certificate_value" assert response.creation_timestamp == "creation_timestamp_value" @@ -616,7 +640,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): client = RegionSslCertificatesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -644,17 +668,14 @@ def test_get_rest_flattened(): 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 "ssl_certificate_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): client = RegionSslCertificatesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -672,7 +693,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertRegionSslCertificateRequest ): client = RegionSslCertificatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -707,17 +728,16 @@ def test_insert_rest( 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" @@ -752,7 +772,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): client = RegionSslCertificatesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -772,7 +792,6 @@ def test_insert_rest_flattened(): ssl_certificate_resource = compute.SslCertificate( certificate="certificate_value" ) - client.insert( project="project_value", region="region_value", @@ -784,11 +803,8 @@ def test_insert_rest_flattened(): 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.SslCertificate.to_json( ssl_certificate_resource, including_default_value_fields=False, @@ -798,7 +814,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): client = RegionSslCertificatesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -818,7 +834,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListRegionSslCertificatesRequest ): client = RegionSslCertificatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -836,17 +852,16 @@ def test_list_rest( 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.SslCertificateList.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.SslCertificate(certificate="certificate_value")] @@ -862,7 +877,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): client = RegionSslCertificatesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -888,15 +903,13 @@ def test_list_rest_flattened(): 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 = RegionSslCertificatesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -911,13 +924,12 @@ def test_list_rest_flattened_error(): def test_list_pager(): client = RegionSslCertificatesClient( - credentials=credentials.AnonymousCredentials(), + 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.SslCertificateList( items=[ @@ -935,7 +947,6 @@ def test_list_pager(): items=[compute.SslCertificate(), compute.SslCertificate(),], ), ) - # Two responses for two calls response = response + response @@ -954,7 +965,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.SslCertificate) for i in results) pages = list(client.list(request={}).pages) @@ -965,16 +975,16 @@ def test_list_pager(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.RegionSslCertificatesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionSslCertificatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.RegionSslCertificatesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionSslCertificatesClient( @@ -984,7 +994,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.RegionSslCertificatesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionSslCertificatesClient( @@ -995,7 +1005,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.RegionSslCertificatesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = RegionSslCertificatesClient(transport=transport) assert client.transport is transport @@ -1006,17 +1016,17 @@ def test_transport_instance(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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_ssl_certificates_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.RegionSslCertificatesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1028,7 +1038,7 @@ def test_region_ssl_certificates_base_transport(): ) as Transport: Transport.return_value = None transport = transports.RegionSslCertificatesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1044,15 +1054,40 @@ def test_region_ssl_certificates_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_region_ssl_certificates_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.region_ssl_certificates.transports.RegionSslCertificatesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionSslCertificatesTransport( + 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_ssl_certificates_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_ssl_certificates.transports.RegionSslCertificatesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionSslCertificatesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1068,19 +1103,36 @@ def test_region_ssl_certificates_base_transport_with_credentials_file(): def test_region_ssl_certificates_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.region_ssl_certificates.transports.RegionSslCertificatesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionSslCertificatesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_region_ssl_certificates_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RegionSslCertificatesClient() + 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_ssl_certificates_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) RegionSslCertificatesClient() adc.assert_called_once_with( scopes=( @@ -1092,7 +1144,7 @@ def test_region_ssl_certificates_auth_adc(): def test_region_ssl_certificates_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1104,7 +1156,7 @@ def test_region_ssl_certificates_http_transport_client_cert_source_for_mtls(): def test_region_ssl_certificates_host_no_port(): client = RegionSslCertificatesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1114,7 +1166,7 @@ def test_region_ssl_certificates_host_no_port(): def test_region_ssl_certificates_host_with_port(): client = RegionSslCertificatesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1124,7 +1176,6 @@ def test_region_ssl_certificates_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1145,7 +1196,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = RegionSslCertificatesClient.common_folder_path(folder) assert expected == actual @@ -1164,7 +1214,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = RegionSslCertificatesClient.common_organization_path(organization) assert expected == actual @@ -1183,7 +1232,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = RegionSslCertificatesClient.common_project_path(project) assert expected == actual @@ -1203,7 +1251,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1230,7 +1277,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.RegionSslCertificatesTransport, "_prep_wrapped_messages" ) as prep: client = RegionSslCertificatesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1239,6 +1286,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = RegionSslCertificatesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_region_target_http_proxies.py b/tests/unit/gapic/compute_v1/test_region_target_http_proxies.py index 650acbc9c..146189aec 100644 --- a/tests/unit/gapic/compute_v1/test_region_target_http_proxies.py +++ b/tests/unit/gapic/compute_v1/test_region_target_http_proxies.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,33 +13,63 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.compute_v1.services.region_target_http_proxies import ( RegionTargetHttpProxiesClient, ) 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, +) 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 +# - 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", +) + +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(): @@ -90,7 +119,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [RegionTargetHttpProxiesClient,]) def test_region_target_http_proxies_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -105,7 +134,7 @@ def test_region_target_http_proxies_client_from_service_account_info(client_clas @pytest.mark.parametrize("client_class", [RegionTargetHttpProxiesClient,]) def test_region_target_http_proxies_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -152,7 +181,7 @@ def test_region_target_http_proxies_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(RegionTargetHttpProxiesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -412,7 +441,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteRegionTargetHttpProxyRequest ): client = RegionTargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -447,17 +476,16 @@ def test_delete_rest( 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" @@ -492,7 +520,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): client = RegionTargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -520,17 +548,14 @@ def test_delete_rest_flattened(): 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 "target_http_proxy_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): client = RegionTargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -548,7 +573,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetRegionTargetHttpProxyRequest ): client = RegionTargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -570,17 +595,16 @@ def test_get_rest( self_link="self_link_value", url_map="url_map_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.TargetHttpProxy.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.TargetHttpProxy) assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" @@ -588,7 +612,6 @@ 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.region == "region_value" assert response.self_link == "self_link_value" @@ -601,7 +624,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): client = RegionTargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -629,17 +652,14 @@ def test_get_rest_flattened(): 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 "target_http_proxy_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): client = RegionTargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -657,7 +677,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertRegionTargetHttpProxyRequest ): client = RegionTargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -692,17 +712,16 @@ def test_insert_rest( 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" @@ -737,7 +756,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): client = RegionTargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -757,7 +776,6 @@ def test_insert_rest_flattened(): target_http_proxy_resource = compute.TargetHttpProxy( creation_timestamp="creation_timestamp_value" ) - client.insert( project="project_value", region="region_value", @@ -769,11 +787,8 @@ def test_insert_rest_flattened(): 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.TargetHttpProxy.to_json( target_http_proxy_resource, including_default_value_fields=False, @@ -783,7 +798,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): client = RegionTargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -803,7 +818,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListRegionTargetHttpProxiesRequest ): client = RegionTargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -823,17 +838,16 @@ def test_list_rest( 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.TargetHttpProxyList.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 == [ @@ -851,7 +865,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): client = RegionTargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -877,15 +891,13 @@ def test_list_rest_flattened(): 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 = RegionTargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -900,13 +912,12 @@ def test_list_rest_flattened_error(): def test_list_pager(): client = RegionTargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), + 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.TargetHttpProxyList( items=[ @@ -924,7 +935,6 @@ def test_list_pager(): items=[compute.TargetHttpProxy(), compute.TargetHttpProxy(),], ), ) - # Two responses for two calls response = response + response @@ -943,7 +953,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.TargetHttpProxy) for i in results) pages = list(client.list(request={}).pages) @@ -955,7 +964,7 @@ def test_set_url_map_rest( transport: str = "rest", request_type=compute.SetUrlMapRegionTargetHttpProxyRequest ): client = RegionTargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -990,17 +999,16 @@ def test_set_url_map_rest( 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_url_map(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" @@ -1035,7 +1043,7 @@ def test_set_url_map_rest_from_dict(): def test_set_url_map_rest_flattened(): client = RegionTargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1053,7 +1061,6 @@ def test_set_url_map_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. url_map_reference_resource = compute.UrlMapReference(url_map="url_map_value") - client.set_url_map( project="project_value", region="region_value", @@ -1066,13 +1073,9 @@ def test_set_url_map_rest_flattened(): 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 "target_http_proxy_value" in http_call[1] + str(body) - assert compute.UrlMapReference.to_json( url_map_reference_resource, including_default_value_fields=False, @@ -1082,7 +1085,7 @@ def test_set_url_map_rest_flattened(): def test_set_url_map_rest_flattened_error(): client = RegionTargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1100,16 +1103,16 @@ def test_set_url_map_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.RegionTargetHttpProxiesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionTargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.RegionTargetHttpProxiesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionTargetHttpProxiesClient( @@ -1119,7 +1122,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.RegionTargetHttpProxiesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionTargetHttpProxiesClient( @@ -1130,7 +1133,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.RegionTargetHttpProxiesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = RegionTargetHttpProxiesClient(transport=transport) assert client.transport is transport @@ -1141,17 +1144,17 @@ def test_transport_instance(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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_target_http_proxies_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.RegionTargetHttpProxiesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1163,7 +1166,7 @@ def test_region_target_http_proxies_base_transport(): ) as Transport: Transport.return_value = None transport = transports.RegionTargetHttpProxiesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1180,15 +1183,40 @@ def test_region_target_http_proxies_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_region_target_http_proxies_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.region_target_http_proxies.transports.RegionTargetHttpProxiesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionTargetHttpProxiesTransport( + 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_target_http_proxies_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_target_http_proxies.transports.RegionTargetHttpProxiesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionTargetHttpProxiesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1204,19 +1232,36 @@ def test_region_target_http_proxies_base_transport_with_credentials_file(): def test_region_target_http_proxies_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.region_target_http_proxies.transports.RegionTargetHttpProxiesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionTargetHttpProxiesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_region_target_http_proxies_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RegionTargetHttpProxiesClient() + 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_target_http_proxies_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) RegionTargetHttpProxiesClient() adc.assert_called_once_with( scopes=( @@ -1228,7 +1273,7 @@ def test_region_target_http_proxies_auth_adc(): def test_region_target_http_proxies_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1240,7 +1285,7 @@ def test_region_target_http_proxies_http_transport_client_cert_source_for_mtls() def test_region_target_http_proxies_host_no_port(): client = RegionTargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1250,7 +1295,7 @@ def test_region_target_http_proxies_host_no_port(): def test_region_target_http_proxies_host_with_port(): client = RegionTargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1260,7 +1305,6 @@ def test_region_target_http_proxies_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1281,7 +1325,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = RegionTargetHttpProxiesClient.common_folder_path(folder) assert expected == actual @@ -1300,7 +1343,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = RegionTargetHttpProxiesClient.common_organization_path(organization) assert expected == actual @@ -1319,7 +1361,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = RegionTargetHttpProxiesClient.common_project_path(project) assert expected == actual @@ -1339,7 +1380,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1366,7 +1406,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.RegionTargetHttpProxiesTransport, "_prep_wrapped_messages" ) as prep: client = RegionTargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1375,6 +1415,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = RegionTargetHttpProxiesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_region_target_https_proxies.py b/tests/unit/gapic/compute_v1/test_region_target_https_proxies.py index 7d81fd215..eb6a150f0 100644 --- a/tests/unit/gapic/compute_v1/test_region_target_https_proxies.py +++ b/tests/unit/gapic/compute_v1/test_region_target_https_proxies.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,33 +13,63 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.compute_v1.services.region_target_https_proxies import ( RegionTargetHttpsProxiesClient, ) 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, +) 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 +# - 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", +) + +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(): @@ -90,7 +119,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [RegionTargetHttpsProxiesClient,]) def test_region_target_https_proxies_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -105,7 +134,7 @@ def test_region_target_https_proxies_client_from_service_account_info(client_cla @pytest.mark.parametrize("client_class", [RegionTargetHttpsProxiesClient,]) def test_region_target_https_proxies_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -154,7 +183,7 @@ def test_region_target_https_proxies_client_client_options( with mock.patch.object( RegionTargetHttpsProxiesClient, "get_transport_class" ) as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -416,7 +445,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteRegionTargetHttpsProxyRequest ): client = RegionTargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -451,17 +480,16 @@ def test_delete_rest( 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" @@ -496,7 +524,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): client = RegionTargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -524,17 +552,14 @@ def test_delete_rest_flattened(): 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 "target_https_proxy_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): client = RegionTargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -552,7 +577,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetRegionTargetHttpsProxyRequest ): client = RegionTargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -578,17 +603,16 @@ def test_get_rest( ssl_policy="ssl_policy_value", url_map="url_map_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.TargetHttpsProxy.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.TargetHttpsProxy) assert response.authorization_policy == "authorization_policy_value" assert response.creation_timestamp == "creation_timestamp_value" @@ -596,7 +620,6 @@ 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.quic_override == compute.TargetHttpsProxy.QuicOverride.DISABLE assert response.region == "region_value" @@ -613,7 +636,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): client = RegionTargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -641,17 +664,14 @@ def test_get_rest_flattened(): 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 "target_https_proxy_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): client = RegionTargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -669,7 +689,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertRegionTargetHttpsProxyRequest ): client = RegionTargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -704,17 +724,16 @@ def test_insert_rest( 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" @@ -749,7 +768,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): client = RegionTargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -769,7 +788,6 @@ def test_insert_rest_flattened(): target_https_proxy_resource = compute.TargetHttpsProxy( authorization_policy="authorization_policy_value" ) - client.insert( project="project_value", region="region_value", @@ -781,11 +799,8 @@ def test_insert_rest_flattened(): 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.TargetHttpsProxy.to_json( target_https_proxy_resource, including_default_value_fields=False, @@ -795,7 +810,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): client = RegionTargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -815,7 +830,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListRegionTargetHttpsProxiesRequest ): client = RegionTargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -837,17 +852,16 @@ def test_list_rest( 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.TargetHttpsProxyList.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 == [ @@ -865,7 +879,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): client = RegionTargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -891,15 +905,13 @@ def test_list_rest_flattened(): 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 = RegionTargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -914,13 +926,12 @@ def test_list_rest_flattened_error(): def test_list_pager(): client = RegionTargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), + 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.TargetHttpsProxyList( items=[ @@ -938,7 +949,6 @@ def test_list_pager(): items=[compute.TargetHttpsProxy(), compute.TargetHttpsProxy(),], ), ) - # Two responses for two calls response = response + response @@ -957,7 +967,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.TargetHttpsProxy) for i in results) pages = list(client.list(request={}).pages) @@ -970,7 +979,7 @@ def test_set_ssl_certificates_rest( request_type=compute.SetSslCertificatesRegionTargetHttpsProxyRequest, ): client = RegionTargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1005,17 +1014,16 @@ def test_set_ssl_certificates_rest( 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_ssl_certificates(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" @@ -1050,7 +1058,7 @@ def test_set_ssl_certificates_rest_from_dict(): def test_set_ssl_certificates_rest_flattened(): client = RegionTargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1070,7 +1078,6 @@ def test_set_ssl_certificates_rest_flattened(): region_target_https_proxies_set_ssl_certificates_request_resource = compute.RegionTargetHttpsProxiesSetSslCertificatesRequest( ssl_certificates=["ssl_certificates_value"] ) - client.set_ssl_certificates( project="project_value", region="region_value", @@ -1083,13 +1090,9 @@ def test_set_ssl_certificates_rest_flattened(): 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 "target_https_proxy_value" in http_call[1] + str(body) - assert compute.RegionTargetHttpsProxiesSetSslCertificatesRequest.to_json( region_target_https_proxies_set_ssl_certificates_request_resource, including_default_value_fields=False, @@ -1099,7 +1102,7 @@ def test_set_ssl_certificates_rest_flattened(): def test_set_ssl_certificates_rest_flattened_error(): client = RegionTargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1120,7 +1123,7 @@ def test_set_url_map_rest( transport: str = "rest", request_type=compute.SetUrlMapRegionTargetHttpsProxyRequest ): client = RegionTargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1155,17 +1158,16 @@ def test_set_url_map_rest( 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_url_map(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" @@ -1200,7 +1202,7 @@ def test_set_url_map_rest_from_dict(): def test_set_url_map_rest_flattened(): client = RegionTargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. @@ -1218,7 +1220,6 @@ def test_set_url_map_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. url_map_reference_resource = compute.UrlMapReference(url_map="url_map_value") - client.set_url_map( project="project_value", region="region_value", @@ -1231,13 +1232,9 @@ def test_set_url_map_rest_flattened(): 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 "target_https_proxy_value" in http_call[1] + str(body) - assert compute.UrlMapReference.to_json( url_map_reference_resource, including_default_value_fields=False, @@ -1247,7 +1244,7 @@ def test_set_url_map_rest_flattened(): def test_set_url_map_rest_flattened_error(): client = RegionTargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1265,16 +1262,16 @@ def test_set_url_map_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.RegionTargetHttpsProxiesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionTargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.RegionTargetHttpsProxiesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionTargetHttpsProxiesClient( @@ -1284,7 +1281,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.RegionTargetHttpsProxiesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionTargetHttpsProxiesClient( @@ -1295,7 +1292,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.RegionTargetHttpsProxiesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = RegionTargetHttpsProxiesClient(transport=transport) assert client.transport is transport @@ -1306,17 +1303,17 @@ def test_transport_instance(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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_target_https_proxies_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.RegionTargetHttpsProxiesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1328,7 +1325,7 @@ def test_region_target_https_proxies_base_transport(): ) as Transport: Transport.return_value = None transport = transports.RegionTargetHttpsProxiesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1346,15 +1343,40 @@ def test_region_target_https_proxies_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_region_target_https_proxies_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.region_target_https_proxies.transports.RegionTargetHttpsProxiesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionTargetHttpsProxiesTransport( + 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_target_https_proxies_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_target_https_proxies.transports.RegionTargetHttpsProxiesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionTargetHttpsProxiesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1370,19 +1392,36 @@ def test_region_target_https_proxies_base_transport_with_credentials_file(): def test_region_target_https_proxies_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.region_target_https_proxies.transports.RegionTargetHttpsProxiesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionTargetHttpsProxiesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_region_target_https_proxies_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RegionTargetHttpsProxiesClient() + 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_target_https_proxies_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) RegionTargetHttpsProxiesClient() adc.assert_called_once_with( scopes=( @@ -1394,7 +1433,7 @@ def test_region_target_https_proxies_auth_adc(): def test_region_target_https_proxies_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1406,7 +1445,7 @@ def test_region_target_https_proxies_http_transport_client_cert_source_for_mtls( def test_region_target_https_proxies_host_no_port(): client = RegionTargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1416,7 +1455,7 @@ def test_region_target_https_proxies_host_no_port(): def test_region_target_https_proxies_host_with_port(): client = RegionTargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1426,7 +1465,6 @@ def test_region_target_https_proxies_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1447,7 +1485,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = RegionTargetHttpsProxiesClient.common_folder_path(folder) assert expected == actual @@ -1466,7 +1503,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = RegionTargetHttpsProxiesClient.common_organization_path(organization) assert expected == actual @@ -1485,7 +1521,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = RegionTargetHttpsProxiesClient.common_project_path(project) assert expected == actual @@ -1505,7 +1540,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1532,7 +1566,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.RegionTargetHttpsProxiesTransport, "_prep_wrapped_messages" ) as prep: client = RegionTargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1541,6 +1575,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = RegionTargetHttpsProxiesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_region_url_maps.py b/tests/unit/gapic/compute_v1/test_region_url_maps.py index 0ec7507fa..863019f4d 100644 --- a/tests/unit/gapic/compute_v1/test_region_url_maps.py +++ b/tests/unit/gapic/compute_v1/test_region_url_maps.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -87,7 +116,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [RegionUrlMapsClient,]) def test_region_url_maps_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -102,7 +131,7 @@ def test_region_url_maps_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [RegionUrlMapsClient,]) def test_region_url_maps_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -143,7 +172,7 @@ def test_region_url_maps_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(RegionUrlMapsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -381,7 +410,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteRegionUrlMapRequest ): client = RegionUrlMapsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -416,17 +445,16 @@ def test_delete_rest( 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" @@ -460,7 +488,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = RegionUrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionUrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -485,16 +513,13 @@ def test_delete_rest_flattened(): 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 "url_map_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = RegionUrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionUrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -509,7 +534,7 @@ def test_delete_rest_flattened_error(): def test_get_rest(transport: str = "rest", request_type=compute.GetRegionUrlMapRequest): client = RegionUrlMapsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -550,17 +575,16 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetRegionUrlMapR self_link="self_link_value", tests=[compute.UrlMapTest(description="description_value")], ) + # Wrap the value into a proper Response obj json_return_value = compute.UrlMap.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.UrlMap) assert response.creation_timestamp == "creation_timestamp_value" assert response.default_route_action == compute.HttpRouteAction( @@ -598,7 +622,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = RegionUrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionUrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -623,16 +647,13 @@ def test_get_rest_flattened(): 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 "url_map_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = RegionUrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionUrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -649,7 +670,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertRegionUrlMapRequest ): client = RegionUrlMapsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -684,17 +705,16 @@ def test_insert_rest( 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" @@ -728,7 +748,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = RegionUrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionUrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -745,7 +765,6 @@ def test_insert_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. url_map_resource = compute.UrlMap(creation_timestamp="creation_timestamp_value") - client.insert( project="project_value", region="region_value", @@ -757,11 +776,8 @@ def test_insert_rest_flattened(): 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.UrlMap.to_json( url_map_resource, including_default_value_fields=False, @@ -770,7 +786,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = RegionUrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionUrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -789,7 +805,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListRegionUrlMapsRequest ): client = RegionUrlMapsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -807,17 +823,16 @@ def test_list_rest( 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.UrlMapList.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 == [ @@ -834,7 +849,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = RegionUrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionUrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -859,14 +874,12 @@ def test_list_rest_flattened(): 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 = RegionUrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionUrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -879,12 +892,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = RegionUrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionUrlMapsClient(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.UrlMapList( items=[compute.UrlMap(), compute.UrlMap(), compute.UrlMap(),], @@ -894,7 +906,6 @@ def test_list_pager(): compute.UrlMapList(items=[compute.UrlMap(),], next_page_token="ghi",), compute.UrlMapList(items=[compute.UrlMap(), compute.UrlMap(),],), ) - # Two responses for two calls response = response + response @@ -913,7 +924,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.UrlMap) for i in results) pages = list(client.list(request={}).pages) @@ -925,7 +935,7 @@ def test_patch_rest( transport: str = "rest", request_type=compute.PatchRegionUrlMapRequest ): client = RegionUrlMapsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -960,17 +970,16 @@ def test_patch_rest( 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" @@ -1004,7 +1013,7 @@ def test_patch_rest_from_dict(): def test_patch_rest_flattened(): - client = RegionUrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionUrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1021,7 +1030,6 @@ def test_patch_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. url_map_resource = compute.UrlMap(creation_timestamp="creation_timestamp_value") - client.patch( project="project_value", region="region_value", @@ -1034,13 +1042,9 @@ def test_patch_rest_flattened(): 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 "url_map_value" in http_call[1] + str(body) - assert compute.UrlMap.to_json( url_map_resource, including_default_value_fields=False, @@ -1049,7 +1053,7 @@ def test_patch_rest_flattened(): def test_patch_rest_flattened_error(): - client = RegionUrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionUrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1069,7 +1073,7 @@ def test_update_rest( transport: str = "rest", request_type=compute.UpdateRegionUrlMapRequest ): client = RegionUrlMapsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1104,17 +1108,16 @@ def test_update_rest( 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.update(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" @@ -1148,7 +1151,7 @@ def test_update_rest_from_dict(): def test_update_rest_flattened(): - client = RegionUrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionUrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1165,7 +1168,6 @@ def test_update_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. url_map_resource = compute.UrlMap(creation_timestamp="creation_timestamp_value") - client.update( project="project_value", region="region_value", @@ -1178,13 +1180,9 @@ def test_update_rest_flattened(): 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 "url_map_value" in http_call[1] + str(body) - assert compute.UrlMap.to_json( url_map_resource, including_default_value_fields=False, @@ -1193,7 +1191,7 @@ def test_update_rest_flattened(): def test_update_rest_flattened_error(): - client = RegionUrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionUrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1213,7 +1211,7 @@ def test_validate_rest( transport: str = "rest", request_type=compute.ValidateRegionUrlMapRequest ): client = RegionUrlMapsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1226,17 +1224,16 @@ def test_validate_rest( return_value = compute.UrlMapsValidateResponse( result=compute.UrlMapValidationResult(load_errors=["load_errors_value"]), ) + # Wrap the value into a proper Response obj json_return_value = compute.UrlMapsValidateResponse.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.validate(request) # Establish that the response is the type that we expect. - assert isinstance(response, compute.UrlMapsValidateResponse) assert response.result == compute.UrlMapValidationResult( load_errors=["load_errors_value"] @@ -1248,7 +1245,7 @@ def test_validate_rest_from_dict(): def test_validate_rest_flattened(): - client = RegionUrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionUrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1267,7 +1264,6 @@ def test_validate_rest_flattened(): region_url_maps_validate_request_resource = compute.RegionUrlMapsValidateRequest( resource=compute.UrlMap(creation_timestamp="creation_timestamp_value") ) - client.validate( project="project_value", region="region_value", @@ -1280,13 +1276,9 @@ def test_validate_rest_flattened(): 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 "url_map_value" in http_call[1] + str(body) - assert compute.RegionUrlMapsValidateRequest.to_json( region_url_maps_validate_request_resource, including_default_value_fields=False, @@ -1295,7 +1287,7 @@ def test_validate_rest_flattened(): def test_validate_rest_flattened_error(): - client = RegionUrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionUrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1314,16 +1306,16 @@ def test_validate_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.RegionUrlMapsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionUrlMapsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.RegionUrlMapsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionUrlMapsClient( @@ -1333,7 +1325,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.RegionUrlMapsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionUrlMapsClient( @@ -1344,7 +1336,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.RegionUrlMapsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = RegionUrlMapsClient(transport=transport) assert client.transport is transport @@ -1353,17 +1345,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.RegionUrlMapsRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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_url_maps_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.RegionUrlMapsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1375,7 +1367,7 @@ def test_region_url_maps_base_transport(): ) as Transport: Transport.return_value = None transport = transports.RegionUrlMapsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1394,15 +1386,40 @@ def test_region_url_maps_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_region_url_maps_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.region_url_maps.transports.RegionUrlMapsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionUrlMapsTransport( + 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_url_maps_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_url_maps.transports.RegionUrlMapsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionUrlMapsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1418,19 +1435,36 @@ def test_region_url_maps_base_transport_with_credentials_file(): def test_region_url_maps_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.region_url_maps.transports.RegionUrlMapsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionUrlMapsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_region_url_maps_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RegionUrlMapsClient() + 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_url_maps_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) RegionUrlMapsClient() adc.assert_called_once_with( scopes=( @@ -1442,7 +1476,7 @@ def test_region_url_maps_auth_adc(): def test_region_url_maps_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1454,7 +1488,7 @@ def test_region_url_maps_http_transport_client_cert_source_for_mtls(): def test_region_url_maps_host_no_port(): client = RegionUrlMapsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1464,7 +1498,7 @@ def test_region_url_maps_host_no_port(): def test_region_url_maps_host_with_port(): client = RegionUrlMapsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1474,7 +1508,6 @@ def test_region_url_maps_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1495,7 +1528,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = RegionUrlMapsClient.common_folder_path(folder) assert expected == actual @@ -1514,7 +1546,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = RegionUrlMapsClient.common_organization_path(organization) assert expected == actual @@ -1533,7 +1564,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = RegionUrlMapsClient.common_project_path(project) assert expected == actual @@ -1553,7 +1583,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1580,7 +1609,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.RegionUrlMapsTransport, "_prep_wrapped_messages" ) as prep: client = RegionUrlMapsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1589,6 +1618,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = RegionUrlMapsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_regions.py b/tests/unit/gapic/compute_v1/test_regions.py index a7a50c876..324dc36c2 100644 --- a/tests/unit/gapic/compute_v1/test_regions.py +++ b/tests/unit/gapic/compute_v1/test_regions.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,59 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -81,7 +108,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [RegionsClient,]) def test_regions_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -96,7 +123,7 @@ def test_regions_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [RegionsClient,]) def test_regions_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -133,7 +160,7 @@ def test_regions_client_get_transport_class(): def test_regions_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(RegionsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -367,7 +394,7 @@ def test_regions_client_client_options_credentials_file( def test_get_rest(transport: str = "rest", request_type=compute.GetRegionRequest): client = RegionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -389,17 +416,16 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetRegionRequest status=compute.Region.Status.DOWN, zones=["zones_value"], ) + # Wrap the value into a proper Response obj json_return_value = compute.Region.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.Region) assert response.creation_timestamp == "creation_timestamp_value" assert response.deprecated == compute.DeprecationStatus(deleted="deleted_value") @@ -418,7 +444,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = RegionsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -443,14 +469,12 @@ def test_get_rest_flattened(): 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_get_rest_flattened_error(): - client = RegionsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -462,7 +486,7 @@ def test_get_rest_flattened_error(): def test_list_rest(transport: str = "rest", request_type=compute.ListRegionsRequest): client = RegionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -480,17 +504,16 @@ def test_list_rest(transport: str = "rest", request_type=compute.ListRegionsRequ 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.RegionList.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 == [ @@ -507,7 +530,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = RegionsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -530,12 +553,11 @@ def test_list_rest_flattened(): 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 = RegionsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -546,12 +568,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = RegionsClient(credentials=credentials.AnonymousCredentials(),) + client = RegionsClient(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.RegionList( items=[compute.Region(), compute.Region(), compute.Region(),], @@ -561,7 +582,6 @@ def test_list_pager(): compute.RegionList(items=[compute.Region(),], next_page_token="ghi",), compute.RegionList(items=[compute.Region(), compute.Region(),],), ) - # Two responses for two calls response = response + response @@ -580,7 +600,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.Region) for i in results) pages = list(client.list(request={}).pages) @@ -591,16 +610,16 @@ def test_list_pager(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.RegionsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.RegionsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionsClient( @@ -610,7 +629,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.RegionsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RegionsClient( @@ -621,7 +640,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.RegionsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = RegionsClient(transport=transport) assert client.transport is transport @@ -630,17 +649,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.RegionsRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_regions_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.RegionsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -652,7 +671,7 @@ def test_regions_base_transport(): ) as Transport: Transport.return_value = None transport = transports.RegionsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -666,15 +685,41 @@ def test_regions_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_regions_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.regions.transports.RegionsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionsTransport( + 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.readonly", + "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_regions_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.regions.transports.RegionsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -691,19 +736,37 @@ def test_regions_base_transport_with_credentials_file(): def test_regions_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.regions.transports.RegionsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_regions_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RegionsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/compute.readonly", + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_regions_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) RegionsClient() adc.assert_called_once_with( scopes=( @@ -716,7 +779,7 @@ def test_regions_auth_adc(): def test_regions_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -728,7 +791,7 @@ def test_regions_http_transport_client_cert_source_for_mtls(): def test_regions_host_no_port(): client = RegionsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -738,7 +801,7 @@ def test_regions_host_no_port(): def test_regions_host_with_port(): client = RegionsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -748,7 +811,6 @@ def test_regions_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -769,7 +831,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = RegionsClient.common_folder_path(folder) assert expected == actual @@ -788,7 +849,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = RegionsClient.common_organization_path(organization) assert expected == actual @@ -807,7 +867,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = RegionsClient.common_project_path(project) assert expected == actual @@ -827,7 +886,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -854,7 +912,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.RegionsTransport, "_prep_wrapped_messages" ) as prep: client = RegionsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -863,6 +921,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = RegionsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_reservations.py b/tests/unit/gapic/compute_v1/test_reservations.py index 2c251b684..588da231f 100644 --- a/tests/unit/gapic/compute_v1/test_reservations.py +++ b/tests/unit/gapic/compute_v1/test_reservations.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -84,7 +113,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [ReservationsClient,]) def test_reservations_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -99,7 +128,7 @@ def test_reservations_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [ReservationsClient,]) def test_reservations_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -138,7 +167,7 @@ def test_reservations_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(ReservationsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -374,7 +403,7 @@ def test_aggregated_list_rest( transport: str = "rest", request_type=compute.AggregatedListReservationsRequest ): client = ReservationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -397,17 +426,16 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.ReservationAggregatedList.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 == { @@ -427,7 +455,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = ReservationsClient(credentials=credentials.AnonymousCredentials(),) + client = ReservationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -450,12 +478,11 @@ def test_aggregated_list_rest_flattened(): 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 = ReservationsClient(credentials=credentials.AnonymousCredentials(),) + client = ReservationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -466,12 +493,11 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = ReservationsClient(credentials=credentials.AnonymousCredentials(),) + client = ReservationsClient(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.ReservationAggregatedList( items={ @@ -492,7 +518,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -514,7 +539,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -535,7 +559,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteReservationRequest ): client = ReservationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -570,17 +594,16 @@ def test_delete_rest( 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" @@ -614,7 +637,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = ReservationsClient(credentials=credentials.AnonymousCredentials(),) + client = ReservationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -639,16 +662,13 @@ def test_delete_rest_flattened(): 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 "reservation_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = ReservationsClient(credentials=credentials.AnonymousCredentials(),) + client = ReservationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -663,7 +683,7 @@ def test_delete_rest_flattened_error(): def test_get_rest(transport: str = "rest", request_type=compute.GetReservationRequest): client = ReservationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -688,17 +708,16 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetReservationRe status=compute.Reservation.Status.CREATING, zone="zone_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.Reservation.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.Reservation) assert response.commitment == "commitment_value" assert response.creation_timestamp == "creation_timestamp_value" @@ -710,7 +729,6 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetReservationRe assert response.specific_reservation == compute.AllocationSpecificSKUReservation( count="count_value" ) - assert response.specific_reservation_required is True assert response.status == compute.Reservation.Status.CREATING assert response.zone == "zone_value" @@ -721,7 +739,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = ReservationsClient(credentials=credentials.AnonymousCredentials(),) + client = ReservationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -746,16 +764,13 @@ def test_get_rest_flattened(): 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 "reservation_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = ReservationsClient(credentials=credentials.AnonymousCredentials(),) + client = ReservationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -772,7 +787,7 @@ def test_get_iam_policy_rest( transport: str = "rest", request_type=compute.GetIamPolicyReservationRequest ): client = ReservationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -798,17 +813,16 @@ def test_get_iam_policy_rest( 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( @@ -819,7 +833,6 @@ def test_get_iam_policy_rest( ] 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 @@ -830,7 +843,7 @@ def test_get_iam_policy_rest_from_dict(): def test_get_iam_policy_rest_flattened(): - client = ReservationsClient(credentials=credentials.AnonymousCredentials(),) + client = ReservationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -855,16 +868,13 @@ def test_get_iam_policy_rest_flattened(): 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 "resource_value" in http_call[1] + str(body) def test_get_iam_policy_rest_flattened_error(): - client = ReservationsClient(credentials=credentials.AnonymousCredentials(),) + client = ReservationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -881,7 +891,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertReservationRequest ): client = ReservationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -916,17 +926,16 @@ def test_insert_rest( 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" @@ -960,7 +969,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = ReservationsClient(credentials=credentials.AnonymousCredentials(),) + client = ReservationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -977,7 +986,6 @@ def test_insert_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. reservation_resource = compute.Reservation(commitment="commitment_value") - client.insert( project="project_value", zone="zone_value", @@ -989,11 +997,8 @@ def test_insert_rest_flattened(): 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.Reservation.to_json( reservation_resource, including_default_value_fields=False, @@ -1002,7 +1007,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = ReservationsClient(credentials=credentials.AnonymousCredentials(),) + client = ReservationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1019,7 +1024,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListReservationsRequest ): client = ReservationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1037,17 +1042,16 @@ def test_list_rest( 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.ReservationList.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.Reservation(commitment="commitment_value")] @@ -1062,7 +1066,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = ReservationsClient(credentials=credentials.AnonymousCredentials(),) + client = ReservationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1087,14 +1091,12 @@ def test_list_rest_flattened(): 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) def test_list_rest_flattened_error(): - client = ReservationsClient(credentials=credentials.AnonymousCredentials(),) + client = ReservationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1107,12 +1109,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = ReservationsClient(credentials=credentials.AnonymousCredentials(),) + client = ReservationsClient(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.ReservationList( items=[ @@ -1130,7 +1131,6 @@ def test_list_pager(): items=[compute.Reservation(), compute.Reservation(),], ), ) - # Two responses for two calls response = response + response @@ -1149,7 +1149,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.Reservation) for i in results) pages = list(client.list(request={}).pages) @@ -1161,7 +1160,7 @@ def test_resize_rest( transport: str = "rest", request_type=compute.ResizeReservationRequest ): client = ReservationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1196,17 +1195,16 @@ def test_resize_rest( 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.resize(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" @@ -1240,7 +1238,7 @@ def test_resize_rest_from_dict(): def test_resize_rest_flattened(): - client = ReservationsClient(credentials=credentials.AnonymousCredentials(),) + client = ReservationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1259,7 +1257,6 @@ def test_resize_rest_flattened(): reservations_resize_request_resource = compute.ReservationsResizeRequest( specific_sku_count="specific_sku_count_value" ) - client.resize( project="project_value", zone="zone_value", @@ -1272,13 +1269,9 @@ def test_resize_rest_flattened(): 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 "reservation_value" in http_call[1] + str(body) - assert compute.ReservationsResizeRequest.to_json( reservations_resize_request_resource, including_default_value_fields=False, @@ -1287,7 +1280,7 @@ def test_resize_rest_flattened(): def test_resize_rest_flattened_error(): - client = ReservationsClient(credentials=credentials.AnonymousCredentials(),) + client = ReservationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1307,7 +1300,7 @@ def test_set_iam_policy_rest( transport: str = "rest", request_type=compute.SetIamPolicyReservationRequest ): client = ReservationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1333,17 +1326,16 @@ def test_set_iam_policy_rest( 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( @@ -1354,7 +1346,6 @@ def test_set_iam_policy_rest( ] 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 @@ -1365,7 +1356,7 @@ def test_set_iam_policy_rest_from_dict(): def test_set_iam_policy_rest_flattened(): - client = ReservationsClient(credentials=credentials.AnonymousCredentials(),) + client = ReservationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1384,7 +1375,6 @@ def test_set_iam_policy_rest_flattened(): zone_set_policy_request_resource = compute.ZoneSetPolicyRequest( bindings=[compute.Binding(binding_id="binding_id_value")] ) - client.set_iam_policy( project="project_value", zone="zone_value", @@ -1397,13 +1387,9 @@ def test_set_iam_policy_rest_flattened(): 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 "resource_value" in http_call[1] + str(body) - assert compute.ZoneSetPolicyRequest.to_json( zone_set_policy_request_resource, including_default_value_fields=False, @@ -1412,7 +1398,7 @@ def test_set_iam_policy_rest_flattened(): def test_set_iam_policy_rest_flattened_error(): - client = ReservationsClient(credentials=credentials.AnonymousCredentials(),) + client = ReservationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1432,7 +1418,7 @@ def test_test_iam_permissions_rest( transport: str = "rest", request_type=compute.TestIamPermissionsReservationRequest ): client = ReservationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1445,17 +1431,16 @@ def test_test_iam_permissions_rest( 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"] @@ -1465,7 +1450,7 @@ def test_test_iam_permissions_rest_from_dict(): def test_test_iam_permissions_rest_flattened(): - client = ReservationsClient(credentials=credentials.AnonymousCredentials(),) + client = ReservationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1484,7 +1469,6 @@ def test_test_iam_permissions_rest_flattened(): test_permissions_request_resource = compute.TestPermissionsRequest( permissions=["permissions_value"] ) - client.test_iam_permissions( project="project_value", zone="zone_value", @@ -1497,13 +1481,9 @@ def test_test_iam_permissions_rest_flattened(): 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 "resource_value" in http_call[1] + str(body) - assert compute.TestPermissionsRequest.to_json( test_permissions_request_resource, including_default_value_fields=False, @@ -1512,7 +1492,7 @@ def test_test_iam_permissions_rest_flattened(): def test_test_iam_permissions_rest_flattened_error(): - client = ReservationsClient(credentials=credentials.AnonymousCredentials(),) + client = ReservationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1531,16 +1511,16 @@ def test_test_iam_permissions_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ReservationsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ReservationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.ReservationsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ReservationsClient( @@ -1550,7 +1530,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ReservationsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ReservationsClient( @@ -1561,7 +1541,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ReservationsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ReservationsClient(transport=transport) assert client.transport is transport @@ -1570,17 +1550,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.ReservationsRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_reservations_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ReservationsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1592,7 +1572,7 @@ def test_reservations_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ReservationsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1613,15 +1593,40 @@ def test_reservations_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_reservations_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.reservations.transports.ReservationsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ReservationsTransport( + 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_reservations_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.reservations.transports.ReservationsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ReservationsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1637,19 +1642,36 @@ def test_reservations_base_transport_with_credentials_file(): def test_reservations_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.reservations.transports.ReservationsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ReservationsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_reservations_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ReservationsClient() + 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_reservations_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) ReservationsClient() adc.assert_called_once_with( scopes=( @@ -1661,7 +1683,7 @@ def test_reservations_auth_adc(): def test_reservations_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1673,7 +1695,7 @@ def test_reservations_http_transport_client_cert_source_for_mtls(): def test_reservations_host_no_port(): client = ReservationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1683,7 +1705,7 @@ def test_reservations_host_no_port(): def test_reservations_host_with_port(): client = ReservationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1693,7 +1715,6 @@ def test_reservations_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1714,7 +1735,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = ReservationsClient.common_folder_path(folder) assert expected == actual @@ -1733,7 +1753,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = ReservationsClient.common_organization_path(organization) assert expected == actual @@ -1752,7 +1771,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = ReservationsClient.common_project_path(project) assert expected == actual @@ -1772,7 +1790,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1799,7 +1816,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ReservationsTransport, "_prep_wrapped_messages" ) as prep: client = ReservationsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1808,6 +1825,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ReservationsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_resource_policies.py b/tests/unit/gapic/compute_v1/test_resource_policies.py index 1741d029e..b082062c3 100644 --- a/tests/unit/gapic/compute_v1/test_resource_policies.py +++ b/tests/unit/gapic/compute_v1/test_resource_policies.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -88,7 +117,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [ResourcePoliciesClient,]) def test_resource_policies_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -103,7 +132,7 @@ def test_resource_policies_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [ResourcePoliciesClient,]) def test_resource_policies_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -144,7 +173,7 @@ def test_resource_policies_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(ResourcePoliciesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -392,7 +421,7 @@ def test_aggregated_list_rest( transport: str = "rest", request_type=compute.AggregatedListResourcePoliciesRequest ): client = ResourcePoliciesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -420,17 +449,16 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.ResourcePolicyAggregatedList.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.etag == "etag_value" assert response.id == "id_value" @@ -453,7 +481,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = ResourcePoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = ResourcePoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -476,12 +504,11 @@ def test_aggregated_list_rest_flattened(): 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 = ResourcePoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = ResourcePoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -492,12 +519,11 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = ResourcePoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = ResourcePoliciesClient(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.ResourcePolicyAggregatedList( items={ @@ -519,7 +545,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -543,7 +568,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -564,7 +588,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteResourcePolicyRequest ): client = ResourcePoliciesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -599,17 +623,16 @@ def test_delete_rest( 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" @@ -643,7 +666,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = ResourcePoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = ResourcePoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -670,16 +693,13 @@ def test_delete_rest_flattened(): 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_policy_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = ResourcePoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = ResourcePoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -696,7 +716,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetResourcePolicyRequest ): client = ResourcePoliciesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -724,17 +744,16 @@ def test_get_rest( ), status=compute.ResourcePolicy.Status.CREATING, ) + # Wrap the value into a proper Response obj json_return_value = compute.ResourcePolicy.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.ResourcePolicy) assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" @@ -763,7 +782,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = ResourcePoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = ResourcePoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -790,16 +809,13 @@ def test_get_rest_flattened(): 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_policy_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = ResourcePoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = ResourcePoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -816,7 +832,7 @@ def test_get_iam_policy_rest( transport: str = "rest", request_type=compute.GetIamPolicyResourcePolicyRequest ): client = ResourcePoliciesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -842,17 +858,16 @@ def test_get_iam_policy_rest( 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( @@ -863,7 +878,6 @@ def test_get_iam_policy_rest( ] 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 @@ -874,7 +888,7 @@ def test_get_iam_policy_rest_from_dict(): def test_get_iam_policy_rest_flattened(): - client = ResourcePoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = ResourcePoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -899,16 +913,13 @@ def test_get_iam_policy_rest_flattened(): 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) def test_get_iam_policy_rest_flattened_error(): - client = ResourcePoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = ResourcePoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -925,7 +936,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertResourcePolicyRequest ): client = ResourcePoliciesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -960,17 +971,16 @@ def test_insert_rest( 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" @@ -1004,7 +1014,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = ResourcePoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = ResourcePoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1023,7 +1033,6 @@ def test_insert_rest_flattened(): resource_policy_resource = compute.ResourcePolicy( creation_timestamp="creation_timestamp_value" ) - client.insert( project="project_value", region="region_value", @@ -1035,11 +1044,8 @@ def test_insert_rest_flattened(): 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.ResourcePolicy.to_json( resource_policy_resource, including_default_value_fields=False, @@ -1048,7 +1054,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = ResourcePoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = ResourcePoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1067,7 +1073,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListResourcePoliciesRequest ): client = ResourcePoliciesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1088,17 +1094,16 @@ def test_list_rest( 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.ResourcePolicyList.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.etag == "etag_value" assert response.id == "id_value" @@ -1116,7 +1121,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = ResourcePoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = ResourcePoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1141,14 +1146,12 @@ def test_list_rest_flattened(): 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 = ResourcePoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = ResourcePoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1161,12 +1164,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = ResourcePoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = ResourcePoliciesClient(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.ResourcePolicyList( items=[ @@ -1184,7 +1186,6 @@ def test_list_pager(): items=[compute.ResourcePolicy(), compute.ResourcePolicy(),], ), ) - # Two responses for two calls response = response + response @@ -1203,7 +1204,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.ResourcePolicy) for i in results) pages = list(client.list(request={}).pages) @@ -1215,7 +1215,7 @@ def test_set_iam_policy_rest( transport: str = "rest", request_type=compute.SetIamPolicyResourcePolicyRequest ): client = ResourcePoliciesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1241,17 +1241,16 @@ def test_set_iam_policy_rest( 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( @@ -1262,7 +1261,6 @@ def test_set_iam_policy_rest( ] 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 @@ -1273,7 +1271,7 @@ def test_set_iam_policy_rest_from_dict(): def test_set_iam_policy_rest_flattened(): - client = ResourcePoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = ResourcePoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1292,7 +1290,6 @@ def test_set_iam_policy_rest_flattened(): region_set_policy_request_resource = compute.RegionSetPolicyRequest( bindings=[compute.Binding(binding_id="binding_id_value")] ) - client.set_iam_policy( project="project_value", region="region_value", @@ -1305,13 +1302,9 @@ def test_set_iam_policy_rest_flattened(): 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.RegionSetPolicyRequest.to_json( region_set_policy_request_resource, including_default_value_fields=False, @@ -1320,7 +1313,7 @@ def test_set_iam_policy_rest_flattened(): def test_set_iam_policy_rest_flattened_error(): - client = ResourcePoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = ResourcePoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1341,7 +1334,7 @@ def test_test_iam_permissions_rest( request_type=compute.TestIamPermissionsResourcePolicyRequest, ): client = ResourcePoliciesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1354,17 +1347,16 @@ def test_test_iam_permissions_rest( 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"] @@ -1374,7 +1366,7 @@ def test_test_iam_permissions_rest_from_dict(): def test_test_iam_permissions_rest_flattened(): - client = ResourcePoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = ResourcePoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1393,7 +1385,6 @@ def test_test_iam_permissions_rest_flattened(): test_permissions_request_resource = compute.TestPermissionsRequest( permissions=["permissions_value"] ) - client.test_iam_permissions( project="project_value", region="region_value", @@ -1406,13 +1397,9 @@ def test_test_iam_permissions_rest_flattened(): 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.TestPermissionsRequest.to_json( test_permissions_request_resource, including_default_value_fields=False, @@ -1421,7 +1408,7 @@ def test_test_iam_permissions_rest_flattened(): def test_test_iam_permissions_rest_flattened_error(): - client = ResourcePoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = ResourcePoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1440,16 +1427,16 @@ def test_test_iam_permissions_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ResourcePoliciesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ResourcePoliciesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.ResourcePoliciesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ResourcePoliciesClient( @@ -1459,7 +1446,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ResourcePoliciesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ResourcePoliciesClient( @@ -1470,7 +1457,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ResourcePoliciesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ResourcePoliciesClient(transport=transport) assert client.transport is transport @@ -1479,17 +1466,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.ResourcePoliciesRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_resource_policies_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ResourcePoliciesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1501,7 +1488,7 @@ def test_resource_policies_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ResourcePoliciesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1521,15 +1508,40 @@ def test_resource_policies_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_resource_policies_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.resource_policies.transports.ResourcePoliciesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ResourcePoliciesTransport( + 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_resource_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.resource_policies.transports.ResourcePoliciesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ResourcePoliciesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1545,19 +1557,36 @@ def test_resource_policies_base_transport_with_credentials_file(): def test_resource_policies_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.resource_policies.transports.ResourcePoliciesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ResourcePoliciesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_resource_policies_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ResourcePoliciesClient() + 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_resource_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) ResourcePoliciesClient() adc.assert_called_once_with( scopes=( @@ -1569,7 +1598,7 @@ def test_resource_policies_auth_adc(): def test_resource_policies_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1581,7 +1610,7 @@ def test_resource_policies_http_transport_client_cert_source_for_mtls(): def test_resource_policies_host_no_port(): client = ResourcePoliciesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1591,7 +1620,7 @@ def test_resource_policies_host_no_port(): def test_resource_policies_host_with_port(): client = ResourcePoliciesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1601,7 +1630,6 @@ def test_resource_policies_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1622,7 +1650,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = ResourcePoliciesClient.common_folder_path(folder) assert expected == actual @@ -1641,7 +1668,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = ResourcePoliciesClient.common_organization_path(organization) assert expected == actual @@ -1660,7 +1686,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = ResourcePoliciesClient.common_project_path(project) assert expected == actual @@ -1680,7 +1705,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1707,7 +1731,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ResourcePoliciesTransport, "_prep_wrapped_messages" ) as prep: client = ResourcePoliciesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1716,6 +1740,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ResourcePoliciesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_routers.py b/tests/unit/gapic/compute_v1/test_routers.py index 2b3d9ab3b..990e3f53f 100644 --- a/tests/unit/gapic/compute_v1/test_routers.py +++ b/tests/unit/gapic/compute_v1/test_routers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,59 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -81,7 +108,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [RoutersClient,]) def test_routers_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -96,7 +123,7 @@ def test_routers_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [RoutersClient,]) def test_routers_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -133,7 +160,7 @@ def test_routers_client_get_transport_class(): def test_routers_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(RoutersClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -369,7 +396,7 @@ def test_aggregated_list_rest( transport: str = "rest", request_type=compute.AggregatedListRoutersRequest ): client = RoutersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -398,17 +425,16 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.RouterAggregatedList.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 == { @@ -434,7 +460,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = RoutersClient(credentials=credentials.AnonymousCredentials(),) + client = RoutersClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -457,12 +483,11 @@ def test_aggregated_list_rest_flattened(): 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 = RoutersClient(credentials=credentials.AnonymousCredentials(),) + client = RoutersClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -473,12 +498,11 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = RoutersClient(credentials=credentials.AnonymousCredentials(),) + client = RoutersClient(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.RouterAggregatedList( items={ @@ -499,7 +523,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -521,7 +544,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -537,7 +559,7 @@ def test_aggregated_list_pager(): def test_delete_rest(transport: str = "rest", request_type=compute.DeleteRouterRequest): client = RoutersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -572,17 +594,16 @@ def test_delete_rest(transport: str = "rest", request_type=compute.DeleteRouterR 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" @@ -616,7 +637,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = RoutersClient(credentials=credentials.AnonymousCredentials(),) + client = RoutersClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -641,16 +662,13 @@ def test_delete_rest_flattened(): 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 "router_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = RoutersClient(credentials=credentials.AnonymousCredentials(),) + client = RoutersClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -665,7 +683,7 @@ def test_delete_rest_flattened_error(): def test_get_rest(transport: str = "rest", request_type=compute.GetRouterRequest): client = RoutersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -695,17 +713,16 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetRouterRequest region="region_value", self_link="self_link_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.Router.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.Router) assert response.bgp == compute.RouterBgp( advertise_mode=compute.RouterBgp.AdvertiseMode.CUSTOM @@ -730,7 +747,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = RoutersClient(credentials=credentials.AnonymousCredentials(),) + client = RoutersClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -755,16 +772,13 @@ def test_get_rest_flattened(): 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 "router_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = RoutersClient(credentials=credentials.AnonymousCredentials(),) + client = RoutersClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -781,7 +795,7 @@ def test_get_nat_mapping_info_rest( transport: str = "rest", request_type=compute.GetNatMappingInfoRoutersRequest ): client = RoutersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -799,17 +813,16 @@ def test_get_nat_mapping_info_rest( 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.VmEndpointNatMappingsList.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_nat_mapping_info(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GetNatMappingInfoPager) assert response.id == "id_value" assert response.kind == "kind_value" @@ -826,7 +839,7 @@ def test_get_nat_mapping_info_rest_from_dict(): def test_get_nat_mapping_info_rest_flattened(): - client = RoutersClient(credentials=credentials.AnonymousCredentials(),) + client = RoutersClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -851,16 +864,13 @@ def test_get_nat_mapping_info_rest_flattened(): 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 "router_value" in http_call[1] + str(body) def test_get_nat_mapping_info_rest_flattened_error(): - client = RoutersClient(credentials=credentials.AnonymousCredentials(),) + client = RoutersClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -874,12 +884,11 @@ def test_get_nat_mapping_info_rest_flattened_error(): def test_get_nat_mapping_info_pager(): - client = RoutersClient(credentials=credentials.AnonymousCredentials(),) + client = RoutersClient(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.VmEndpointNatMappingsList( result=[ @@ -900,7 +909,6 @@ def test_get_nat_mapping_info_pager(): ], ), ) - # Two responses for two calls response = response + response @@ -919,7 +927,6 @@ def test_get_nat_mapping_info_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.VmEndpointNatMappings) for i in results) pages = list(client.get_nat_mapping_info(request={}).pages) @@ -931,7 +938,7 @@ def test_get_router_status_rest( transport: str = "rest", request_type=compute.GetRouterStatusRouterRequest ): client = RoutersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -949,17 +956,16 @@ def test_get_router_status_rest( ] ), ) + # Wrap the value into a proper Response obj json_return_value = compute.RouterStatusResponse.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_router_status(request) # Establish that the response is the type that we expect. - assert isinstance(response, compute.RouterStatusResponse) assert response.kind == "kind_value" assert response.result == compute.RouterStatus( @@ -972,7 +978,7 @@ def test_get_router_status_rest_from_dict(): def test_get_router_status_rest_flattened(): - client = RoutersClient(credentials=credentials.AnonymousCredentials(),) + client = RoutersClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -997,16 +1003,13 @@ def test_get_router_status_rest_flattened(): 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 "router_value" in http_call[1] + str(body) def test_get_router_status_rest_flattened_error(): - client = RoutersClient(credentials=credentials.AnonymousCredentials(),) + client = RoutersClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1021,7 +1024,7 @@ def test_get_router_status_rest_flattened_error(): def test_insert_rest(transport: str = "rest", request_type=compute.InsertRouterRequest): client = RoutersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1056,17 +1059,16 @@ def test_insert_rest(transport: str = "rest", request_type=compute.InsertRouterR 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" @@ -1100,7 +1102,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = RoutersClient(credentials=credentials.AnonymousCredentials(),) + client = RoutersClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1119,7 +1121,6 @@ def test_insert_rest_flattened(): router_resource = compute.Router( bgp=compute.RouterBgp(advertise_mode=compute.RouterBgp.AdvertiseMode.CUSTOM) ) - client.insert( project="project_value", region="region_value", @@ -1131,11 +1132,8 @@ def test_insert_rest_flattened(): 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.Router.to_json( router_resource, including_default_value_fields=False, @@ -1144,7 +1142,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = RoutersClient(credentials=credentials.AnonymousCredentials(),) + client = RoutersClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1163,7 +1161,7 @@ def test_insert_rest_flattened_error(): def test_list_rest(transport: str = "rest", request_type=compute.ListRoutersRequest): client = RoutersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1187,17 +1185,16 @@ def test_list_rest(transport: str = "rest", request_type=compute.ListRoutersRequ 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.RouterList.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 == [ @@ -1216,7 +1213,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = RoutersClient(credentials=credentials.AnonymousCredentials(),) + client = RoutersClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1241,14 +1238,12 @@ def test_list_rest_flattened(): 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 = RoutersClient(credentials=credentials.AnonymousCredentials(),) + client = RoutersClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1261,12 +1256,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = RoutersClient(credentials=credentials.AnonymousCredentials(),) + client = RoutersClient(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.RouterList( items=[compute.Router(), compute.Router(), compute.Router(),], @@ -1276,7 +1270,6 @@ def test_list_pager(): compute.RouterList(items=[compute.Router(),], next_page_token="ghi",), compute.RouterList(items=[compute.Router(), compute.Router(),],), ) - # Two responses for two calls response = response + response @@ -1295,7 +1288,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.Router) for i in results) pages = list(client.list(request={}).pages) @@ -1305,7 +1297,7 @@ def test_list_pager(): def test_patch_rest(transport: str = "rest", request_type=compute.PatchRouterRequest): client = RoutersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1340,17 +1332,16 @@ def test_patch_rest(transport: str = "rest", request_type=compute.PatchRouterReq 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" @@ -1384,7 +1375,7 @@ def test_patch_rest_from_dict(): def test_patch_rest_flattened(): - client = RoutersClient(credentials=credentials.AnonymousCredentials(),) + client = RoutersClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1403,7 +1394,6 @@ def test_patch_rest_flattened(): router_resource = compute.Router( bgp=compute.RouterBgp(advertise_mode=compute.RouterBgp.AdvertiseMode.CUSTOM) ) - client.patch( project="project_value", region="region_value", @@ -1416,13 +1406,9 @@ def test_patch_rest_flattened(): 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 "router_value" in http_call[1] + str(body) - assert compute.Router.to_json( router_resource, including_default_value_fields=False, @@ -1431,7 +1417,7 @@ def test_patch_rest_flattened(): def test_patch_rest_flattened_error(): - client = RoutersClient(credentials=credentials.AnonymousCredentials(),) + client = RoutersClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1453,7 +1439,7 @@ def test_preview_rest( transport: str = "rest", request_type=compute.PreviewRouterRequest ): client = RoutersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1470,17 +1456,16 @@ def test_preview_rest( ) ), ) + # Wrap the value into a proper Response obj json_return_value = compute.RoutersPreviewResponse.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.preview(request) # Establish that the response is the type that we expect. - assert isinstance(response, compute.RoutersPreviewResponse) assert response.resource == compute.Router( bgp=compute.RouterBgp(advertise_mode=compute.RouterBgp.AdvertiseMode.CUSTOM) @@ -1492,7 +1477,7 @@ def test_preview_rest_from_dict(): def test_preview_rest_flattened(): - client = RoutersClient(credentials=credentials.AnonymousCredentials(),) + client = RoutersClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1511,7 +1496,6 @@ def test_preview_rest_flattened(): router_resource = compute.Router( bgp=compute.RouterBgp(advertise_mode=compute.RouterBgp.AdvertiseMode.CUSTOM) ) - client.preview( project="project_value", region="region_value", @@ -1524,13 +1508,9 @@ def test_preview_rest_flattened(): 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 "router_value" in http_call[1] + str(body) - assert compute.Router.to_json( router_resource, including_default_value_fields=False, @@ -1539,7 +1519,7 @@ def test_preview_rest_flattened(): def test_preview_rest_flattened_error(): - client = RoutersClient(credentials=credentials.AnonymousCredentials(),) + client = RoutersClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1559,7 +1539,7 @@ def test_preview_rest_flattened_error(): def test_update_rest(transport: str = "rest", request_type=compute.UpdateRouterRequest): client = RoutersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1594,17 +1574,16 @@ def test_update_rest(transport: str = "rest", request_type=compute.UpdateRouterR 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.update(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" @@ -1638,7 +1617,7 @@ def test_update_rest_from_dict(): def test_update_rest_flattened(): - client = RoutersClient(credentials=credentials.AnonymousCredentials(),) + client = RoutersClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1657,7 +1636,6 @@ def test_update_rest_flattened(): router_resource = compute.Router( bgp=compute.RouterBgp(advertise_mode=compute.RouterBgp.AdvertiseMode.CUSTOM) ) - client.update( project="project_value", region="region_value", @@ -1670,13 +1648,9 @@ def test_update_rest_flattened(): 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 "router_value" in http_call[1] + str(body) - assert compute.Router.to_json( router_resource, including_default_value_fields=False, @@ -1685,7 +1659,7 @@ def test_update_rest_flattened(): def test_update_rest_flattened_error(): - client = RoutersClient(credentials=credentials.AnonymousCredentials(),) + client = RoutersClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1706,16 +1680,16 @@ def test_update_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.RoutersRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RoutersClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.RoutersRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RoutersClient( @@ -1725,7 +1699,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.RoutersRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RoutersClient( @@ -1736,7 +1710,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.RoutersRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = RoutersClient(transport=transport) assert client.transport is transport @@ -1745,17 +1719,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.RoutersRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_routers_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.RoutersTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1767,7 +1741,7 @@ def test_routers_base_transport(): ) as Transport: Transport.return_value = None transport = transports.RoutersTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1789,15 +1763,40 @@ def test_routers_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_routers_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.routers.transports.RoutersTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RoutersTransport( + 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_routers_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.routers.transports.RoutersTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RoutersTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1813,19 +1812,36 @@ def test_routers_base_transport_with_credentials_file(): def test_routers_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.routers.transports.RoutersTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RoutersTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_routers_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RoutersClient() + 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_routers_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) RoutersClient() adc.assert_called_once_with( scopes=( @@ -1837,7 +1853,7 @@ def test_routers_auth_adc(): def test_routers_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1849,7 +1865,7 @@ def test_routers_http_transport_client_cert_source_for_mtls(): def test_routers_host_no_port(): client = RoutersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1859,7 +1875,7 @@ def test_routers_host_no_port(): def test_routers_host_with_port(): client = RoutersClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1869,7 +1885,6 @@ def test_routers_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1890,7 +1905,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = RoutersClient.common_folder_path(folder) assert expected == actual @@ -1909,7 +1923,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = RoutersClient.common_organization_path(organization) assert expected == actual @@ -1928,7 +1941,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = RoutersClient.common_project_path(project) assert expected == actual @@ -1948,7 +1960,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1975,7 +1986,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.RoutersTransport, "_prep_wrapped_messages" ) as prep: client = RoutersClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1984,6 +1995,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = RoutersClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_routes.py b/tests/unit/gapic/compute_v1/test_routes.py index b55c944ff..63fef8c82 100644 --- a/tests/unit/gapic/compute_v1/test_routes.py +++ b/tests/unit/gapic/compute_v1/test_routes.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,57 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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 +# - 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", +) + +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(): @@ -81,7 +106,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [RoutesClient,]) def test_routes_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -96,7 +121,7 @@ def test_routes_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [RoutesClient,]) def test_routes_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -133,7 +158,7 @@ def test_routes_client_get_transport_class(): def test_routes_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(RoutesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -367,7 +392,7 @@ def test_routes_client_client_options_credentials_file( def test_delete_rest(transport: str = "rest", request_type=compute.DeleteRouteRequest): client = RoutesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -402,17 +427,16 @@ def test_delete_rest(transport: str = "rest", request_type=compute.DeleteRouteRe 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" @@ -446,7 +470,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = RoutesClient(credentials=credentials.AnonymousCredentials(),) + client = RoutesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -471,14 +495,12 @@ def test_delete_rest_flattened(): 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 "route_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = RoutesClient(credentials=credentials.AnonymousCredentials(),) + client = RoutesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -490,7 +512,7 @@ def test_delete_rest_flattened_error(): def test_get_rest(transport: str = "rest", request_type=compute.GetRouteRequest): client = RoutesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -520,17 +542,16 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetRouteRequest) tags=["tags_value"], warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)], ) + # Wrap the value into a proper Response obj json_return_value = compute.Route.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.Route) assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" @@ -559,7 +580,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = RoutesClient(credentials=credentials.AnonymousCredentials(),) + client = RoutesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -584,14 +605,12 @@ def test_get_rest_flattened(): 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 "route_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = RoutesClient(credentials=credentials.AnonymousCredentials(),) + client = RoutesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -603,7 +622,7 @@ def test_get_rest_flattened_error(): def test_insert_rest(transport: str = "rest", request_type=compute.InsertRouteRequest): client = RoutesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -638,17 +657,16 @@ def test_insert_rest(transport: str = "rest", request_type=compute.InsertRouteRe 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" @@ -682,7 +700,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = RoutesClient(credentials=credentials.AnonymousCredentials(),) + client = RoutesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -699,7 +717,6 @@ def test_insert_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. route_resource = compute.Route(creation_timestamp="creation_timestamp_value") - client.insert( project="project_value", route_resource=route_resource, ) @@ -709,9 +726,7 @@ def test_insert_rest_flattened(): 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.Route.to_json( route_resource, including_default_value_fields=False, @@ -720,7 +735,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = RoutesClient(credentials=credentials.AnonymousCredentials(),) + client = RoutesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -734,7 +749,7 @@ def test_insert_rest_flattened_error(): def test_list_rest(transport: str = "rest", request_type=compute.ListRoutesRequest): client = RoutesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -752,17 +767,16 @@ def test_list_rest(transport: str = "rest", request_type=compute.ListRoutesReque 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.RouteList.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 == [ @@ -779,7 +793,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = RoutesClient(credentials=credentials.AnonymousCredentials(),) + client = RoutesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -802,12 +816,11 @@ def test_list_rest_flattened(): 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 = RoutesClient(credentials=credentials.AnonymousCredentials(),) + client = RoutesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -818,12 +831,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = RoutesClient(credentials=credentials.AnonymousCredentials(),) + client = RoutesClient(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.RouteList( items=[compute.Route(), compute.Route(), compute.Route(),], @@ -833,7 +845,6 @@ def test_list_pager(): compute.RouteList(items=[compute.Route(),], next_page_token="ghi",), compute.RouteList(items=[compute.Route(), compute.Route(),],), ) - # Two responses for two calls response = response + response @@ -852,7 +863,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.Route) for i in results) pages = list(client.list(request={}).pages) @@ -863,16 +873,16 @@ def test_list_pager(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.RoutesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RoutesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.RoutesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RoutesClient( @@ -882,7 +892,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.RoutesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = RoutesClient( @@ -893,7 +903,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.RoutesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = RoutesClient(transport=transport) assert client.transport is transport @@ -902,17 +912,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.RoutesRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_routes_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.RoutesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -924,7 +934,7 @@ def test_routes_base_transport(): ) as Transport: Transport.return_value = None transport = transports.RoutesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -940,15 +950,40 @@ def test_routes_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_routes_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.routes.transports.RoutesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RoutesTransport( + 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_routes_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.routes.transports.RoutesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RoutesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -964,19 +999,36 @@ def test_routes_base_transport_with_credentials_file(): def test_routes_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.routes.transports.RoutesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RoutesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_routes_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RoutesClient() + 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_routes_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) RoutesClient() adc.assert_called_once_with( scopes=( @@ -988,7 +1040,7 @@ def test_routes_auth_adc(): def test_routes_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1000,7 +1052,7 @@ def test_routes_http_transport_client_cert_source_for_mtls(): def test_routes_host_no_port(): client = RoutesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1010,7 +1062,7 @@ def test_routes_host_no_port(): def test_routes_host_with_port(): client = RoutesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1020,7 +1072,6 @@ def test_routes_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1041,7 +1092,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = RoutesClient.common_folder_path(folder) assert expected == actual @@ -1060,7 +1110,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = RoutesClient.common_organization_path(organization) assert expected == actual @@ -1079,7 +1128,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = RoutesClient.common_project_path(project) assert expected == actual @@ -1099,7 +1147,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1126,7 +1173,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.RoutesTransport, "_prep_wrapped_messages" ) as prep: client = RoutesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1135,6 +1182,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = RoutesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_security_policies.py b/tests/unit/gapic/compute_v1/test_security_policies.py index 7b13a3ded..85b8e2e43 100644 --- a/tests/unit/gapic/compute_v1/test_security_policies.py +++ b/tests/unit/gapic/compute_v1/test_security_policies.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -88,7 +117,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [SecurityPoliciesClient,]) def test_security_policies_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -103,7 +132,7 @@ def test_security_policies_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [SecurityPoliciesClient,]) def test_security_policies_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -144,7 +173,7 @@ def test_security_policies_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(SecurityPoliciesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -392,7 +421,7 @@ def test_add_rule_rest( transport: str = "rest", request_type=compute.AddRuleSecurityPolicyRequest ): client = SecurityPoliciesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -427,17 +456,16 @@ def test_add_rule_rest( 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" @@ -471,7 +499,7 @@ def test_add_rule_rest_from_dict(): def test_add_rule_rest_flattened(): - client = SecurityPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -490,7 +518,6 @@ def test_add_rule_rest_flattened(): security_policy_rule_resource = compute.SecurityPolicyRule( action="action_value" ) - client.add_rule( project="project_value", security_policy="security_policy_value", @@ -502,11 +529,8 @@ def test_add_rule_rest_flattened(): 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 "security_policy_value" in http_call[1] + str(body) - assert compute.SecurityPolicyRule.to_json( security_policy_rule_resource, including_default_value_fields=False, @@ -515,7 +539,7 @@ def test_add_rule_rest_flattened(): def test_add_rule_rest_flattened_error(): - client = SecurityPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -534,7 +558,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteSecurityPolicyRequest ): client = SecurityPoliciesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -569,17 +593,16 @@ def test_delete_rest( 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" @@ -613,7 +636,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = SecurityPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -638,14 +661,12 @@ def test_delete_rest_flattened(): 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 "security_policy_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = SecurityPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -661,7 +682,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetSecurityPolicyRequest ): client = SecurityPoliciesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -681,17 +702,16 @@ def test_get_rest( rules=[compute.SecurityPolicyRule(action="action_value")], self_link="self_link_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.SecurityPolicy.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.SecurityPolicy) assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" @@ -708,7 +728,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = SecurityPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -733,14 +753,12 @@ def test_get_rest_flattened(): 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 "security_policy_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = SecurityPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -756,7 +774,7 @@ def test_get_rule_rest( transport: str = "rest", request_type=compute.GetRuleSecurityPolicyRequest ): client = SecurityPoliciesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -778,17 +796,16 @@ def test_get_rule_rest( preview=True, priority=898, ) + # Wrap the value into a proper Response obj json_return_value = compute.SecurityPolicyRule.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.SecurityPolicyRule) assert response.action == "action_value" assert response.description == "description_value" @@ -798,7 +815,6 @@ def test_get_rule_rest( src_ip_ranges=["src_ip_ranges_value"] ) ) - assert response.preview is True assert response.priority == 898 @@ -808,7 +824,7 @@ def test_get_rule_rest_from_dict(): def test_get_rule_rest_flattened(): - client = SecurityPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -833,14 +849,12 @@ def test_get_rule_rest_flattened(): 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 "security_policy_value" in http_call[1] + str(body) def test_get_rule_rest_flattened_error(): - client = SecurityPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -856,7 +870,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertSecurityPolicyRequest ): client = SecurityPoliciesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -891,17 +905,16 @@ def test_insert_rest( 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" @@ -935,7 +948,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = SecurityPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -954,7 +967,6 @@ def test_insert_rest_flattened(): security_policy_resource = compute.SecurityPolicy( creation_timestamp="creation_timestamp_value" ) - client.insert( project="project_value", security_policy_resource=security_policy_resource, ) @@ -964,9 +976,7 @@ def test_insert_rest_flattened(): 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.SecurityPolicy.to_json( security_policy_resource, including_default_value_fields=False, @@ -975,7 +985,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = SecurityPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -993,7 +1003,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListSecurityPoliciesRequest ): client = SecurityPoliciesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1012,17 +1022,16 @@ def test_list_rest( 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.SecurityPolicyList.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 == [ @@ -1038,7 +1047,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = SecurityPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1061,12 +1070,11 @@ def test_list_rest_flattened(): 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 = SecurityPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1077,12 +1085,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = SecurityPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityPoliciesClient(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.SecurityPolicyList( items=[ @@ -1100,7 +1107,6 @@ def test_list_pager(): items=[compute.SecurityPolicy(), compute.SecurityPolicy(),], ), ) - # Two responses for two calls response = response + response @@ -1119,7 +1125,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.SecurityPolicy) for i in results) pages = list(client.list(request={}).pages) @@ -1132,7 +1137,7 @@ def test_list_preconfigured_expression_sets_rest( request_type=compute.ListPreconfiguredExpressionSetsSecurityPoliciesRequest, ): client = SecurityPoliciesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1151,6 +1156,7 @@ def test_list_preconfigured_expression_sets_rest( ) ), ) + # Wrap the value into a proper Response obj json_return_value = compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse.to_json( return_value @@ -1159,11 +1165,9 @@ def test_list_preconfigured_expression_sets_rest( response_value.status_code = 200 response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_preconfigured_expression_sets(request) # Establish that the response is the type that we expect. - assert isinstance( response, compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse ) @@ -1179,7 +1183,7 @@ def test_list_preconfigured_expression_sets_rest_from_dict(): def test_list_preconfigured_expression_sets_rest_flattened(): - client = SecurityPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1204,12 +1208,11 @@ def test_list_preconfigured_expression_sets_rest_flattened(): 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_preconfigured_expression_sets_rest_flattened_error(): - client = SecurityPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1224,7 +1227,7 @@ def test_patch_rest( transport: str = "rest", request_type=compute.PatchSecurityPolicyRequest ): client = SecurityPoliciesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1259,17 +1262,16 @@ def test_patch_rest( 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" @@ -1303,7 +1305,7 @@ def test_patch_rest_from_dict(): def test_patch_rest_flattened(): - client = SecurityPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1322,7 +1324,6 @@ def test_patch_rest_flattened(): security_policy_resource = compute.SecurityPolicy( creation_timestamp="creation_timestamp_value" ) - client.patch( project="project_value", security_policy="security_policy_value", @@ -1334,11 +1335,8 @@ def test_patch_rest_flattened(): 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 "security_policy_value" in http_call[1] + str(body) - assert compute.SecurityPolicy.to_json( security_policy_resource, including_default_value_fields=False, @@ -1347,7 +1345,7 @@ def test_patch_rest_flattened(): def test_patch_rest_flattened_error(): - client = SecurityPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1366,7 +1364,7 @@ def test_patch_rule_rest( transport: str = "rest", request_type=compute.PatchRuleSecurityPolicyRequest ): client = SecurityPoliciesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1401,17 +1399,16 @@ def test_patch_rule_rest( 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" @@ -1445,7 +1442,7 @@ def test_patch_rule_rest_from_dict(): def test_patch_rule_rest_flattened(): - client = SecurityPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1464,7 +1461,6 @@ def test_patch_rule_rest_flattened(): security_policy_rule_resource = compute.SecurityPolicyRule( action="action_value" ) - client.patch_rule( project="project_value", security_policy="security_policy_value", @@ -1476,11 +1472,8 @@ def test_patch_rule_rest_flattened(): 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 "security_policy_value" in http_call[1] + str(body) - assert compute.SecurityPolicyRule.to_json( security_policy_rule_resource, including_default_value_fields=False, @@ -1489,7 +1482,7 @@ def test_patch_rule_rest_flattened(): def test_patch_rule_rest_flattened_error(): - client = SecurityPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1508,7 +1501,7 @@ def test_remove_rule_rest( transport: str = "rest", request_type=compute.RemoveRuleSecurityPolicyRequest ): client = SecurityPoliciesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1543,17 +1536,16 @@ def test_remove_rule_rest( 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" @@ -1587,7 +1579,7 @@ def test_remove_rule_rest_from_dict(): def test_remove_rule_rest_flattened(): - client = SecurityPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1612,14 +1604,12 @@ def test_remove_rule_rest_flattened(): 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 "security_policy_value" in http_call[1] + str(body) def test_remove_rule_rest_flattened_error(): - client = SecurityPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1634,16 +1624,16 @@ def test_remove_rule_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SecurityPoliciesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SecurityPoliciesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.SecurityPoliciesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SecurityPoliciesClient( @@ -1653,7 +1643,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.SecurityPoliciesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SecurityPoliciesClient( @@ -1664,7 +1654,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.SecurityPoliciesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = SecurityPoliciesClient(transport=transport) assert client.transport is transport @@ -1673,17 +1663,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.SecurityPoliciesRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_security_policies_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.SecurityPoliciesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1695,7 +1685,7 @@ def test_security_policies_base_transport(): ) as Transport: Transport.return_value = None transport = transports.SecurityPoliciesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1717,15 +1707,40 @@ def test_security_policies_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_security_policies_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.security_policies.transports.SecurityPoliciesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityPoliciesTransport( + 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_security_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.security_policies.transports.SecurityPoliciesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SecurityPoliciesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1741,19 +1756,36 @@ def test_security_policies_base_transport_with_credentials_file(): def test_security_policies_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.security_policies.transports.SecurityPoliciesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SecurityPoliciesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_security_policies_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SecurityPoliciesClient() + 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_security_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) SecurityPoliciesClient() adc.assert_called_once_with( scopes=( @@ -1765,7 +1797,7 @@ def test_security_policies_auth_adc(): def test_security_policies_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1777,7 +1809,7 @@ def test_security_policies_http_transport_client_cert_source_for_mtls(): def test_security_policies_host_no_port(): client = SecurityPoliciesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1787,7 +1819,7 @@ def test_security_policies_host_no_port(): def test_security_policies_host_with_port(): client = SecurityPoliciesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1797,7 +1829,6 @@ def test_security_policies_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1818,7 +1849,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = SecurityPoliciesClient.common_folder_path(folder) assert expected == actual @@ -1837,7 +1867,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = SecurityPoliciesClient.common_organization_path(organization) assert expected == actual @@ -1856,7 +1885,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = SecurityPoliciesClient.common_project_path(project) assert expected == actual @@ -1876,7 +1904,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1903,7 +1930,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.SecurityPoliciesTransport, "_prep_wrapped_messages" ) as prep: client = SecurityPoliciesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1912,6 +1939,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = SecurityPoliciesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_snapshots.py b/tests/unit/gapic/compute_v1/test_snapshots.py index e57542eac..3e5d6dd2c 100644 --- a/tests/unit/gapic/compute_v1/test_snapshots.py +++ b/tests/unit/gapic/compute_v1/test_snapshots.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,59 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -82,7 +109,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [SnapshotsClient,]) def test_snapshots_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -97,7 +124,7 @@ def test_snapshots_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [SnapshotsClient,]) def test_snapshots_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -134,7 +161,7 @@ def test_snapshots_client_get_transport_class(): def test_snapshots_client_client_options(client_class, transport_class, transport_name): # Check that if channel is provided we won't create a new one. with mock.patch.object(SnapshotsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -370,7 +397,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteSnapshotRequest ): client = SnapshotsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -405,17 +432,16 @@ def test_delete_rest( 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" @@ -449,7 +475,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = SnapshotsClient(credentials=credentials.AnonymousCredentials(),) + client = SnapshotsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -474,14 +500,12 @@ def test_delete_rest_flattened(): 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 "snapshot_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = SnapshotsClient(credentials=credentials.AnonymousCredentials(),) + client = SnapshotsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -495,7 +519,7 @@ def test_delete_rest_flattened_error(): def test_get_rest(transport: str = "rest", request_type=compute.GetSnapshotRequest): client = SnapshotsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -533,19 +557,17 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetSnapshotReque storage_bytes_status=compute.Snapshot.StorageBytesStatus.UPDATING, storage_locations=["storage_locations_value"], ) + # Wrap the value into a proper Response obj json_return_value = compute.Snapshot.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.Snapshot) - assert response.auto_created is True assert response.chain_name == "chain_name_value" assert response.creation_timestamp == "creation_timestamp_value" @@ -579,7 +601,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = SnapshotsClient(credentials=credentials.AnonymousCredentials(),) + client = SnapshotsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -604,14 +626,12 @@ def test_get_rest_flattened(): 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 "snapshot_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = SnapshotsClient(credentials=credentials.AnonymousCredentials(),) + client = SnapshotsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -627,7 +647,7 @@ def test_get_iam_policy_rest( transport: str = "rest", request_type=compute.GetIamPolicySnapshotRequest ): client = SnapshotsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -653,17 +673,16 @@ def test_get_iam_policy_rest( 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( @@ -674,7 +693,6 @@ def test_get_iam_policy_rest( ] 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 @@ -685,7 +703,7 @@ def test_get_iam_policy_rest_from_dict(): def test_get_iam_policy_rest_flattened(): - client = SnapshotsClient(credentials=credentials.AnonymousCredentials(),) + client = SnapshotsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -710,14 +728,12 @@ def test_get_iam_policy_rest_flattened(): 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) def test_get_iam_policy_rest_flattened_error(): - client = SnapshotsClient(credentials=credentials.AnonymousCredentials(),) + client = SnapshotsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -731,7 +747,7 @@ def test_get_iam_policy_rest_flattened_error(): def test_list_rest(transport: str = "rest", request_type=compute.ListSnapshotsRequest): client = SnapshotsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -749,17 +765,16 @@ def test_list_rest(transport: str = "rest", request_type=compute.ListSnapshotsRe 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.SnapshotList.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.Snapshot(auto_created=True)] @@ -774,7 +789,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = SnapshotsClient(credentials=credentials.AnonymousCredentials(),) + client = SnapshotsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -797,12 +812,11 @@ def test_list_rest_flattened(): 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 = SnapshotsClient(credentials=credentials.AnonymousCredentials(),) + client = SnapshotsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -813,12 +827,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = SnapshotsClient(credentials=credentials.AnonymousCredentials(),) + client = SnapshotsClient(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.SnapshotList( items=[compute.Snapshot(), compute.Snapshot(), compute.Snapshot(),], @@ -828,7 +841,6 @@ def test_list_pager(): compute.SnapshotList(items=[compute.Snapshot(),], next_page_token="ghi",), compute.SnapshotList(items=[compute.Snapshot(), compute.Snapshot(),],), ) - # Two responses for two calls response = response + response @@ -847,7 +859,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.Snapshot) for i in results) pages = list(client.list(request={}).pages) @@ -859,7 +870,7 @@ def test_set_iam_policy_rest( transport: str = "rest", request_type=compute.SetIamPolicySnapshotRequest ): client = SnapshotsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -885,17 +896,16 @@ def test_set_iam_policy_rest( 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( @@ -906,7 +916,6 @@ def test_set_iam_policy_rest( ] 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 @@ -917,7 +926,7 @@ def test_set_iam_policy_rest_from_dict(): def test_set_iam_policy_rest_flattened(): - client = SnapshotsClient(credentials=credentials.AnonymousCredentials(),) + client = SnapshotsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -936,7 +945,6 @@ def test_set_iam_policy_rest_flattened(): global_set_policy_request_resource = compute.GlobalSetPolicyRequest( bindings=[compute.Binding(binding_id="binding_id_value")] ) - client.set_iam_policy( project="project_value", resource="resource_value", @@ -948,11 +956,8 @@ def test_set_iam_policy_rest_flattened(): 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.GlobalSetPolicyRequest.to_json( global_set_policy_request_resource, including_default_value_fields=False, @@ -961,7 +966,7 @@ def test_set_iam_policy_rest_flattened(): def test_set_iam_policy_rest_flattened_error(): - client = SnapshotsClient(credentials=credentials.AnonymousCredentials(),) + client = SnapshotsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -980,7 +985,7 @@ def test_set_labels_rest( transport: str = "rest", request_type=compute.SetLabelsSnapshotRequest ): client = SnapshotsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1015,17 +1020,16 @@ def test_set_labels_rest( 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" @@ -1059,7 +1063,7 @@ def test_set_labels_rest_from_dict(): def test_set_labels_rest_flattened(): - client = SnapshotsClient(credentials=credentials.AnonymousCredentials(),) + client = SnapshotsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1078,7 +1082,6 @@ def test_set_labels_rest_flattened(): global_set_labels_request_resource = compute.GlobalSetLabelsRequest( label_fingerprint="label_fingerprint_value" ) - client.set_labels( project="project_value", resource="resource_value", @@ -1090,11 +1093,8 @@ def test_set_labels_rest_flattened(): 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, @@ -1103,7 +1103,7 @@ def test_set_labels_rest_flattened(): def test_set_labels_rest_flattened_error(): - client = SnapshotsClient(credentials=credentials.AnonymousCredentials(),) + client = SnapshotsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1122,7 +1122,7 @@ def test_test_iam_permissions_rest( transport: str = "rest", request_type=compute.TestIamPermissionsSnapshotRequest ): client = SnapshotsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1135,17 +1135,16 @@ def test_test_iam_permissions_rest( 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"] @@ -1155,7 +1154,7 @@ def test_test_iam_permissions_rest_from_dict(): def test_test_iam_permissions_rest_flattened(): - client = SnapshotsClient(credentials=credentials.AnonymousCredentials(),) + client = SnapshotsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1174,7 +1173,6 @@ def test_test_iam_permissions_rest_flattened(): test_permissions_request_resource = compute.TestPermissionsRequest( permissions=["permissions_value"] ) - client.test_iam_permissions( project="project_value", resource="resource_value", @@ -1186,11 +1184,8 @@ def test_test_iam_permissions_rest_flattened(): 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.TestPermissionsRequest.to_json( test_permissions_request_resource, including_default_value_fields=False, @@ -1199,7 +1194,7 @@ def test_test_iam_permissions_rest_flattened(): def test_test_iam_permissions_rest_flattened_error(): - client = SnapshotsClient(credentials=credentials.AnonymousCredentials(),) + client = SnapshotsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1217,16 +1212,16 @@ def test_test_iam_permissions_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SnapshotsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SnapshotsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.SnapshotsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SnapshotsClient( @@ -1236,7 +1231,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.SnapshotsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SnapshotsClient( @@ -1247,7 +1242,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.SnapshotsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = SnapshotsClient(transport=transport) assert client.transport is transport @@ -1256,17 +1251,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.SnapshotsRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_snapshots_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.SnapshotsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1278,7 +1273,7 @@ def test_snapshots_base_transport(): ) as Transport: Transport.return_value = None transport = transports.SnapshotsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1297,15 +1292,40 @@ def test_snapshots_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_snapshots_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.snapshots.transports.SnapshotsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SnapshotsTransport( + 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_snapshots_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.snapshots.transports.SnapshotsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SnapshotsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1321,19 +1341,36 @@ def test_snapshots_base_transport_with_credentials_file(): def test_snapshots_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.snapshots.transports.SnapshotsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SnapshotsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_snapshots_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SnapshotsClient() + 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_snapshots_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) SnapshotsClient() adc.assert_called_once_with( scopes=( @@ -1345,7 +1382,7 @@ def test_snapshots_auth_adc(): def test_snapshots_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1357,7 +1394,7 @@ def test_snapshots_http_transport_client_cert_source_for_mtls(): def test_snapshots_host_no_port(): client = SnapshotsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1367,7 +1404,7 @@ def test_snapshots_host_no_port(): def test_snapshots_host_with_port(): client = SnapshotsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1377,7 +1414,6 @@ def test_snapshots_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1398,7 +1434,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = SnapshotsClient.common_folder_path(folder) assert expected == actual @@ -1417,7 +1452,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = SnapshotsClient.common_organization_path(organization) assert expected == actual @@ -1436,7 +1470,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = SnapshotsClient.common_project_path(project) assert expected == actual @@ -1456,7 +1489,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1483,7 +1515,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.SnapshotsTransport, "_prep_wrapped_messages" ) as prep: client = SnapshotsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1492,6 +1524,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = SnapshotsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_ssl_certificates.py b/tests/unit/gapic/compute_v1/test_ssl_certificates.py index fffb64b51..4cc2ddf82 100644 --- a/tests/unit/gapic/compute_v1/test_ssl_certificates.py +++ b/tests/unit/gapic/compute_v1/test_ssl_certificates.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -87,7 +116,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [SslCertificatesClient,]) def test_ssl_certificates_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -102,7 +131,7 @@ def test_ssl_certificates_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [SslCertificatesClient,]) def test_ssl_certificates_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -143,7 +172,7 @@ def test_ssl_certificates_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(SslCertificatesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -391,7 +420,7 @@ def test_aggregated_list_rest( transport: str = "rest", request_type=compute.AggregatedListSslCertificatesRequest ): client = SslCertificatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -416,17 +445,16 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.SslCertificateAggregatedList.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 == { @@ -446,7 +474,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = SslCertificatesClient(credentials=credentials.AnonymousCredentials(),) + client = SslCertificatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -469,12 +497,11 @@ def test_aggregated_list_rest_flattened(): 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 = SslCertificatesClient(credentials=credentials.AnonymousCredentials(),) + client = SslCertificatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -485,12 +512,11 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = SslCertificatesClient(credentials=credentials.AnonymousCredentials(),) + client = SslCertificatesClient(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.SslCertificateAggregatedList( items={ @@ -512,7 +538,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -536,7 +561,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -557,7 +581,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteSslCertificateRequest ): client = SslCertificatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -592,17 +616,16 @@ def test_delete_rest( 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" @@ -636,7 +659,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = SslCertificatesClient(credentials=credentials.AnonymousCredentials(),) + client = SslCertificatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -661,14 +684,12 @@ def test_delete_rest_flattened(): 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 "ssl_certificate_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = SslCertificatesClient(credentials=credentials.AnonymousCredentials(),) + client = SslCertificatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -684,7 +705,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetSslCertificateRequest ): client = SslCertificatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -714,17 +735,16 @@ def test_get_rest( subject_alternative_names=["subject_alternative_names_value"], type_=compute.SslCertificate.Type.MANAGED, ) + # Wrap the value into a proper Response obj json_return_value = compute.SslCertificate.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.SslCertificate) assert response.certificate == "certificate_value" assert response.creation_timestamp == "creation_timestamp_value" @@ -751,7 +771,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = SslCertificatesClient(credentials=credentials.AnonymousCredentials(),) + client = SslCertificatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -776,14 +796,12 @@ def test_get_rest_flattened(): 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 "ssl_certificate_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = SslCertificatesClient(credentials=credentials.AnonymousCredentials(),) + client = SslCertificatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -799,7 +817,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertSslCertificateRequest ): client = SslCertificatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -834,17 +852,16 @@ def test_insert_rest( 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" @@ -878,7 +895,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = SslCertificatesClient(credentials=credentials.AnonymousCredentials(),) + client = SslCertificatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -897,7 +914,6 @@ def test_insert_rest_flattened(): ssl_certificate_resource = compute.SslCertificate( certificate="certificate_value" ) - client.insert( project="project_value", ssl_certificate_resource=ssl_certificate_resource, ) @@ -907,9 +923,7 @@ def test_insert_rest_flattened(): 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.SslCertificate.to_json( ssl_certificate_resource, including_default_value_fields=False, @@ -918,7 +932,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = SslCertificatesClient(credentials=credentials.AnonymousCredentials(),) + client = SslCertificatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -936,7 +950,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListSslCertificatesRequest ): client = SslCertificatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -954,17 +968,16 @@ def test_list_rest( 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.SslCertificateList.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.SslCertificate(certificate="certificate_value")] @@ -979,7 +992,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = SslCertificatesClient(credentials=credentials.AnonymousCredentials(),) + client = SslCertificatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1002,12 +1015,11 @@ def test_list_rest_flattened(): 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 = SslCertificatesClient(credentials=credentials.AnonymousCredentials(),) + client = SslCertificatesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1018,12 +1030,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = SslCertificatesClient(credentials=credentials.AnonymousCredentials(),) + client = SslCertificatesClient(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.SslCertificateList( items=[ @@ -1041,7 +1052,6 @@ def test_list_pager(): items=[compute.SslCertificate(), compute.SslCertificate(),], ), ) - # Two responses for two calls response = response + response @@ -1060,7 +1070,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.SslCertificate) for i in results) pages = list(client.list(request={}).pages) @@ -1071,16 +1080,16 @@ def test_list_pager(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SslCertificatesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SslCertificatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.SslCertificatesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SslCertificatesClient( @@ -1090,7 +1099,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.SslCertificatesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SslCertificatesClient( @@ -1101,7 +1110,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.SslCertificatesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = SslCertificatesClient(transport=transport) assert client.transport is transport @@ -1110,17 +1119,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.SslCertificatesRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_ssl_certificates_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.SslCertificatesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1132,7 +1141,7 @@ def test_ssl_certificates_base_transport(): ) as Transport: Transport.return_value = None transport = transports.SslCertificatesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1149,15 +1158,40 @@ def test_ssl_certificates_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_ssl_certificates_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.ssl_certificates.transports.SslCertificatesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SslCertificatesTransport( + 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_ssl_certificates_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.ssl_certificates.transports.SslCertificatesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SslCertificatesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1173,19 +1207,36 @@ def test_ssl_certificates_base_transport_with_credentials_file(): def test_ssl_certificates_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.ssl_certificates.transports.SslCertificatesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SslCertificatesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_ssl_certificates_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SslCertificatesClient() + 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_ssl_certificates_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) SslCertificatesClient() adc.assert_called_once_with( scopes=( @@ -1197,7 +1248,7 @@ def test_ssl_certificates_auth_adc(): def test_ssl_certificates_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1209,7 +1260,7 @@ def test_ssl_certificates_http_transport_client_cert_source_for_mtls(): def test_ssl_certificates_host_no_port(): client = SslCertificatesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1219,7 +1270,7 @@ def test_ssl_certificates_host_no_port(): def test_ssl_certificates_host_with_port(): client = SslCertificatesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1229,7 +1280,6 @@ def test_ssl_certificates_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1250,7 +1300,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = SslCertificatesClient.common_folder_path(folder) assert expected == actual @@ -1269,7 +1318,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = SslCertificatesClient.common_organization_path(organization) assert expected == actual @@ -1288,7 +1336,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = SslCertificatesClient.common_project_path(project) assert expected == actual @@ -1308,7 +1355,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1335,7 +1381,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.SslCertificatesTransport, "_prep_wrapped_messages" ) as prep: client = SslCertificatesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1344,6 +1390,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = SslCertificatesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_ssl_policies.py b/tests/unit/gapic/compute_v1/test_ssl_policies.py index b616d865b..845a11bd4 100644 --- a/tests/unit/gapic/compute_v1/test_ssl_policies.py +++ b/tests/unit/gapic/compute_v1/test_ssl_policies.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -84,7 +113,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [SslPoliciesClient,]) def test_ssl_policies_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -99,7 +128,7 @@ def test_ssl_policies_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [SslPoliciesClient,]) def test_ssl_policies_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -138,7 +167,7 @@ def test_ssl_policies_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(SslPoliciesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -374,7 +403,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteSslPolicyRequest ): client = SslPoliciesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -409,17 +438,16 @@ def test_delete_rest( 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" @@ -453,7 +481,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = SslPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SslPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -478,14 +506,12 @@ def test_delete_rest_flattened(): 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 "ssl_policy_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = SslPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SslPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -499,7 +525,7 @@ def test_delete_rest_flattened_error(): def test_get_rest(transport: str = "rest", request_type=compute.GetSslPolicyRequest): client = SslPoliciesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -523,17 +549,16 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetSslPolicyRequ self_link="self_link_value", warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)], ) + # Wrap the value into a proper Response obj json_return_value = compute.SslPolicy.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.SslPolicy) assert response.creation_timestamp == "creation_timestamp_value" assert response.custom_features == ["custom_features_value"] @@ -556,7 +581,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = SslPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SslPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -581,14 +606,12 @@ def test_get_rest_flattened(): 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 "ssl_policy_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = SslPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SslPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -604,7 +627,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertSslPolicyRequest ): client = SslPoliciesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -639,17 +662,16 @@ def test_insert_rest( 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" @@ -683,7 +705,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = SslPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SslPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -702,7 +724,6 @@ def test_insert_rest_flattened(): ssl_policy_resource = compute.SslPolicy( creation_timestamp="creation_timestamp_value" ) - client.insert( project="project_value", ssl_policy_resource=ssl_policy_resource, ) @@ -712,9 +733,7 @@ def test_insert_rest_flattened(): 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.SslPolicy.to_json( ssl_policy_resource, including_default_value_fields=False, @@ -723,7 +742,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = SslPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SslPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -741,7 +760,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListSslPoliciesRequest ): client = SslPoliciesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -759,17 +778,16 @@ def test_list_rest( 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.SslPoliciesList.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 == [ @@ -786,7 +804,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = SslPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SslPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -809,12 +827,11 @@ def test_list_rest_flattened(): 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 = SslPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SslPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -825,12 +842,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = SslPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SslPoliciesClient(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.SslPoliciesList( items=[compute.SslPolicy(), compute.SslPolicy(), compute.SslPolicy(),], @@ -842,7 +858,6 @@ def test_list_pager(): ), compute.SslPoliciesList(items=[compute.SslPolicy(), compute.SslPolicy(),],), ) - # Two responses for two calls response = response + response @@ -861,7 +876,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.SslPolicy) for i in results) pages = list(client.list(request={}).pages) @@ -874,7 +888,7 @@ def test_list_available_features_rest( request_type=compute.ListAvailableFeaturesSslPoliciesRequest, ): client = SslPoliciesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -887,6 +901,7 @@ def test_list_available_features_rest( return_value = compute.SslPoliciesListAvailableFeaturesResponse( features=["features_value"], ) + # Wrap the value into a proper Response obj json_return_value = compute.SslPoliciesListAvailableFeaturesResponse.to_json( return_value @@ -895,11 +910,9 @@ def test_list_available_features_rest( response_value.status_code = 200 response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_available_features(request) # Establish that the response is the type that we expect. - assert isinstance(response, compute.SslPoliciesListAvailableFeaturesResponse) assert response.features == ["features_value"] @@ -909,7 +922,7 @@ def test_list_available_features_rest_from_dict(): def test_list_available_features_rest_flattened(): - client = SslPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SslPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -934,12 +947,11 @@ def test_list_available_features_rest_flattened(): 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_available_features_rest_flattened_error(): - client = SslPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SslPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -953,7 +965,7 @@ def test_patch_rest( transport: str = "rest", request_type=compute.PatchSslPolicyRequest ): client = SslPoliciesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -988,17 +1000,16 @@ def test_patch_rest( 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" @@ -1032,7 +1043,7 @@ def test_patch_rest_from_dict(): def test_patch_rest_flattened(): - client = SslPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SslPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1051,7 +1062,6 @@ def test_patch_rest_flattened(): ssl_policy_resource = compute.SslPolicy( creation_timestamp="creation_timestamp_value" ) - client.patch( project="project_value", ssl_policy="ssl_policy_value", @@ -1063,11 +1073,8 @@ def test_patch_rest_flattened(): 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 "ssl_policy_value" in http_call[1] + str(body) - assert compute.SslPolicy.to_json( ssl_policy_resource, including_default_value_fields=False, @@ -1076,7 +1083,7 @@ def test_patch_rest_flattened(): def test_patch_rest_flattened_error(): - client = SslPoliciesClient(credentials=credentials.AnonymousCredentials(),) + client = SslPoliciesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1094,16 +1101,16 @@ def test_patch_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SslPoliciesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SslPoliciesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.SslPoliciesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SslPoliciesClient( @@ -1113,7 +1120,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.SslPoliciesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SslPoliciesClient( @@ -1124,7 +1131,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.SslPoliciesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = SslPoliciesClient(transport=transport) assert client.transport is transport @@ -1133,17 +1140,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.SslPoliciesRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_ssl_policies_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.SslPoliciesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1155,7 +1162,7 @@ def test_ssl_policies_base_transport(): ) as Transport: Transport.return_value = None transport = transports.SslPoliciesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1173,15 +1180,40 @@ def test_ssl_policies_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_ssl_policies_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.ssl_policies.transports.SslPoliciesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SslPoliciesTransport( + 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_ssl_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.ssl_policies.transports.SslPoliciesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SslPoliciesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1197,19 +1229,36 @@ def test_ssl_policies_base_transport_with_credentials_file(): def test_ssl_policies_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.ssl_policies.transports.SslPoliciesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SslPoliciesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_ssl_policies_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SslPoliciesClient() + 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_ssl_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) SslPoliciesClient() adc.assert_called_once_with( scopes=( @@ -1221,7 +1270,7 @@ def test_ssl_policies_auth_adc(): def test_ssl_policies_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1233,7 +1282,7 @@ def test_ssl_policies_http_transport_client_cert_source_for_mtls(): def test_ssl_policies_host_no_port(): client = SslPoliciesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1243,7 +1292,7 @@ def test_ssl_policies_host_no_port(): def test_ssl_policies_host_with_port(): client = SslPoliciesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1253,7 +1302,6 @@ def test_ssl_policies_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1274,7 +1322,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = SslPoliciesClient.common_folder_path(folder) assert expected == actual @@ -1293,7 +1340,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = SslPoliciesClient.common_organization_path(organization) assert expected == actual @@ -1312,7 +1358,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = SslPoliciesClient.common_project_path(project) assert expected == actual @@ -1332,7 +1377,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1359,7 +1403,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.SslPoliciesTransport, "_prep_wrapped_messages" ) as prep: client = SslPoliciesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1368,6 +1412,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = SslPoliciesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_subnetworks.py b/tests/unit/gapic/compute_v1/test_subnetworks.py index 2a4f056b0..5502d59de 100644 --- a/tests/unit/gapic/compute_v1/test_subnetworks.py +++ b/tests/unit/gapic/compute_v1/test_subnetworks.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -84,7 +113,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [SubnetworksClient,]) def test_subnetworks_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -99,7 +128,7 @@ def test_subnetworks_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [SubnetworksClient,]) def test_subnetworks_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -138,7 +167,7 @@ def test_subnetworks_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(SubnetworksClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -374,7 +403,7 @@ def test_aggregated_list_rest( transport: str = "rest", request_type=compute.AggregatedListSubnetworksRequest ): client = SubnetworksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -401,17 +430,16 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.SubnetworkAggregatedList.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 == { @@ -433,7 +461,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = SubnetworksClient(credentials=credentials.AnonymousCredentials(),) + client = SubnetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -456,12 +484,11 @@ def test_aggregated_list_rest_flattened(): 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 = SubnetworksClient(credentials=credentials.AnonymousCredentials(),) + client = SubnetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -472,12 +499,11 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = SubnetworksClient(credentials=credentials.AnonymousCredentials(),) + client = SubnetworksClient(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.SubnetworkAggregatedList( items={ @@ -498,7 +524,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -520,7 +545,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -541,7 +565,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteSubnetworkRequest ): client = SubnetworksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -576,17 +600,16 @@ def test_delete_rest( 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" @@ -620,7 +643,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = SubnetworksClient(credentials=credentials.AnonymousCredentials(),) + client = SubnetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -647,16 +670,13 @@ def test_delete_rest_flattened(): 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 "subnetwork_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = SubnetworksClient(credentials=credentials.AnonymousCredentials(),) + client = SubnetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -673,7 +693,7 @@ def test_expand_ip_cidr_range_rest( transport: str = "rest", request_type=compute.ExpandIpCidrRangeSubnetworkRequest ): client = SubnetworksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -708,17 +728,16 @@ def test_expand_ip_cidr_range_rest( 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.expand_ip_cidr_range(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" @@ -752,7 +771,7 @@ def test_expand_ip_cidr_range_rest_from_dict(): def test_expand_ip_cidr_range_rest_flattened(): - client = SubnetworksClient(credentials=credentials.AnonymousCredentials(),) + client = SubnetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -771,7 +790,6 @@ def test_expand_ip_cidr_range_rest_flattened(): subnetworks_expand_ip_cidr_range_request_resource = compute.SubnetworksExpandIpCidrRangeRequest( ip_cidr_range="ip_cidr_range_value" ) - client.expand_ip_cidr_range( project="project_value", region="region_value", @@ -784,13 +802,9 @@ def test_expand_ip_cidr_range_rest_flattened(): 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 "subnetwork_value" in http_call[1] + str(body) - assert compute.SubnetworksExpandIpCidrRangeRequest.to_json( subnetworks_expand_ip_cidr_range_request_resource, including_default_value_fields=False, @@ -799,7 +813,7 @@ def test_expand_ip_cidr_range_rest_flattened(): def test_expand_ip_cidr_range_rest_flattened_error(): - client = SubnetworksClient(credentials=credentials.AnonymousCredentials(),) + client = SubnetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -817,7 +831,7 @@ def test_expand_ip_cidr_range_rest_flattened_error(): def test_get_rest(transport: str = "rest", request_type=compute.GetSubnetworkRequest): client = SubnetworksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -853,21 +867,19 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetSubnetworkReq self_link="self_link_value", state=compute.Subnetwork.State.DRAINING, ) + # Wrap the value into a proper Response obj json_return_value = compute.Subnetwork.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.Subnetwork) assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" - assert response.enable_flow_logs is True assert response.fingerprint == "fingerprint_value" assert response.gateway_address == "gateway_address_value" @@ -880,7 +892,6 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetSubnetworkReq ) assert response.name == "name_value" assert response.network == "network_value" - assert response.private_ip_google_access is True assert ( response.private_ipv6_google_access @@ -901,7 +912,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = SubnetworksClient(credentials=credentials.AnonymousCredentials(),) + client = SubnetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -928,16 +939,13 @@ def test_get_rest_flattened(): 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 "subnetwork_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = SubnetworksClient(credentials=credentials.AnonymousCredentials(),) + client = SubnetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -954,7 +962,7 @@ def test_get_iam_policy_rest( transport: str = "rest", request_type=compute.GetIamPolicySubnetworkRequest ): client = SubnetworksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -980,17 +988,16 @@ def test_get_iam_policy_rest( 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( @@ -1001,7 +1008,6 @@ def test_get_iam_policy_rest( ] 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 @@ -1012,7 +1018,7 @@ def test_get_iam_policy_rest_from_dict(): def test_get_iam_policy_rest_flattened(): - client = SubnetworksClient(credentials=credentials.AnonymousCredentials(),) + client = SubnetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1037,16 +1043,13 @@ def test_get_iam_policy_rest_flattened(): 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) def test_get_iam_policy_rest_flattened_error(): - client = SubnetworksClient(credentials=credentials.AnonymousCredentials(),) + client = SubnetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1063,7 +1066,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertSubnetworkRequest ): client = SubnetworksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1098,17 +1101,16 @@ def test_insert_rest( 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" @@ -1142,7 +1144,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = SubnetworksClient(credentials=credentials.AnonymousCredentials(),) + client = SubnetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1161,7 +1163,6 @@ def test_insert_rest_flattened(): subnetwork_resource = compute.Subnetwork( creation_timestamp="creation_timestamp_value" ) - client.insert( project="project_value", region="region_value", @@ -1173,11 +1174,8 @@ def test_insert_rest_flattened(): 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.Subnetwork.to_json( subnetwork_resource, including_default_value_fields=False, @@ -1186,7 +1184,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = SubnetworksClient(credentials=credentials.AnonymousCredentials(),) + client = SubnetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1205,7 +1203,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListSubnetworksRequest ): client = SubnetworksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1223,17 +1221,16 @@ def test_list_rest( 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.SubnetworkList.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 == [ @@ -1250,7 +1247,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = SubnetworksClient(credentials=credentials.AnonymousCredentials(),) + client = SubnetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1275,14 +1272,12 @@ def test_list_rest_flattened(): 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 = SubnetworksClient(credentials=credentials.AnonymousCredentials(),) + client = SubnetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1295,12 +1290,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = SubnetworksClient(credentials=credentials.AnonymousCredentials(),) + client = SubnetworksClient(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.SubnetworkList( items=[ @@ -1318,7 +1312,6 @@ def test_list_pager(): items=[compute.Subnetwork(), compute.Subnetwork(),], ), ) - # Two responses for two calls response = response + response @@ -1337,7 +1330,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.Subnetwork) for i in results) pages = list(client.list(request={}).pages) @@ -1349,7 +1341,7 @@ def test_list_usable_rest( transport: str = "rest", request_type=compute.ListUsableSubnetworksRequest ): client = SubnetworksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1367,6 +1359,7 @@ def test_list_usable_rest( 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.UsableSubnetworksAggregatedList.to_json( return_value @@ -1375,11 +1368,9 @@ def test_list_usable_rest( response_value.status_code = 200 response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_usable(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsablePager) assert response.id == "id_value" assert response.items == [ @@ -1396,7 +1387,7 @@ def test_list_usable_rest_from_dict(): def test_list_usable_rest_flattened(): - client = SubnetworksClient(credentials=credentials.AnonymousCredentials(),) + client = SubnetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1421,12 +1412,11 @@ def test_list_usable_rest_flattened(): 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_usable_rest_flattened_error(): - client = SubnetworksClient(credentials=credentials.AnonymousCredentials(),) + client = SubnetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1437,12 +1427,11 @@ def test_list_usable_rest_flattened_error(): def test_list_usable_pager(): - client = SubnetworksClient(credentials=credentials.AnonymousCredentials(),) + client = SubnetworksClient(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.UsableSubnetworksAggregatedList( items=[ @@ -1460,7 +1449,6 @@ def test_list_usable_pager(): items=[compute.UsableSubnetwork(), compute.UsableSubnetwork(),], ), ) - # Two responses for two calls response = response + response @@ -1481,7 +1469,6 @@ def test_list_usable_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.UsableSubnetwork) for i in results) pages = list(client.list_usable(request={}).pages) @@ -1493,7 +1480,7 @@ def test_patch_rest( transport: str = "rest", request_type=compute.PatchSubnetworkRequest ): client = SubnetworksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1528,17 +1515,16 @@ def test_patch_rest( 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" @@ -1572,7 +1558,7 @@ def test_patch_rest_from_dict(): def test_patch_rest_flattened(): - client = SubnetworksClient(credentials=credentials.AnonymousCredentials(),) + client = SubnetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1591,7 +1577,6 @@ def test_patch_rest_flattened(): subnetwork_resource = compute.Subnetwork( creation_timestamp="creation_timestamp_value" ) - client.patch( project="project_value", region="region_value", @@ -1604,13 +1589,9 @@ def test_patch_rest_flattened(): 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 "subnetwork_value" in http_call[1] + str(body) - assert compute.Subnetwork.to_json( subnetwork_resource, including_default_value_fields=False, @@ -1619,7 +1600,7 @@ def test_patch_rest_flattened(): def test_patch_rest_flattened_error(): - client = SubnetworksClient(credentials=credentials.AnonymousCredentials(),) + client = SubnetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1639,7 +1620,7 @@ def test_set_iam_policy_rest( transport: str = "rest", request_type=compute.SetIamPolicySubnetworkRequest ): client = SubnetworksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1665,17 +1646,16 @@ def test_set_iam_policy_rest( 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( @@ -1686,7 +1666,6 @@ def test_set_iam_policy_rest( ] 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 @@ -1697,7 +1676,7 @@ def test_set_iam_policy_rest_from_dict(): def test_set_iam_policy_rest_flattened(): - client = SubnetworksClient(credentials=credentials.AnonymousCredentials(),) + client = SubnetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1716,7 +1695,6 @@ def test_set_iam_policy_rest_flattened(): region_set_policy_request_resource = compute.RegionSetPolicyRequest( bindings=[compute.Binding(binding_id="binding_id_value")] ) - client.set_iam_policy( project="project_value", region="region_value", @@ -1729,13 +1707,9 @@ def test_set_iam_policy_rest_flattened(): 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.RegionSetPolicyRequest.to_json( region_set_policy_request_resource, including_default_value_fields=False, @@ -1744,7 +1718,7 @@ def test_set_iam_policy_rest_flattened(): def test_set_iam_policy_rest_flattened_error(): - client = SubnetworksClient(credentials=credentials.AnonymousCredentials(),) + client = SubnetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1765,7 +1739,7 @@ def test_set_private_ip_google_access_rest( request_type=compute.SetPrivateIpGoogleAccessSubnetworkRequest, ): client = SubnetworksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1800,17 +1774,16 @@ def test_set_private_ip_google_access_rest( 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_private_ip_google_access(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" @@ -1844,7 +1817,7 @@ def test_set_private_ip_google_access_rest_from_dict(): def test_set_private_ip_google_access_rest_flattened(): - client = SubnetworksClient(credentials=credentials.AnonymousCredentials(),) + client = SubnetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1863,7 +1836,6 @@ def test_set_private_ip_google_access_rest_flattened(): subnetworks_set_private_ip_google_access_request_resource = compute.SubnetworksSetPrivateIpGoogleAccessRequest( private_ip_google_access=True ) - client.set_private_ip_google_access( project="project_value", region="region_value", @@ -1876,13 +1848,9 @@ def test_set_private_ip_google_access_rest_flattened(): 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 "subnetwork_value" in http_call[1] + str(body) - assert compute.SubnetworksSetPrivateIpGoogleAccessRequest.to_json( subnetworks_set_private_ip_google_access_request_resource, including_default_value_fields=False, @@ -1891,7 +1859,7 @@ def test_set_private_ip_google_access_rest_flattened(): def test_set_private_ip_google_access_rest_flattened_error(): - client = SubnetworksClient(credentials=credentials.AnonymousCredentials(),) + client = SubnetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1911,7 +1879,7 @@ def test_test_iam_permissions_rest( transport: str = "rest", request_type=compute.TestIamPermissionsSubnetworkRequest ): client = SubnetworksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1924,17 +1892,16 @@ def test_test_iam_permissions_rest( 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"] @@ -1944,7 +1911,7 @@ def test_test_iam_permissions_rest_from_dict(): def test_test_iam_permissions_rest_flattened(): - client = SubnetworksClient(credentials=credentials.AnonymousCredentials(),) + client = SubnetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1963,7 +1930,6 @@ def test_test_iam_permissions_rest_flattened(): test_permissions_request_resource = compute.TestPermissionsRequest( permissions=["permissions_value"] ) - client.test_iam_permissions( project="project_value", region="region_value", @@ -1976,13 +1942,9 @@ def test_test_iam_permissions_rest_flattened(): 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.TestPermissionsRequest.to_json( test_permissions_request_resource, including_default_value_fields=False, @@ -1991,7 +1953,7 @@ def test_test_iam_permissions_rest_flattened(): def test_test_iam_permissions_rest_flattened_error(): - client = SubnetworksClient(credentials=credentials.AnonymousCredentials(),) + client = SubnetworksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2010,16 +1972,16 @@ def test_test_iam_permissions_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SubnetworksRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SubnetworksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.SubnetworksRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SubnetworksClient( @@ -2029,7 +1991,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.SubnetworksRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SubnetworksClient( @@ -2040,7 +2002,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.SubnetworksRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = SubnetworksClient(transport=transport) assert client.transport is transport @@ -2049,17 +2011,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.SubnetworksRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_subnetworks_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.SubnetworksTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2071,7 +2033,7 @@ def test_subnetworks_base_transport(): ) as Transport: Transport.return_value = None transport = transports.SubnetworksTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2095,15 +2057,40 @@ def test_subnetworks_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_subnetworks_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.subnetworks.transports.SubnetworksTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SubnetworksTransport( + 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_subnetworks_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.subnetworks.transports.SubnetworksTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SubnetworksTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2119,19 +2106,36 @@ def test_subnetworks_base_transport_with_credentials_file(): def test_subnetworks_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.subnetworks.transports.SubnetworksTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SubnetworksTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_subnetworks_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SubnetworksClient() + 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_subnetworks_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) SubnetworksClient() adc.assert_called_once_with( scopes=( @@ -2143,7 +2147,7 @@ def test_subnetworks_auth_adc(): def test_subnetworks_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -2155,7 +2159,7 @@ def test_subnetworks_http_transport_client_cert_source_for_mtls(): def test_subnetworks_host_no_port(): client = SubnetworksClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -2165,7 +2169,7 @@ def test_subnetworks_host_no_port(): def test_subnetworks_host_with_port(): client = SubnetworksClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -2175,7 +2179,6 @@ def test_subnetworks_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2196,7 +2199,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = SubnetworksClient.common_folder_path(folder) assert expected == actual @@ -2215,7 +2217,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = SubnetworksClient.common_organization_path(organization) assert expected == actual @@ -2234,7 +2235,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = SubnetworksClient.common_project_path(project) assert expected == actual @@ -2254,7 +2254,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2281,7 +2280,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.SubnetworksTransport, "_prep_wrapped_messages" ) as prep: client = SubnetworksClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2290,6 +2289,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = SubnetworksClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_target_grpc_proxies.py b/tests/unit/gapic/compute_v1/test_target_grpc_proxies.py index 7e44a27b4..5fd2bb1d2 100644 --- a/tests/unit/gapic/compute_v1/test_target_grpc_proxies.py +++ b/tests/unit/gapic/compute_v1/test_target_grpc_proxies.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -88,7 +117,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [TargetGrpcProxiesClient,]) def test_target_grpc_proxies_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -103,7 +132,7 @@ def test_target_grpc_proxies_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [TargetGrpcProxiesClient,]) def test_target_grpc_proxies_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -144,7 +173,7 @@ def test_target_grpc_proxies_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(TargetGrpcProxiesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -392,7 +421,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteTargetGrpcProxyRequest ): client = TargetGrpcProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -427,17 +456,16 @@ def test_delete_rest( 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" @@ -471,7 +499,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = TargetGrpcProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetGrpcProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -496,14 +524,12 @@ def test_delete_rest_flattened(): 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_grpc_proxy_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = TargetGrpcProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetGrpcProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -519,7 +545,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetTargetGrpcProxyRequest ): client = TargetGrpcProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -541,17 +567,16 @@ def test_get_rest( url_map="url_map_value", validate_for_proxyless=True, ) + # Wrap the value into a proper Response obj json_return_value = compute.TargetGrpcProxy.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.TargetGrpcProxy) assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" @@ -562,7 +587,6 @@ def test_get_rest( assert response.self_link == "self_link_value" assert response.self_link_with_id == "self_link_with_id_value" assert response.url_map == "url_map_value" - assert response.validate_for_proxyless is True @@ -571,7 +595,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = TargetGrpcProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetGrpcProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -596,14 +620,12 @@ def test_get_rest_flattened(): 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_grpc_proxy_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = TargetGrpcProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetGrpcProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -619,7 +641,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertTargetGrpcProxyRequest ): client = TargetGrpcProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -654,17 +676,16 @@ def test_insert_rest( 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" @@ -698,7 +719,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = TargetGrpcProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetGrpcProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -717,7 +738,6 @@ def test_insert_rest_flattened(): target_grpc_proxy_resource = compute.TargetGrpcProxy( creation_timestamp="creation_timestamp_value" ) - client.insert( project="project_value", target_grpc_proxy_resource=target_grpc_proxy_resource, @@ -728,9 +748,7 @@ def test_insert_rest_flattened(): 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.TargetGrpcProxy.to_json( target_grpc_proxy_resource, including_default_value_fields=False, @@ -739,7 +757,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = TargetGrpcProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetGrpcProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -757,7 +775,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListTargetGrpcProxiesRequest ): client = TargetGrpcProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -777,17 +795,16 @@ def test_list_rest( 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.TargetGrpcProxyList.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 == [ @@ -804,7 +821,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = TargetGrpcProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetGrpcProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -827,12 +844,11 @@ def test_list_rest_flattened(): 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 = TargetGrpcProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetGrpcProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -843,12 +859,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = TargetGrpcProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetGrpcProxiesClient(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.TargetGrpcProxyList( items=[ @@ -866,7 +881,6 @@ def test_list_pager(): items=[compute.TargetGrpcProxy(), compute.TargetGrpcProxy(),], ), ) - # Two responses for two calls response = response + response @@ -885,7 +899,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.TargetGrpcProxy) for i in results) pages = list(client.list(request={}).pages) @@ -897,7 +910,7 @@ def test_patch_rest( transport: str = "rest", request_type=compute.PatchTargetGrpcProxyRequest ): client = TargetGrpcProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -932,17 +945,16 @@ def test_patch_rest( 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" @@ -976,7 +988,7 @@ def test_patch_rest_from_dict(): def test_patch_rest_flattened(): - client = TargetGrpcProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetGrpcProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -995,7 +1007,6 @@ def test_patch_rest_flattened(): target_grpc_proxy_resource = compute.TargetGrpcProxy( creation_timestamp="creation_timestamp_value" ) - client.patch( project="project_value", target_grpc_proxy="target_grpc_proxy_value", @@ -1007,11 +1018,8 @@ def test_patch_rest_flattened(): 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_grpc_proxy_value" in http_call[1] + str(body) - assert compute.TargetGrpcProxy.to_json( target_grpc_proxy_resource, including_default_value_fields=False, @@ -1020,7 +1028,7 @@ def test_patch_rest_flattened(): def test_patch_rest_flattened_error(): - client = TargetGrpcProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetGrpcProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1038,16 +1046,16 @@ def test_patch_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.TargetGrpcProxiesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TargetGrpcProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.TargetGrpcProxiesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TargetGrpcProxiesClient( @@ -1057,7 +1065,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.TargetGrpcProxiesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TargetGrpcProxiesClient( @@ -1068,7 +1076,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.TargetGrpcProxiesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = TargetGrpcProxiesClient(transport=transport) assert client.transport is transport @@ -1079,17 +1087,17 @@ def test_transport_instance(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_target_grpc_proxies_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.TargetGrpcProxiesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1101,7 +1109,7 @@ def test_target_grpc_proxies_base_transport(): ) as Transport: Transport.return_value = None transport = transports.TargetGrpcProxiesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1118,15 +1126,40 @@ def test_target_grpc_proxies_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_target_grpc_proxies_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.target_grpc_proxies.transports.TargetGrpcProxiesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TargetGrpcProxiesTransport( + 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_target_grpc_proxies_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.target_grpc_proxies.transports.TargetGrpcProxiesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.TargetGrpcProxiesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1142,19 +1175,36 @@ def test_target_grpc_proxies_base_transport_with_credentials_file(): def test_target_grpc_proxies_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.target_grpc_proxies.transports.TargetGrpcProxiesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.TargetGrpcProxiesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_target_grpc_proxies_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + TargetGrpcProxiesClient() + 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_target_grpc_proxies_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) TargetGrpcProxiesClient() adc.assert_called_once_with( scopes=( @@ -1166,7 +1216,7 @@ def test_target_grpc_proxies_auth_adc(): def test_target_grpc_proxies_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1178,7 +1228,7 @@ def test_target_grpc_proxies_http_transport_client_cert_source_for_mtls(): def test_target_grpc_proxies_host_no_port(): client = TargetGrpcProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1188,7 +1238,7 @@ def test_target_grpc_proxies_host_no_port(): def test_target_grpc_proxies_host_with_port(): client = TargetGrpcProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1198,7 +1248,6 @@ def test_target_grpc_proxies_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1219,7 +1268,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = TargetGrpcProxiesClient.common_folder_path(folder) assert expected == actual @@ -1238,7 +1286,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = TargetGrpcProxiesClient.common_organization_path(organization) assert expected == actual @@ -1257,7 +1304,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = TargetGrpcProxiesClient.common_project_path(project) assert expected == actual @@ -1277,7 +1323,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1304,7 +1349,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.TargetGrpcProxiesTransport, "_prep_wrapped_messages" ) as prep: client = TargetGrpcProxiesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1313,6 +1358,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = TargetGrpcProxiesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_target_http_proxies.py b/tests/unit/gapic/compute_v1/test_target_http_proxies.py index 7e9f95478..379a93a82 100644 --- a/tests/unit/gapic/compute_v1/test_target_http_proxies.py +++ b/tests/unit/gapic/compute_v1/test_target_http_proxies.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -88,7 +117,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [TargetHttpProxiesClient,]) def test_target_http_proxies_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -103,7 +132,7 @@ def test_target_http_proxies_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [TargetHttpProxiesClient,]) def test_target_http_proxies_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -144,7 +173,7 @@ def test_target_http_proxies_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(TargetHttpProxiesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -392,7 +421,7 @@ def test_aggregated_list_rest( transport: str = "rest", request_type=compute.AggregatedListTargetHttpProxiesRequest ): client = TargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -418,17 +447,16 @@ def test_aggregated_list_rest( self_link="self_link_value", unreachables=["unreachables_value"], ) + # Wrap the value into a proper Response obj json_return_value = compute.TargetHttpProxyAggregatedList.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 == { @@ -449,7 +477,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = TargetHttpProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetHttpProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -472,12 +500,11 @@ def test_aggregated_list_rest_flattened(): 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 = TargetHttpProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetHttpProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -488,12 +515,11 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = TargetHttpProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetHttpProxiesClient(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.TargetHttpProxyAggregatedList( items={ @@ -515,7 +541,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -539,7 +564,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -560,7 +584,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteTargetHttpProxyRequest ): client = TargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -595,17 +619,16 @@ def test_delete_rest( 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" @@ -639,7 +662,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = TargetHttpProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetHttpProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -664,14 +687,12 @@ def test_delete_rest_flattened(): 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_http_proxy_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = TargetHttpProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetHttpProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -687,7 +708,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetTargetHttpProxyRequest ): client = TargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -709,17 +730,16 @@ def test_get_rest( self_link="self_link_value", url_map="url_map_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.TargetHttpProxy.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.TargetHttpProxy) assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" @@ -727,7 +747,6 @@ 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.region == "region_value" assert response.self_link == "self_link_value" @@ -739,7 +758,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = TargetHttpProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetHttpProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -764,14 +783,12 @@ def test_get_rest_flattened(): 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_http_proxy_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = TargetHttpProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetHttpProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -787,7 +804,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertTargetHttpProxyRequest ): client = TargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -822,17 +839,16 @@ def test_insert_rest( 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" @@ -866,7 +882,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = TargetHttpProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetHttpProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -885,7 +901,6 @@ def test_insert_rest_flattened(): target_http_proxy_resource = compute.TargetHttpProxy( creation_timestamp="creation_timestamp_value" ) - client.insert( project="project_value", target_http_proxy_resource=target_http_proxy_resource, @@ -896,9 +911,7 @@ def test_insert_rest_flattened(): 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.TargetHttpProxy.to_json( target_http_proxy_resource, including_default_value_fields=False, @@ -907,7 +920,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = TargetHttpProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetHttpProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -925,7 +938,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListTargetHttpProxiesRequest ): client = TargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -945,17 +958,16 @@ def test_list_rest( 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.TargetHttpProxyList.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 == [ @@ -972,7 +984,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = TargetHttpProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetHttpProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -995,12 +1007,11 @@ def test_list_rest_flattened(): 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 = TargetHttpProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetHttpProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1011,12 +1022,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = TargetHttpProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetHttpProxiesClient(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.TargetHttpProxyList( items=[ @@ -1034,7 +1044,6 @@ def test_list_pager(): items=[compute.TargetHttpProxy(), compute.TargetHttpProxy(),], ), ) - # Two responses for two calls response = response + response @@ -1053,7 +1062,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.TargetHttpProxy) for i in results) pages = list(client.list(request={}).pages) @@ -1065,7 +1073,7 @@ def test_patch_rest( transport: str = "rest", request_type=compute.PatchTargetHttpProxyRequest ): client = TargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1100,17 +1108,16 @@ def test_patch_rest( 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" @@ -1144,7 +1151,7 @@ def test_patch_rest_from_dict(): def test_patch_rest_flattened(): - client = TargetHttpProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetHttpProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1163,7 +1170,6 @@ def test_patch_rest_flattened(): target_http_proxy_resource = compute.TargetHttpProxy( creation_timestamp="creation_timestamp_value" ) - client.patch( project="project_value", target_http_proxy="target_http_proxy_value", @@ -1175,11 +1181,8 @@ def test_patch_rest_flattened(): 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_http_proxy_value" in http_call[1] + str(body) - assert compute.TargetHttpProxy.to_json( target_http_proxy_resource, including_default_value_fields=False, @@ -1188,7 +1191,7 @@ def test_patch_rest_flattened(): def test_patch_rest_flattened_error(): - client = TargetHttpProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetHttpProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1207,7 +1210,7 @@ def test_set_url_map_rest( transport: str = "rest", request_type=compute.SetUrlMapTargetHttpProxyRequest ): client = TargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1242,17 +1245,16 @@ def test_set_url_map_rest( 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_url_map(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" @@ -1286,7 +1288,7 @@ def test_set_url_map_rest_from_dict(): def test_set_url_map_rest_flattened(): - client = TargetHttpProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetHttpProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1303,7 +1305,6 @@ def test_set_url_map_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. url_map_reference_resource = compute.UrlMapReference(url_map="url_map_value") - client.set_url_map( project="project_value", target_http_proxy="target_http_proxy_value", @@ -1315,11 +1316,8 @@ def test_set_url_map_rest_flattened(): 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_http_proxy_value" in http_call[1] + str(body) - assert compute.UrlMapReference.to_json( url_map_reference_resource, including_default_value_fields=False, @@ -1328,7 +1326,7 @@ def test_set_url_map_rest_flattened(): def test_set_url_map_rest_flattened_error(): - client = TargetHttpProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetHttpProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1344,16 +1342,16 @@ def test_set_url_map_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.TargetHttpProxiesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.TargetHttpProxiesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TargetHttpProxiesClient( @@ -1363,7 +1361,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.TargetHttpProxiesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TargetHttpProxiesClient( @@ -1374,7 +1372,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.TargetHttpProxiesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = TargetHttpProxiesClient(transport=transport) assert client.transport is transport @@ -1385,17 +1383,17 @@ def test_transport_instance(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_target_http_proxies_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.TargetHttpProxiesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1407,7 +1405,7 @@ def test_target_http_proxies_base_transport(): ) as Transport: Transport.return_value = None transport = transports.TargetHttpProxiesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1426,15 +1424,40 @@ def test_target_http_proxies_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_target_http_proxies_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.target_http_proxies.transports.TargetHttpProxiesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TargetHttpProxiesTransport( + 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_target_http_proxies_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.target_http_proxies.transports.TargetHttpProxiesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.TargetHttpProxiesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1450,19 +1473,36 @@ def test_target_http_proxies_base_transport_with_credentials_file(): def test_target_http_proxies_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.target_http_proxies.transports.TargetHttpProxiesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.TargetHttpProxiesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_target_http_proxies_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + TargetHttpProxiesClient() + 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_target_http_proxies_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) TargetHttpProxiesClient() adc.assert_called_once_with( scopes=( @@ -1474,7 +1514,7 @@ def test_target_http_proxies_auth_adc(): def test_target_http_proxies_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1486,7 +1526,7 @@ def test_target_http_proxies_http_transport_client_cert_source_for_mtls(): def test_target_http_proxies_host_no_port(): client = TargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1496,7 +1536,7 @@ def test_target_http_proxies_host_no_port(): def test_target_http_proxies_host_with_port(): client = TargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1506,7 +1546,6 @@ def test_target_http_proxies_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1527,7 +1566,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = TargetHttpProxiesClient.common_folder_path(folder) assert expected == actual @@ -1546,7 +1584,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = TargetHttpProxiesClient.common_organization_path(organization) assert expected == actual @@ -1565,7 +1602,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = TargetHttpProxiesClient.common_project_path(project) assert expected == actual @@ -1585,7 +1621,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1612,7 +1647,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.TargetHttpProxiesTransport, "_prep_wrapped_messages" ) as prep: client = TargetHttpProxiesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1621,6 +1656,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = TargetHttpProxiesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_target_https_proxies.py b/tests/unit/gapic/compute_v1/test_target_https_proxies.py index a3d5cbd16..10ccf7f81 100644 --- a/tests/unit/gapic/compute_v1/test_target_https_proxies.py +++ b/tests/unit/gapic/compute_v1/test_target_https_proxies.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,33 +13,63 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.compute_v1.services.target_https_proxies import ( TargetHttpsProxiesClient, ) 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, +) 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 +# - 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", +) + +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(): @@ -90,7 +119,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [TargetHttpsProxiesClient,]) def test_target_https_proxies_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -105,7 +134,7 @@ def test_target_https_proxies_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [TargetHttpsProxiesClient,]) def test_target_https_proxies_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -146,7 +175,7 @@ def test_target_https_proxies_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(TargetHttpsProxiesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -395,7 +424,7 @@ def test_aggregated_list_rest( request_type=compute.AggregatedListTargetHttpsProxiesRequest, ): client = TargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -422,17 +451,16 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.TargetHttpsProxyAggregatedList.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 == { @@ -456,7 +484,9 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = TargetHttpsProxiesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -479,12 +509,13 @@ def test_aggregated_list_rest_flattened(): 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 = TargetHttpsProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetHttpsProxiesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -495,12 +526,13 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = TargetHttpsProxiesClient(credentials=credentials.AnonymousCredentials(),) + 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: # Set the response as a series of pages - response = ( compute.TargetHttpsProxyAggregatedList( items={ @@ -522,7 +554,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -546,7 +577,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -567,7 +597,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteTargetHttpsProxyRequest ): client = TargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -602,17 +632,16 @@ def test_delete_rest( 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" @@ -646,7 +675,9 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = TargetHttpsProxiesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -671,14 +702,14 @@ def test_delete_rest_flattened(): 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) def test_delete_rest_flattened_error(): - client = TargetHttpsProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetHttpsProxiesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -694,7 +725,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetTargetHttpsProxyRequest ): client = TargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -720,17 +751,16 @@ def test_get_rest( ssl_policy="ssl_policy_value", url_map="url_map_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.TargetHttpsProxy.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.TargetHttpsProxy) assert response.authorization_policy == "authorization_policy_value" assert response.creation_timestamp == "creation_timestamp_value" @@ -738,7 +768,6 @@ 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.quic_override == compute.TargetHttpsProxy.QuicOverride.DISABLE assert response.region == "region_value" @@ -754,7 +783,9 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = TargetHttpsProxiesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -779,14 +810,14 @@ def test_get_rest_flattened(): 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) def test_get_rest_flattened_error(): - client = TargetHttpsProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetHttpsProxiesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -802,7 +833,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertTargetHttpsProxyRequest ): client = TargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -837,17 +868,16 @@ def test_insert_rest( 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" @@ -881,7 +911,9 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = TargetHttpsProxiesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -900,7 +932,6 @@ def test_insert_rest_flattened(): target_https_proxy_resource = compute.TargetHttpsProxy( authorization_policy="authorization_policy_value" ) - client.insert( project="project_value", target_https_proxy_resource=target_https_proxy_resource, @@ -911,9 +942,7 @@ def test_insert_rest_flattened(): 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.TargetHttpsProxy.to_json( target_https_proxy_resource, including_default_value_fields=False, @@ -922,7 +951,9 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = TargetHttpsProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetHttpsProxiesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -940,7 +971,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListTargetHttpsProxiesRequest ): client = TargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -962,17 +993,16 @@ def test_list_rest( 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.TargetHttpsProxyList.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 == [ @@ -989,7 +1019,9 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = TargetHttpsProxiesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -1012,12 +1044,13 @@ def test_list_rest_flattened(): 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 = TargetHttpsProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetHttpsProxiesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1028,12 +1061,13 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = TargetHttpsProxiesClient(credentials=credentials.AnonymousCredentials(),) + 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: # Set the response as a series of pages - response = ( compute.TargetHttpsProxyList( items=[ @@ -1051,7 +1085,6 @@ def test_list_pager(): items=[compute.TargetHttpsProxy(), compute.TargetHttpsProxy(),], ), ) - # Two responses for two calls response = response + response @@ -1070,7 +1103,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.TargetHttpsProxy) for i in results) pages = list(client.list(request={}).pages) @@ -1082,7 +1114,7 @@ def test_set_quic_override_rest( transport: str = "rest", request_type=compute.SetQuicOverrideTargetHttpsProxyRequest ): client = TargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1117,17 +1149,16 @@ def test_set_quic_override_rest( 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_quic_override(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" @@ -1161,7 +1192,9 @@ def test_set_quic_override_rest_from_dict(): def test_set_quic_override_rest_flattened(): - client = TargetHttpsProxiesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -1180,7 +1213,6 @@ def test_set_quic_override_rest_flattened(): target_https_proxies_set_quic_override_request_resource = compute.TargetHttpsProxiesSetQuicOverrideRequest( quic_override=compute.TargetHttpsProxiesSetQuicOverrideRequest.QuicOverride.DISABLE ) - client.set_quic_override( project="project_value", target_https_proxy="target_https_proxy_value", @@ -1192,11 +1224,8 @@ def test_set_quic_override_rest_flattened(): 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.TargetHttpsProxiesSetQuicOverrideRequest.to_json( target_https_proxies_set_quic_override_request_resource, including_default_value_fields=False, @@ -1205,7 +1234,9 @@ def test_set_quic_override_rest_flattened(): def test_set_quic_override_rest_flattened_error(): - client = TargetHttpsProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetHttpsProxiesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1225,7 +1256,7 @@ def test_set_ssl_certificates_rest( request_type=compute.SetSslCertificatesTargetHttpsProxyRequest, ): client = TargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1260,17 +1291,16 @@ def test_set_ssl_certificates_rest( 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_ssl_certificates(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" @@ -1304,7 +1334,9 @@ def test_set_ssl_certificates_rest_from_dict(): def test_set_ssl_certificates_rest_flattened(): - client = TargetHttpsProxiesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -1323,7 +1355,6 @@ def test_set_ssl_certificates_rest_flattened(): target_https_proxies_set_ssl_certificates_request_resource = compute.TargetHttpsProxiesSetSslCertificatesRequest( ssl_certificates=["ssl_certificates_value"] ) - client.set_ssl_certificates( project="project_value", target_https_proxy="target_https_proxy_value", @@ -1335,11 +1366,8 @@ def test_set_ssl_certificates_rest_flattened(): 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.TargetHttpsProxiesSetSslCertificatesRequest.to_json( target_https_proxies_set_ssl_certificates_request_resource, including_default_value_fields=False, @@ -1348,7 +1376,9 @@ def test_set_ssl_certificates_rest_flattened(): def test_set_ssl_certificates_rest_flattened_error(): - client = TargetHttpsProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetHttpsProxiesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1367,7 +1397,7 @@ def test_set_ssl_policy_rest( transport: str = "rest", request_type=compute.SetSslPolicyTargetHttpsProxyRequest ): client = TargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1402,17 +1432,16 @@ def test_set_ssl_policy_rest( 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_ssl_policy(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" @@ -1446,7 +1475,9 @@ def test_set_ssl_policy_rest_from_dict(): def test_set_ssl_policy_rest_flattened(): - client = TargetHttpsProxiesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -1465,7 +1496,6 @@ def test_set_ssl_policy_rest_flattened(): ssl_policy_reference_resource = compute.SslPolicyReference( ssl_policy="ssl_policy_value" ) - client.set_ssl_policy( project="project_value", target_https_proxy="target_https_proxy_value", @@ -1477,11 +1507,8 @@ def test_set_ssl_policy_rest_flattened(): 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.SslPolicyReference.to_json( ssl_policy_reference_resource, including_default_value_fields=False, @@ -1490,7 +1517,9 @@ def test_set_ssl_policy_rest_flattened(): def test_set_ssl_policy_rest_flattened_error(): - client = TargetHttpsProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetHttpsProxiesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1509,7 +1538,7 @@ def test_set_url_map_rest( transport: str = "rest", request_type=compute.SetUrlMapTargetHttpsProxyRequest ): client = TargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1544,17 +1573,16 @@ def test_set_url_map_rest( 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_url_map(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" @@ -1588,7 +1616,9 @@ def test_set_url_map_rest_from_dict(): def test_set_url_map_rest_flattened(): - client = TargetHttpsProxiesClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -1605,7 +1635,6 @@ def test_set_url_map_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. url_map_reference_resource = compute.UrlMapReference(url_map="url_map_value") - client.set_url_map( project="project_value", target_https_proxy="target_https_proxy_value", @@ -1617,11 +1646,8 @@ def test_set_url_map_rest_flattened(): 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.UrlMapReference.to_json( url_map_reference_resource, including_default_value_fields=False, @@ -1630,7 +1656,9 @@ def test_set_url_map_rest_flattened(): def test_set_url_map_rest_flattened_error(): - client = TargetHttpsProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetHttpsProxiesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1646,16 +1674,16 @@ def test_set_url_map_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.TargetHttpsProxiesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.TargetHttpsProxiesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TargetHttpsProxiesClient( @@ -1665,7 +1693,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.TargetHttpsProxiesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TargetHttpsProxiesClient( @@ -1676,7 +1704,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.TargetHttpsProxiesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = TargetHttpsProxiesClient(transport=transport) assert client.transport is transport @@ -1687,17 +1715,17 @@ def test_transport_instance(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_target_https_proxies_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.TargetHttpsProxiesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1709,7 +1737,7 @@ def test_target_https_proxies_base_transport(): ) as Transport: Transport.return_value = None transport = transports.TargetHttpsProxiesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1730,15 +1758,40 @@ def test_target_https_proxies_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_target_https_proxies_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.target_https_proxies.transports.TargetHttpsProxiesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TargetHttpsProxiesTransport( + 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_target_https_proxies_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.target_https_proxies.transports.TargetHttpsProxiesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.TargetHttpsProxiesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1754,19 +1807,36 @@ def test_target_https_proxies_base_transport_with_credentials_file(): def test_target_https_proxies_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.target_https_proxies.transports.TargetHttpsProxiesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.TargetHttpsProxiesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_target_https_proxies_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + TargetHttpsProxiesClient() + 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_target_https_proxies_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) TargetHttpsProxiesClient() adc.assert_called_once_with( scopes=( @@ -1778,7 +1848,7 @@ def test_target_https_proxies_auth_adc(): def test_target_https_proxies_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1790,7 +1860,7 @@ def test_target_https_proxies_http_transport_client_cert_source_for_mtls(): def test_target_https_proxies_host_no_port(): client = TargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1800,7 +1870,7 @@ def test_target_https_proxies_host_no_port(): def test_target_https_proxies_host_with_port(): client = TargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1810,7 +1880,6 @@ def test_target_https_proxies_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1831,7 +1900,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = TargetHttpsProxiesClient.common_folder_path(folder) assert expected == actual @@ -1850,7 +1918,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = TargetHttpsProxiesClient.common_organization_path(organization) assert expected == actual @@ -1869,7 +1936,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = TargetHttpsProxiesClient.common_project_path(project) assert expected == actual @@ -1889,7 +1955,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1916,7 +1981,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.TargetHttpsProxiesTransport, "_prep_wrapped_messages" ) as prep: client = TargetHttpsProxiesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1925,6 +1990,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = TargetHttpsProxiesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_target_instances.py b/tests/unit/gapic/compute_v1/test_target_instances.py index 0ff77fe75..1c8099e93 100644 --- a/tests/unit/gapic/compute_v1/test_target_instances.py +++ b/tests/unit/gapic/compute_v1/test_target_instances.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -87,7 +116,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [TargetInstancesClient,]) def test_target_instances_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -102,7 +131,7 @@ def test_target_instances_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [TargetInstancesClient,]) def test_target_instances_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -143,7 +172,7 @@ def test_target_instances_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(TargetInstancesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -391,7 +420,7 @@ def test_aggregated_list_rest( transport: str = "rest", request_type=compute.AggregatedListTargetInstancesRequest ): client = TargetInstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -418,17 +447,16 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.TargetInstanceAggregatedList.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 == { @@ -450,7 +478,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = TargetInstancesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetInstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -473,12 +501,11 @@ def test_aggregated_list_rest_flattened(): 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 = TargetInstancesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetInstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -489,12 +516,11 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = TargetInstancesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetInstancesClient(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.TargetInstanceAggregatedList( items={ @@ -516,7 +542,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -540,7 +565,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -561,7 +585,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteTargetInstanceRequest ): client = TargetInstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -596,17 +620,16 @@ def test_delete_rest( 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" @@ -640,7 +663,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = TargetInstancesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetInstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -667,16 +690,13 @@ def test_delete_rest_flattened(): 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 "target_instance_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = TargetInstancesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetInstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -693,7 +713,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetTargetInstanceRequest ): client = TargetInstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -714,17 +734,16 @@ def test_get_rest( self_link="self_link_value", zone="zone_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.TargetInstance.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.TargetInstance) assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" @@ -742,7 +761,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = TargetInstancesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetInstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -769,16 +788,13 @@ def test_get_rest_flattened(): 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 "target_instance_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = TargetInstancesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetInstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -795,7 +811,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertTargetInstanceRequest ): client = TargetInstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -830,17 +846,16 @@ def test_insert_rest( 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" @@ -874,7 +889,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = TargetInstancesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetInstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -893,7 +908,6 @@ def test_insert_rest_flattened(): target_instance_resource = compute.TargetInstance( creation_timestamp="creation_timestamp_value" ) - client.insert( project="project_value", zone="zone_value", @@ -905,11 +919,8 @@ def test_insert_rest_flattened(): 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.TargetInstance.to_json( target_instance_resource, including_default_value_fields=False, @@ -918,7 +929,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = TargetInstancesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetInstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -937,7 +948,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListTargetInstancesRequest ): client = TargetInstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -957,17 +968,16 @@ def test_list_rest( 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.TargetInstanceList.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 == [ @@ -984,7 +994,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = TargetInstancesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetInstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1009,14 +1019,12 @@ def test_list_rest_flattened(): 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) def test_list_rest_flattened_error(): - client = TargetInstancesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetInstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1029,12 +1037,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = TargetInstancesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetInstancesClient(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.TargetInstanceList( items=[ @@ -1052,7 +1059,6 @@ def test_list_pager(): items=[compute.TargetInstance(), compute.TargetInstance(),], ), ) - # Two responses for two calls response = response + response @@ -1071,7 +1077,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.TargetInstance) for i in results) pages = list(client.list(request={}).pages) @@ -1082,16 +1087,16 @@ def test_list_pager(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.TargetInstancesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TargetInstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.TargetInstancesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TargetInstancesClient( @@ -1101,7 +1106,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.TargetInstancesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TargetInstancesClient( @@ -1112,7 +1117,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.TargetInstancesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = TargetInstancesClient(transport=transport) assert client.transport is transport @@ -1121,17 +1126,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.TargetInstancesRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_target_instances_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.TargetInstancesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1143,7 +1148,7 @@ def test_target_instances_base_transport(): ) as Transport: Transport.return_value = None transport = transports.TargetInstancesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1160,15 +1165,40 @@ def test_target_instances_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_target_instances_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.target_instances.transports.TargetInstancesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TargetInstancesTransport( + 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_target_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.target_instances.transports.TargetInstancesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.TargetInstancesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1184,19 +1214,36 @@ def test_target_instances_base_transport_with_credentials_file(): def test_target_instances_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.target_instances.transports.TargetInstancesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.TargetInstancesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_target_instances_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + TargetInstancesClient() + 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_target_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) TargetInstancesClient() adc.assert_called_once_with( scopes=( @@ -1208,7 +1255,7 @@ def test_target_instances_auth_adc(): def test_target_instances_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1220,7 +1267,7 @@ def test_target_instances_http_transport_client_cert_source_for_mtls(): def test_target_instances_host_no_port(): client = TargetInstancesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1230,7 +1277,7 @@ def test_target_instances_host_no_port(): def test_target_instances_host_with_port(): client = TargetInstancesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1240,7 +1287,6 @@ def test_target_instances_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1261,7 +1307,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = TargetInstancesClient.common_folder_path(folder) assert expected == actual @@ -1280,7 +1325,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = TargetInstancesClient.common_organization_path(organization) assert expected == actual @@ -1299,7 +1343,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = TargetInstancesClient.common_project_path(project) assert expected == actual @@ -1319,7 +1362,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1346,7 +1388,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.TargetInstancesTransport, "_prep_wrapped_messages" ) as prep: client = TargetInstancesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1355,6 +1397,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = TargetInstancesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_target_pools.py b/tests/unit/gapic/compute_v1/test_target_pools.py index db7f01f3d..e34ef3b29 100644 --- a/tests/unit/gapic/compute_v1/test_target_pools.py +++ b/tests/unit/gapic/compute_v1/test_target_pools.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -84,7 +113,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [TargetPoolsClient,]) def test_target_pools_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -99,7 +128,7 @@ def test_target_pools_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [TargetPoolsClient,]) def test_target_pools_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -138,7 +167,7 @@ def test_target_pools_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(TargetPoolsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -374,7 +403,7 @@ def test_add_health_check_rest( transport: str = "rest", request_type=compute.AddHealthCheckTargetPoolRequest ): client = TargetPoolsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -409,17 +438,16 @@ def test_add_health_check_rest( 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_health_check(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" @@ -453,7 +481,7 @@ def test_add_health_check_rest_from_dict(): def test_add_health_check_rest_flattened(): - client = TargetPoolsClient(credentials=credentials.AnonymousCredentials(),) + client = TargetPoolsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -474,7 +502,6 @@ def test_add_health_check_rest_flattened(): compute.HealthCheckReference(health_check="health_check_value") ] ) - client.add_health_check( project="project_value", region="region_value", @@ -487,13 +514,9 @@ def test_add_health_check_rest_flattened(): 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 "target_pool_value" in http_call[1] + str(body) - assert compute.TargetPoolsAddHealthCheckRequest.to_json( target_pools_add_health_check_request_resource, including_default_value_fields=False, @@ -502,7 +525,7 @@ def test_add_health_check_rest_flattened(): def test_add_health_check_rest_flattened_error(): - client = TargetPoolsClient(credentials=credentials.AnonymousCredentials(),) + client = TargetPoolsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -524,7 +547,7 @@ def test_add_instance_rest( transport: str = "rest", request_type=compute.AddInstanceTargetPoolRequest ): client = TargetPoolsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -559,17 +582,16 @@ def test_add_instance_rest( 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_instance(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" @@ -603,7 +625,7 @@ def test_add_instance_rest_from_dict(): def test_add_instance_rest_flattened(): - client = TargetPoolsClient(credentials=credentials.AnonymousCredentials(),) + client = TargetPoolsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -622,7 +644,6 @@ def test_add_instance_rest_flattened(): target_pools_add_instance_request_resource = compute.TargetPoolsAddInstanceRequest( instances=[compute.InstanceReference(instance="instance_value")] ) - client.add_instance( project="project_value", region="region_value", @@ -635,13 +656,9 @@ def test_add_instance_rest_flattened(): 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 "target_pool_value" in http_call[1] + str(body) - assert compute.TargetPoolsAddInstanceRequest.to_json( target_pools_add_instance_request_resource, including_default_value_fields=False, @@ -650,7 +667,7 @@ def test_add_instance_rest_flattened(): def test_add_instance_rest_flattened_error(): - client = TargetPoolsClient(credentials=credentials.AnonymousCredentials(),) + client = TargetPoolsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -670,7 +687,7 @@ def test_aggregated_list_rest( transport: str = "rest", request_type=compute.AggregatedListTargetPoolsRequest ): client = TargetPoolsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -693,17 +710,16 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.TargetPoolAggregatedList.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 == { @@ -723,7 +739,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = TargetPoolsClient(credentials=credentials.AnonymousCredentials(),) + client = TargetPoolsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -746,12 +762,11 @@ def test_aggregated_list_rest_flattened(): 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 = TargetPoolsClient(credentials=credentials.AnonymousCredentials(),) + client = TargetPoolsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -762,12 +777,11 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = TargetPoolsClient(credentials=credentials.AnonymousCredentials(),) + client = TargetPoolsClient(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.TargetPoolAggregatedList( items={ @@ -788,7 +802,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -810,7 +823,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -831,7 +843,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteTargetPoolRequest ): client = TargetPoolsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -866,17 +878,16 @@ def test_delete_rest( 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" @@ -910,7 +921,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = TargetPoolsClient(credentials=credentials.AnonymousCredentials(),) + client = TargetPoolsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -937,16 +948,13 @@ def test_delete_rest_flattened(): 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 "target_pool_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = TargetPoolsClient(credentials=credentials.AnonymousCredentials(),) + client = TargetPoolsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -961,7 +969,7 @@ def test_delete_rest_flattened_error(): def test_get_rest(transport: str = "rest", request_type=compute.GetTargetPoolRequest): client = TargetPoolsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -985,17 +993,16 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetTargetPoolReq self_link="self_link_value", session_affinity=compute.TargetPool.SessionAffinity.CLIENT_IP, ) + # Wrap the value into a proper Response obj json_return_value = compute.TargetPool.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.TargetPool) assert response.backup_pool == "backup_pool_value" assert response.creation_timestamp == "creation_timestamp_value" @@ -1016,7 +1023,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = TargetPoolsClient(credentials=credentials.AnonymousCredentials(),) + client = TargetPoolsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1043,16 +1050,13 @@ def test_get_rest_flattened(): 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 "target_pool_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = TargetPoolsClient(credentials=credentials.AnonymousCredentials(),) + client = TargetPoolsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1069,7 +1073,7 @@ def test_get_health_rest( transport: str = "rest", request_type=compute.GetHealthTargetPoolRequest ): client = TargetPoolsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1085,17 +1089,16 @@ def test_get_health_rest( ], kind="kind_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.TargetPoolInstanceHealth.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_health(request) # Establish that the response is the type that we expect. - assert isinstance(response, compute.TargetPoolInstanceHealth) assert response.health_status == [ compute.HealthStatus(annotations={"key_value": "value_value"}) @@ -1108,7 +1111,7 @@ def test_get_health_rest_from_dict(): def test_get_health_rest_flattened(): - client = TargetPoolsClient(credentials=credentials.AnonymousCredentials(),) + client = TargetPoolsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1127,7 +1130,6 @@ def test_get_health_rest_flattened(): instance_reference_resource = compute.InstanceReference( instance="instance_value" ) - client.get_health( project="project_value", region="region_value", @@ -1140,13 +1142,9 @@ def test_get_health_rest_flattened(): 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 "target_pool_value" in http_call[1] + str(body) - assert compute.InstanceReference.to_json( instance_reference_resource, including_default_value_fields=False, @@ -1155,7 +1153,7 @@ def test_get_health_rest_flattened(): def test_get_health_rest_flattened_error(): - client = TargetPoolsClient(credentials=credentials.AnonymousCredentials(),) + client = TargetPoolsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1175,7 +1173,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertTargetPoolRequest ): client = TargetPoolsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1210,17 +1208,16 @@ def test_insert_rest( 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" @@ -1254,7 +1251,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = TargetPoolsClient(credentials=credentials.AnonymousCredentials(),) + client = TargetPoolsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1271,7 +1268,6 @@ def test_insert_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. target_pool_resource = compute.TargetPool(backup_pool="backup_pool_value") - client.insert( project="project_value", region="region_value", @@ -1283,11 +1279,8 @@ def test_insert_rest_flattened(): 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.TargetPool.to_json( target_pool_resource, including_default_value_fields=False, @@ -1296,7 +1289,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = TargetPoolsClient(credentials=credentials.AnonymousCredentials(),) + client = TargetPoolsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1313,7 +1306,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListTargetPoolsRequest ): client = TargetPoolsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1331,17 +1324,16 @@ def test_list_rest( 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.TargetPoolList.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.TargetPool(backup_pool="backup_pool_value")] @@ -1356,7 +1348,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = TargetPoolsClient(credentials=credentials.AnonymousCredentials(),) + client = TargetPoolsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1381,14 +1373,12 @@ def test_list_rest_flattened(): 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 = TargetPoolsClient(credentials=credentials.AnonymousCredentials(),) + client = TargetPoolsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1401,12 +1391,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = TargetPoolsClient(credentials=credentials.AnonymousCredentials(),) + client = TargetPoolsClient(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.TargetPoolList( items=[ @@ -1424,7 +1413,6 @@ def test_list_pager(): items=[compute.TargetPool(), compute.TargetPool(),], ), ) - # Two responses for two calls response = response + response @@ -1443,7 +1431,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.TargetPool) for i in results) pages = list(client.list(request={}).pages) @@ -1455,7 +1442,7 @@ def test_remove_health_check_rest( transport: str = "rest", request_type=compute.RemoveHealthCheckTargetPoolRequest ): client = TargetPoolsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1490,17 +1477,16 @@ def test_remove_health_check_rest( 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_health_check(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" @@ -1534,7 +1520,7 @@ def test_remove_health_check_rest_from_dict(): def test_remove_health_check_rest_flattened(): - client = TargetPoolsClient(credentials=credentials.AnonymousCredentials(),) + client = TargetPoolsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1555,7 +1541,6 @@ def test_remove_health_check_rest_flattened(): compute.HealthCheckReference(health_check="health_check_value") ] ) - client.remove_health_check( project="project_value", region="region_value", @@ -1568,13 +1553,9 @@ def test_remove_health_check_rest_flattened(): 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 "target_pool_value" in http_call[1] + str(body) - assert compute.TargetPoolsRemoveHealthCheckRequest.to_json( target_pools_remove_health_check_request_resource, including_default_value_fields=False, @@ -1583,7 +1564,7 @@ def test_remove_health_check_rest_flattened(): def test_remove_health_check_rest_flattened_error(): - client = TargetPoolsClient(credentials=credentials.AnonymousCredentials(),) + client = TargetPoolsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1605,7 +1586,7 @@ def test_remove_instance_rest( transport: str = "rest", request_type=compute.RemoveInstanceTargetPoolRequest ): client = TargetPoolsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1640,17 +1621,16 @@ def test_remove_instance_rest( 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_instance(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" @@ -1684,7 +1664,7 @@ def test_remove_instance_rest_from_dict(): def test_remove_instance_rest_flattened(): - client = TargetPoolsClient(credentials=credentials.AnonymousCredentials(),) + client = TargetPoolsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1703,7 +1683,6 @@ def test_remove_instance_rest_flattened(): target_pools_remove_instance_request_resource = compute.TargetPoolsRemoveInstanceRequest( instances=[compute.InstanceReference(instance="instance_value")] ) - client.remove_instance( project="project_value", region="region_value", @@ -1716,13 +1695,9 @@ def test_remove_instance_rest_flattened(): 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 "target_pool_value" in http_call[1] + str(body) - assert compute.TargetPoolsRemoveInstanceRequest.to_json( target_pools_remove_instance_request_resource, including_default_value_fields=False, @@ -1731,7 +1706,7 @@ def test_remove_instance_rest_flattened(): def test_remove_instance_rest_flattened_error(): - client = TargetPoolsClient(credentials=credentials.AnonymousCredentials(),) + client = TargetPoolsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1751,7 +1726,7 @@ def test_set_backup_rest( transport: str = "rest", request_type=compute.SetBackupTargetPoolRequest ): client = TargetPoolsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1786,17 +1761,16 @@ def test_set_backup_rest( 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_backup(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" @@ -1830,7 +1804,7 @@ def test_set_backup_rest_from_dict(): def test_set_backup_rest_flattened(): - client = TargetPoolsClient(credentials=credentials.AnonymousCredentials(),) + client = TargetPoolsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1847,7 +1821,6 @@ def test_set_backup_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. target_reference_resource = compute.TargetReference(target="target_value") - client.set_backup( project="project_value", region="region_value", @@ -1860,13 +1833,9 @@ def test_set_backup_rest_flattened(): 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 "target_pool_value" in http_call[1] + str(body) - assert compute.TargetReference.to_json( target_reference_resource, including_default_value_fields=False, @@ -1875,7 +1844,7 @@ def test_set_backup_rest_flattened(): def test_set_backup_rest_flattened_error(): - client = TargetPoolsClient(credentials=credentials.AnonymousCredentials(),) + client = TargetPoolsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1892,16 +1861,16 @@ def test_set_backup_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.TargetPoolsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TargetPoolsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.TargetPoolsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TargetPoolsClient( @@ -1911,7 +1880,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.TargetPoolsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TargetPoolsClient( @@ -1922,7 +1891,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.TargetPoolsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = TargetPoolsClient(transport=transport) assert client.transport is transport @@ -1931,17 +1900,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.TargetPoolsRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_target_pools_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.TargetPoolsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1953,7 +1922,7 @@ def test_target_pools_base_transport(): ) as Transport: Transport.return_value = None transport = transports.TargetPoolsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1976,15 +1945,40 @@ def test_target_pools_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_target_pools_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.target_pools.transports.TargetPoolsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TargetPoolsTransport( + 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_target_pools_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.target_pools.transports.TargetPoolsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.TargetPoolsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2000,19 +1994,36 @@ def test_target_pools_base_transport_with_credentials_file(): def test_target_pools_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.target_pools.transports.TargetPoolsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.TargetPoolsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_target_pools_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + TargetPoolsClient() + 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_target_pools_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) TargetPoolsClient() adc.assert_called_once_with( scopes=( @@ -2024,7 +2035,7 @@ def test_target_pools_auth_adc(): def test_target_pools_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -2036,7 +2047,7 @@ def test_target_pools_http_transport_client_cert_source_for_mtls(): def test_target_pools_host_no_port(): client = TargetPoolsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -2046,7 +2057,7 @@ def test_target_pools_host_no_port(): def test_target_pools_host_with_port(): client = TargetPoolsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -2056,7 +2067,6 @@ def test_target_pools_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2077,7 +2087,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = TargetPoolsClient.common_folder_path(folder) assert expected == actual @@ -2096,7 +2105,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = TargetPoolsClient.common_organization_path(organization) assert expected == actual @@ -2115,7 +2123,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = TargetPoolsClient.common_project_path(project) assert expected == actual @@ -2135,7 +2142,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2162,7 +2168,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.TargetPoolsTransport, "_prep_wrapped_messages" ) as prep: client = TargetPoolsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2171,6 +2177,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = TargetPoolsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_target_ssl_proxies.py b/tests/unit/gapic/compute_v1/test_target_ssl_proxies.py index ddaf513cd..c1c8265b6 100644 --- a/tests/unit/gapic/compute_v1/test_target_ssl_proxies.py +++ b/tests/unit/gapic/compute_v1/test_target_ssl_proxies.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -88,7 +117,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [TargetSslProxiesClient,]) def test_target_ssl_proxies_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -103,7 +132,7 @@ def test_target_ssl_proxies_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [TargetSslProxiesClient,]) def test_target_ssl_proxies_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -144,7 +173,7 @@ def test_target_ssl_proxies_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(TargetSslProxiesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -392,7 +421,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteTargetSslProxyRequest ): client = TargetSslProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -427,17 +456,16 @@ def test_delete_rest( 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" @@ -471,7 +499,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = TargetSslProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetSslProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -496,14 +524,12 @@ def test_delete_rest_flattened(): 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_ssl_proxy_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = TargetSslProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetSslProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -519,7 +545,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetTargetSslProxyRequest ): client = TargetSslProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -541,17 +567,16 @@ def test_get_rest( ssl_certificates=["ssl_certificates_value"], ssl_policy="ssl_policy_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.TargetSslProxy.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.TargetSslProxy) assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" @@ -570,7 +595,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = TargetSslProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetSslProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -595,14 +620,12 @@ def test_get_rest_flattened(): 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_ssl_proxy_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = TargetSslProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetSslProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -618,7 +641,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertTargetSslProxyRequest ): client = TargetSslProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -653,17 +676,16 @@ def test_insert_rest( 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" @@ -697,7 +719,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = TargetSslProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetSslProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -716,7 +738,6 @@ def test_insert_rest_flattened(): target_ssl_proxy_resource = compute.TargetSslProxy( creation_timestamp="creation_timestamp_value" ) - client.insert( project="project_value", target_ssl_proxy_resource=target_ssl_proxy_resource, @@ -727,9 +748,7 @@ def test_insert_rest_flattened(): 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.TargetSslProxy.to_json( target_ssl_proxy_resource, including_default_value_fields=False, @@ -738,7 +757,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = TargetSslProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetSslProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -756,7 +775,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListTargetSslProxiesRequest ): client = TargetSslProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -776,17 +795,16 @@ def test_list_rest( 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.TargetSslProxyList.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 == [ @@ -803,7 +821,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = TargetSslProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetSslProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -826,12 +844,11 @@ def test_list_rest_flattened(): 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 = TargetSslProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetSslProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -842,12 +859,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = TargetSslProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetSslProxiesClient(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.TargetSslProxyList( items=[ @@ -865,7 +881,6 @@ def test_list_pager(): items=[compute.TargetSslProxy(), compute.TargetSslProxy(),], ), ) - # Two responses for two calls response = response + response @@ -884,7 +899,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.TargetSslProxy) for i in results) pages = list(client.list(request={}).pages) @@ -896,7 +910,7 @@ def test_set_backend_service_rest( transport: str = "rest", request_type=compute.SetBackendServiceTargetSslProxyRequest ): client = TargetSslProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -931,17 +945,16 @@ def test_set_backend_service_rest( 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_backend_service(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" @@ -975,7 +988,7 @@ def test_set_backend_service_rest_from_dict(): def test_set_backend_service_rest_flattened(): - client = TargetSslProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetSslProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -994,7 +1007,6 @@ def test_set_backend_service_rest_flattened(): target_ssl_proxies_set_backend_service_request_resource = compute.TargetSslProxiesSetBackendServiceRequest( service="service_value" ) - client.set_backend_service( project="project_value", target_ssl_proxy="target_ssl_proxy_value", @@ -1006,11 +1018,8 @@ def test_set_backend_service_rest_flattened(): 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_ssl_proxy_value" in http_call[1] + str(body) - assert compute.TargetSslProxiesSetBackendServiceRequest.to_json( target_ssl_proxies_set_backend_service_request_resource, including_default_value_fields=False, @@ -1019,7 +1028,7 @@ def test_set_backend_service_rest_flattened(): def test_set_backend_service_rest_flattened_error(): - client = TargetSslProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetSslProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1038,7 +1047,7 @@ def test_set_proxy_header_rest( transport: str = "rest", request_type=compute.SetProxyHeaderTargetSslProxyRequest ): client = TargetSslProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1073,17 +1082,16 @@ def test_set_proxy_header_rest( 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_proxy_header(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" @@ -1117,7 +1125,7 @@ def test_set_proxy_header_rest_from_dict(): def test_set_proxy_header_rest_flattened(): - client = TargetSslProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetSslProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1136,7 +1144,6 @@ def test_set_proxy_header_rest_flattened(): target_ssl_proxies_set_proxy_header_request_resource = compute.TargetSslProxiesSetProxyHeaderRequest( proxy_header=compute.TargetSslProxiesSetProxyHeaderRequest.ProxyHeader.NONE ) - client.set_proxy_header( project="project_value", target_ssl_proxy="target_ssl_proxy_value", @@ -1148,11 +1155,8 @@ def test_set_proxy_header_rest_flattened(): 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_ssl_proxy_value" in http_call[1] + str(body) - assert compute.TargetSslProxiesSetProxyHeaderRequest.to_json( target_ssl_proxies_set_proxy_header_request_resource, including_default_value_fields=False, @@ -1161,7 +1165,7 @@ def test_set_proxy_header_rest_flattened(): def test_set_proxy_header_rest_flattened_error(): - client = TargetSslProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetSslProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1181,7 +1185,7 @@ def test_set_ssl_certificates_rest( request_type=compute.SetSslCertificatesTargetSslProxyRequest, ): client = TargetSslProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1216,17 +1220,16 @@ def test_set_ssl_certificates_rest( 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_ssl_certificates(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" @@ -1260,7 +1263,7 @@ def test_set_ssl_certificates_rest_from_dict(): def test_set_ssl_certificates_rest_flattened(): - client = TargetSslProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetSslProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1279,7 +1282,6 @@ def test_set_ssl_certificates_rest_flattened(): target_ssl_proxies_set_ssl_certificates_request_resource = compute.TargetSslProxiesSetSslCertificatesRequest( ssl_certificates=["ssl_certificates_value"] ) - client.set_ssl_certificates( project="project_value", target_ssl_proxy="target_ssl_proxy_value", @@ -1291,11 +1293,8 @@ def test_set_ssl_certificates_rest_flattened(): 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_ssl_proxy_value" in http_call[1] + str(body) - assert compute.TargetSslProxiesSetSslCertificatesRequest.to_json( target_ssl_proxies_set_ssl_certificates_request_resource, including_default_value_fields=False, @@ -1304,7 +1303,7 @@ def test_set_ssl_certificates_rest_flattened(): def test_set_ssl_certificates_rest_flattened_error(): - client = TargetSslProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetSslProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1323,7 +1322,7 @@ def test_set_ssl_policy_rest( transport: str = "rest", request_type=compute.SetSslPolicyTargetSslProxyRequest ): client = TargetSslProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1358,17 +1357,16 @@ def test_set_ssl_policy_rest( 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_ssl_policy(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" @@ -1402,7 +1400,7 @@ def test_set_ssl_policy_rest_from_dict(): def test_set_ssl_policy_rest_flattened(): - client = TargetSslProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetSslProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1421,7 +1419,6 @@ def test_set_ssl_policy_rest_flattened(): ssl_policy_reference_resource = compute.SslPolicyReference( ssl_policy="ssl_policy_value" ) - client.set_ssl_policy( project="project_value", target_ssl_proxy="target_ssl_proxy_value", @@ -1433,11 +1430,8 @@ def test_set_ssl_policy_rest_flattened(): 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_ssl_proxy_value" in http_call[1] + str(body) - assert compute.SslPolicyReference.to_json( ssl_policy_reference_resource, including_default_value_fields=False, @@ -1446,7 +1440,7 @@ def test_set_ssl_policy_rest_flattened(): def test_set_ssl_policy_rest_flattened_error(): - client = TargetSslProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetSslProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1464,16 +1458,16 @@ def test_set_ssl_policy_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.TargetSslProxiesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TargetSslProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.TargetSslProxiesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TargetSslProxiesClient( @@ -1483,7 +1477,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.TargetSslProxiesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TargetSslProxiesClient( @@ -1494,7 +1488,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.TargetSslProxiesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = TargetSslProxiesClient(transport=transport) assert client.transport is transport @@ -1503,17 +1497,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.TargetSslProxiesRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_target_ssl_proxies_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.TargetSslProxiesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1525,7 +1519,7 @@ def test_target_ssl_proxies_base_transport(): ) as Transport: Transport.return_value = None transport = transports.TargetSslProxiesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1545,15 +1539,40 @@ def test_target_ssl_proxies_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_target_ssl_proxies_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.target_ssl_proxies.transports.TargetSslProxiesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TargetSslProxiesTransport( + 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_target_ssl_proxies_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.target_ssl_proxies.transports.TargetSslProxiesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.TargetSslProxiesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1569,19 +1588,36 @@ def test_target_ssl_proxies_base_transport_with_credentials_file(): def test_target_ssl_proxies_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.target_ssl_proxies.transports.TargetSslProxiesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.TargetSslProxiesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_target_ssl_proxies_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + TargetSslProxiesClient() + 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_target_ssl_proxies_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) TargetSslProxiesClient() adc.assert_called_once_with( scopes=( @@ -1593,7 +1629,7 @@ def test_target_ssl_proxies_auth_adc(): def test_target_ssl_proxies_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1605,7 +1641,7 @@ def test_target_ssl_proxies_http_transport_client_cert_source_for_mtls(): def test_target_ssl_proxies_host_no_port(): client = TargetSslProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1615,7 +1651,7 @@ def test_target_ssl_proxies_host_no_port(): def test_target_ssl_proxies_host_with_port(): client = TargetSslProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1625,7 +1661,6 @@ def test_target_ssl_proxies_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1646,7 +1681,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = TargetSslProxiesClient.common_folder_path(folder) assert expected == actual @@ -1665,7 +1699,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = TargetSslProxiesClient.common_organization_path(organization) assert expected == actual @@ -1684,7 +1717,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = TargetSslProxiesClient.common_project_path(project) assert expected == actual @@ -1704,7 +1736,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1731,7 +1762,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.TargetSslProxiesTransport, "_prep_wrapped_messages" ) as prep: client = TargetSslProxiesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1740,6 +1771,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = TargetSslProxiesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_target_tcp_proxies.py b/tests/unit/gapic/compute_v1/test_target_tcp_proxies.py index ab0dad99a..15c3146d1 100644 --- a/tests/unit/gapic/compute_v1/test_target_tcp_proxies.py +++ b/tests/unit/gapic/compute_v1/test_target_tcp_proxies.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -88,7 +117,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [TargetTcpProxiesClient,]) def test_target_tcp_proxies_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -103,7 +132,7 @@ def test_target_tcp_proxies_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [TargetTcpProxiesClient,]) def test_target_tcp_proxies_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -144,7 +173,7 @@ def test_target_tcp_proxies_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(TargetTcpProxiesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -392,7 +421,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteTargetTcpProxyRequest ): client = TargetTcpProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -427,17 +456,16 @@ def test_delete_rest( 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" @@ -471,7 +499,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = TargetTcpProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetTcpProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -496,14 +524,12 @@ def test_delete_rest_flattened(): 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_tcp_proxy_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = TargetTcpProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetTcpProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -519,7 +545,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetTargetTcpProxyRequest ): client = TargetTcpProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -539,17 +565,16 @@ def test_get_rest( self_link="self_link_value", service="service_value", ) + # Wrap the value into a proper Response obj json_return_value = compute.TargetTcpProxy.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.TargetTcpProxy) assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" @@ -566,7 +591,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = TargetTcpProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetTcpProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -591,14 +616,12 @@ def test_get_rest_flattened(): 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_tcp_proxy_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = TargetTcpProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetTcpProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -614,7 +637,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertTargetTcpProxyRequest ): client = TargetTcpProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -649,17 +672,16 @@ def test_insert_rest( 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" @@ -693,7 +715,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = TargetTcpProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetTcpProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -712,7 +734,6 @@ def test_insert_rest_flattened(): target_tcp_proxy_resource = compute.TargetTcpProxy( creation_timestamp="creation_timestamp_value" ) - client.insert( project="project_value", target_tcp_proxy_resource=target_tcp_proxy_resource, @@ -723,9 +744,7 @@ def test_insert_rest_flattened(): 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.TargetTcpProxy.to_json( target_tcp_proxy_resource, including_default_value_fields=False, @@ -734,7 +753,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = TargetTcpProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetTcpProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -752,7 +771,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListTargetTcpProxiesRequest ): client = TargetTcpProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -772,17 +791,16 @@ def test_list_rest( 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.TargetTcpProxyList.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 == [ @@ -799,7 +817,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = TargetTcpProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetTcpProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -822,12 +840,11 @@ def test_list_rest_flattened(): 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 = TargetTcpProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetTcpProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -838,12 +855,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = TargetTcpProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetTcpProxiesClient(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.TargetTcpProxyList( items=[ @@ -861,7 +877,6 @@ def test_list_pager(): items=[compute.TargetTcpProxy(), compute.TargetTcpProxy(),], ), ) - # Two responses for two calls response = response + response @@ -880,7 +895,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.TargetTcpProxy) for i in results) pages = list(client.list(request={}).pages) @@ -892,7 +906,7 @@ def test_set_backend_service_rest( transport: str = "rest", request_type=compute.SetBackendServiceTargetTcpProxyRequest ): client = TargetTcpProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -927,17 +941,16 @@ def test_set_backend_service_rest( 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_backend_service(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" @@ -971,7 +984,7 @@ def test_set_backend_service_rest_from_dict(): def test_set_backend_service_rest_flattened(): - client = TargetTcpProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetTcpProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -990,7 +1003,6 @@ def test_set_backend_service_rest_flattened(): target_tcp_proxies_set_backend_service_request_resource = compute.TargetTcpProxiesSetBackendServiceRequest( service="service_value" ) - client.set_backend_service( project="project_value", target_tcp_proxy="target_tcp_proxy_value", @@ -1002,11 +1014,8 @@ def test_set_backend_service_rest_flattened(): 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_tcp_proxy_value" in http_call[1] + str(body) - assert compute.TargetTcpProxiesSetBackendServiceRequest.to_json( target_tcp_proxies_set_backend_service_request_resource, including_default_value_fields=False, @@ -1015,7 +1024,7 @@ def test_set_backend_service_rest_flattened(): def test_set_backend_service_rest_flattened_error(): - client = TargetTcpProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetTcpProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1034,7 +1043,7 @@ def test_set_proxy_header_rest( transport: str = "rest", request_type=compute.SetProxyHeaderTargetTcpProxyRequest ): client = TargetTcpProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1069,17 +1078,16 @@ def test_set_proxy_header_rest( 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_proxy_header(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" @@ -1113,7 +1121,7 @@ def test_set_proxy_header_rest_from_dict(): def test_set_proxy_header_rest_flattened(): - client = TargetTcpProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetTcpProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1132,7 +1140,6 @@ def test_set_proxy_header_rest_flattened(): target_tcp_proxies_set_proxy_header_request_resource = compute.TargetTcpProxiesSetProxyHeaderRequest( proxy_header=compute.TargetTcpProxiesSetProxyHeaderRequest.ProxyHeader.NONE ) - client.set_proxy_header( project="project_value", target_tcp_proxy="target_tcp_proxy_value", @@ -1144,11 +1151,8 @@ def test_set_proxy_header_rest_flattened(): 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_tcp_proxy_value" in http_call[1] + str(body) - assert compute.TargetTcpProxiesSetProxyHeaderRequest.to_json( target_tcp_proxies_set_proxy_header_request_resource, including_default_value_fields=False, @@ -1157,7 +1161,7 @@ def test_set_proxy_header_rest_flattened(): def test_set_proxy_header_rest_flattened_error(): - client = TargetTcpProxiesClient(credentials=credentials.AnonymousCredentials(),) + client = TargetTcpProxiesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1175,16 +1179,16 @@ def test_set_proxy_header_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.TargetTcpProxiesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TargetTcpProxiesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.TargetTcpProxiesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TargetTcpProxiesClient( @@ -1194,7 +1198,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.TargetTcpProxiesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TargetTcpProxiesClient( @@ -1205,7 +1209,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.TargetTcpProxiesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = TargetTcpProxiesClient(transport=transport) assert client.transport is transport @@ -1214,17 +1218,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.TargetTcpProxiesRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_target_tcp_proxies_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.TargetTcpProxiesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1236,7 +1240,7 @@ def test_target_tcp_proxies_base_transport(): ) as Transport: Transport.return_value = None transport = transports.TargetTcpProxiesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1254,15 +1258,40 @@ def test_target_tcp_proxies_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_target_tcp_proxies_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.target_tcp_proxies.transports.TargetTcpProxiesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TargetTcpProxiesTransport( + 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_target_tcp_proxies_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.target_tcp_proxies.transports.TargetTcpProxiesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.TargetTcpProxiesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1278,19 +1307,36 @@ def test_target_tcp_proxies_base_transport_with_credentials_file(): def test_target_tcp_proxies_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.target_tcp_proxies.transports.TargetTcpProxiesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.TargetTcpProxiesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_target_tcp_proxies_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + TargetTcpProxiesClient() + 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_target_tcp_proxies_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) TargetTcpProxiesClient() adc.assert_called_once_with( scopes=( @@ -1302,7 +1348,7 @@ def test_target_tcp_proxies_auth_adc(): def test_target_tcp_proxies_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1314,7 +1360,7 @@ def test_target_tcp_proxies_http_transport_client_cert_source_for_mtls(): def test_target_tcp_proxies_host_no_port(): client = TargetTcpProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1324,7 +1370,7 @@ def test_target_tcp_proxies_host_no_port(): def test_target_tcp_proxies_host_with_port(): client = TargetTcpProxiesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1334,7 +1380,6 @@ def test_target_tcp_proxies_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1355,7 +1400,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = TargetTcpProxiesClient.common_folder_path(folder) assert expected == actual @@ -1374,7 +1418,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = TargetTcpProxiesClient.common_organization_path(organization) assert expected == actual @@ -1393,7 +1436,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = TargetTcpProxiesClient.common_project_path(project) assert expected == actual @@ -1413,7 +1455,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1440,7 +1481,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.TargetTcpProxiesTransport, "_prep_wrapped_messages" ) as prep: client = TargetTcpProxiesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1449,6 +1490,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = TargetTcpProxiesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_target_vpn_gateways.py b/tests/unit/gapic/compute_v1/test_target_vpn_gateways.py index bebb3ab54..332c8edd6 100644 --- a/tests/unit/gapic/compute_v1/test_target_vpn_gateways.py +++ b/tests/unit/gapic/compute_v1/test_target_vpn_gateways.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -88,7 +117,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [TargetVpnGatewaysClient,]) def test_target_vpn_gateways_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -103,7 +132,7 @@ def test_target_vpn_gateways_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [TargetVpnGatewaysClient,]) def test_target_vpn_gateways_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -144,7 +173,7 @@ def test_target_vpn_gateways_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(TargetVpnGatewaysClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -392,7 +421,7 @@ def test_aggregated_list_rest( transport: str = "rest", request_type=compute.AggregatedListTargetVpnGatewaysRequest ): client = TargetVpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -419,17 +448,16 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.TargetVpnGatewayAggregatedList.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 == { @@ -451,7 +479,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = TargetVpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = TargetVpnGatewaysClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -474,12 +502,11 @@ def test_aggregated_list_rest_flattened(): 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 = TargetVpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = TargetVpnGatewaysClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -490,12 +517,11 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = TargetVpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = TargetVpnGatewaysClient(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.TargetVpnGatewayAggregatedList( items={ @@ -517,7 +543,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -541,7 +566,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -562,7 +586,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteTargetVpnGatewayRequest ): client = TargetVpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -597,17 +621,16 @@ def test_delete_rest( 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" @@ -641,7 +664,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = TargetVpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = TargetVpnGatewaysClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -668,16 +691,13 @@ def test_delete_rest_flattened(): 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 "target_vpn_gateway_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = TargetVpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = TargetVpnGatewaysClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -694,7 +714,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetTargetVpnGatewayRequest ): client = TargetVpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -717,17 +737,16 @@ def test_get_rest( status=compute.TargetVpnGateway.Status.CREATING, tunnels=["tunnels_value"], ) + # Wrap the value into a proper Response obj json_return_value = compute.TargetVpnGateway.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.TargetVpnGateway) assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" @@ -747,7 +766,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = TargetVpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = TargetVpnGatewaysClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -774,16 +793,13 @@ def test_get_rest_flattened(): 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 "target_vpn_gateway_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = TargetVpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = TargetVpnGatewaysClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -800,7 +816,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertTargetVpnGatewayRequest ): client = TargetVpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -835,17 +851,16 @@ def test_insert_rest( 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" @@ -879,7 +894,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = TargetVpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = TargetVpnGatewaysClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -898,7 +913,6 @@ def test_insert_rest_flattened(): target_vpn_gateway_resource = compute.TargetVpnGateway( creation_timestamp="creation_timestamp_value" ) - client.insert( project="project_value", region="region_value", @@ -910,11 +924,8 @@ def test_insert_rest_flattened(): 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.TargetVpnGateway.to_json( target_vpn_gateway_resource, including_default_value_fields=False, @@ -923,7 +934,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = TargetVpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = TargetVpnGatewaysClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -942,7 +953,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListTargetVpnGatewaysRequest ): client = TargetVpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -962,17 +973,16 @@ def test_list_rest( 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.TargetVpnGatewayList.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 == [ @@ -989,7 +999,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = TargetVpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = TargetVpnGatewaysClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1014,14 +1024,12 @@ def test_list_rest_flattened(): 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 = TargetVpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = TargetVpnGatewaysClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1034,12 +1042,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = TargetVpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = TargetVpnGatewaysClient(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.TargetVpnGatewayList( items=[ @@ -1057,7 +1064,6 @@ def test_list_pager(): items=[compute.TargetVpnGateway(), compute.TargetVpnGateway(),], ), ) - # Two responses for two calls response = response + response @@ -1076,7 +1082,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.TargetVpnGateway) for i in results) pages = list(client.list(request={}).pages) @@ -1087,16 +1092,16 @@ def test_list_pager(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.TargetVpnGatewaysRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TargetVpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.TargetVpnGatewaysRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TargetVpnGatewaysClient( @@ -1106,7 +1111,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.TargetVpnGatewaysRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TargetVpnGatewaysClient( @@ -1117,7 +1122,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.TargetVpnGatewaysRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = TargetVpnGatewaysClient(transport=transport) assert client.transport is transport @@ -1128,17 +1133,17 @@ def test_transport_instance(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_target_vpn_gateways_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.TargetVpnGatewaysTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1150,7 +1155,7 @@ def test_target_vpn_gateways_base_transport(): ) as Transport: Transport.return_value = None transport = transports.TargetVpnGatewaysTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1167,15 +1172,40 @@ def test_target_vpn_gateways_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_target_vpn_gateways_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.target_vpn_gateways.transports.TargetVpnGatewaysTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TargetVpnGatewaysTransport( + 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_target_vpn_gateways_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.target_vpn_gateways.transports.TargetVpnGatewaysTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.TargetVpnGatewaysTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1191,19 +1221,36 @@ def test_target_vpn_gateways_base_transport_with_credentials_file(): def test_target_vpn_gateways_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.target_vpn_gateways.transports.TargetVpnGatewaysTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.TargetVpnGatewaysTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_target_vpn_gateways_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + TargetVpnGatewaysClient() + 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_target_vpn_gateways_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) TargetVpnGatewaysClient() adc.assert_called_once_with( scopes=( @@ -1215,7 +1262,7 @@ def test_target_vpn_gateways_auth_adc(): def test_target_vpn_gateways_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1227,7 +1274,7 @@ def test_target_vpn_gateways_http_transport_client_cert_source_for_mtls(): def test_target_vpn_gateways_host_no_port(): client = TargetVpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1237,7 +1284,7 @@ def test_target_vpn_gateways_host_no_port(): def test_target_vpn_gateways_host_with_port(): client = TargetVpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1247,7 +1294,6 @@ def test_target_vpn_gateways_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1268,7 +1314,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = TargetVpnGatewaysClient.common_folder_path(folder) assert expected == actual @@ -1287,7 +1332,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = TargetVpnGatewaysClient.common_organization_path(organization) assert expected == actual @@ -1306,7 +1350,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = TargetVpnGatewaysClient.common_project_path(project) assert expected == actual @@ -1326,7 +1369,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1353,7 +1395,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.TargetVpnGatewaysTransport, "_prep_wrapped_messages" ) as prep: client = TargetVpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1362,6 +1404,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = TargetVpnGatewaysClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_url_maps.py b/tests/unit/gapic/compute_v1/test_url_maps.py index ecd2fccf8..f627743c3 100644 --- a/tests/unit/gapic/compute_v1/test_url_maps.py +++ b/tests/unit/gapic/compute_v1/test_url_maps.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,59 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -81,7 +108,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [UrlMapsClient,]) def test_url_maps_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -96,7 +123,7 @@ def test_url_maps_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [UrlMapsClient,]) def test_url_maps_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -133,7 +160,7 @@ def test_url_maps_client_get_transport_class(): def test_url_maps_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(UrlMapsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -369,7 +396,7 @@ def test_aggregated_list_rest( transport: str = "rest", request_type=compute.AggregatedListUrlMapsRequest ): client = UrlMapsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -394,17 +421,16 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.UrlMapsAggregatedList.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 == { @@ -424,7 +450,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = UrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = UrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -447,12 +473,11 @@ def test_aggregated_list_rest_flattened(): 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 = UrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = UrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -463,12 +488,11 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = UrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = UrlMapsClient(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.UrlMapsAggregatedList( items={ @@ -489,7 +513,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -511,7 +534,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -527,7 +549,7 @@ def test_aggregated_list_pager(): def test_delete_rest(transport: str = "rest", request_type=compute.DeleteUrlMapRequest): client = UrlMapsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -562,17 +584,16 @@ def test_delete_rest(transport: str = "rest", request_type=compute.DeleteUrlMapR 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" @@ -606,7 +627,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = UrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = UrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -631,14 +652,12 @@ def test_delete_rest_flattened(): 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 "url_map_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = UrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = UrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -652,7 +671,7 @@ def test_delete_rest_flattened_error(): def test_get_rest(transport: str = "rest", request_type=compute.GetUrlMapRequest): client = UrlMapsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -693,17 +712,16 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetUrlMapRequest self_link="self_link_value", tests=[compute.UrlMapTest(description="description_value")], ) + # Wrap the value into a proper Response obj json_return_value = compute.UrlMap.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.UrlMap) assert response.creation_timestamp == "creation_timestamp_value" assert response.default_route_action == compute.HttpRouteAction( @@ -741,7 +759,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = UrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = UrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -766,14 +784,12 @@ def test_get_rest_flattened(): 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 "url_map_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = UrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = UrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -787,7 +803,7 @@ def test_get_rest_flattened_error(): def test_insert_rest(transport: str = "rest", request_type=compute.InsertUrlMapRequest): client = UrlMapsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -822,17 +838,16 @@ def test_insert_rest(transport: str = "rest", request_type=compute.InsertUrlMapR 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" @@ -866,7 +881,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = UrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = UrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -883,7 +898,6 @@ def test_insert_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. url_map_resource = compute.UrlMap(creation_timestamp="creation_timestamp_value") - client.insert( project="project_value", url_map_resource=url_map_resource, ) @@ -893,9 +907,7 @@ def test_insert_rest_flattened(): 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.UrlMap.to_json( url_map_resource, including_default_value_fields=False, @@ -904,7 +916,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = UrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = UrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -922,7 +934,7 @@ def test_invalidate_cache_rest( transport: str = "rest", request_type=compute.InvalidateCacheUrlMapRequest ): client = UrlMapsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -957,17 +969,16 @@ def test_invalidate_cache_rest( 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.invalidate_cache(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" @@ -1001,7 +1012,7 @@ def test_invalidate_cache_rest_from_dict(): def test_invalidate_cache_rest_flattened(): - client = UrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = UrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1020,7 +1031,6 @@ def test_invalidate_cache_rest_flattened(): cache_invalidation_rule_resource = compute.CacheInvalidationRule( host="host_value" ) - client.invalidate_cache( project="project_value", url_map="url_map_value", @@ -1032,11 +1042,8 @@ def test_invalidate_cache_rest_flattened(): 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 "url_map_value" in http_call[1] + str(body) - assert compute.CacheInvalidationRule.to_json( cache_invalidation_rule_resource, including_default_value_fields=False, @@ -1045,7 +1052,7 @@ def test_invalidate_cache_rest_flattened(): def test_invalidate_cache_rest_flattened_error(): - client = UrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = UrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1062,7 +1069,7 @@ def test_invalidate_cache_rest_flattened_error(): def test_list_rest(transport: str = "rest", request_type=compute.ListUrlMapsRequest): client = UrlMapsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1080,17 +1087,16 @@ def test_list_rest(transport: str = "rest", request_type=compute.ListUrlMapsRequ 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.UrlMapList.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 == [ @@ -1107,7 +1113,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = UrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = UrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1130,12 +1136,11 @@ def test_list_rest_flattened(): 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 = UrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = UrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1146,12 +1151,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = UrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = UrlMapsClient(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.UrlMapList( items=[compute.UrlMap(), compute.UrlMap(), compute.UrlMap(),], @@ -1161,7 +1165,6 @@ def test_list_pager(): compute.UrlMapList(items=[compute.UrlMap(),], next_page_token="ghi",), compute.UrlMapList(items=[compute.UrlMap(), compute.UrlMap(),],), ) - # Two responses for two calls response = response + response @@ -1180,7 +1183,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.UrlMap) for i in results) pages = list(client.list(request={}).pages) @@ -1190,7 +1192,7 @@ def test_list_pager(): def test_patch_rest(transport: str = "rest", request_type=compute.PatchUrlMapRequest): client = UrlMapsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1225,17 +1227,16 @@ def test_patch_rest(transport: str = "rest", request_type=compute.PatchUrlMapReq 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" @@ -1269,7 +1270,7 @@ def test_patch_rest_from_dict(): def test_patch_rest_flattened(): - client = UrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = UrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1286,7 +1287,6 @@ def test_patch_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. url_map_resource = compute.UrlMap(creation_timestamp="creation_timestamp_value") - client.patch( project="project_value", url_map="url_map_value", @@ -1298,11 +1298,8 @@ def test_patch_rest_flattened(): 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 "url_map_value" in http_call[1] + str(body) - assert compute.UrlMap.to_json( url_map_resource, including_default_value_fields=False, @@ -1311,7 +1308,7 @@ def test_patch_rest_flattened(): def test_patch_rest_flattened_error(): - client = UrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = UrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1328,7 +1325,7 @@ def test_patch_rest_flattened_error(): def test_update_rest(transport: str = "rest", request_type=compute.UpdateUrlMapRequest): client = UrlMapsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1363,17 +1360,16 @@ def test_update_rest(transport: str = "rest", request_type=compute.UpdateUrlMapR 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.update(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" @@ -1407,7 +1403,7 @@ def test_update_rest_from_dict(): def test_update_rest_flattened(): - client = UrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = UrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1424,7 +1420,6 @@ def test_update_rest_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. url_map_resource = compute.UrlMap(creation_timestamp="creation_timestamp_value") - client.update( project="project_value", url_map="url_map_value", @@ -1436,11 +1431,8 @@ def test_update_rest_flattened(): 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 "url_map_value" in http_call[1] + str(body) - assert compute.UrlMap.to_json( url_map_resource, including_default_value_fields=False, @@ -1449,7 +1441,7 @@ def test_update_rest_flattened(): def test_update_rest_flattened_error(): - client = UrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = UrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1468,7 +1460,7 @@ def test_validate_rest( transport: str = "rest", request_type=compute.ValidateUrlMapRequest ): client = UrlMapsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1481,17 +1473,16 @@ def test_validate_rest( return_value = compute.UrlMapsValidateResponse( result=compute.UrlMapValidationResult(load_errors=["load_errors_value"]), ) + # Wrap the value into a proper Response obj json_return_value = compute.UrlMapsValidateResponse.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.validate(request) # Establish that the response is the type that we expect. - assert isinstance(response, compute.UrlMapsValidateResponse) assert response.result == compute.UrlMapValidationResult( load_errors=["load_errors_value"] @@ -1503,7 +1494,7 @@ def test_validate_rest_from_dict(): def test_validate_rest_flattened(): - client = UrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = UrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1522,7 +1513,6 @@ def test_validate_rest_flattened(): url_maps_validate_request_resource = compute.UrlMapsValidateRequest( resource=compute.UrlMap(creation_timestamp="creation_timestamp_value") ) - client.validate( project="project_value", url_map="url_map_value", @@ -1534,11 +1524,8 @@ def test_validate_rest_flattened(): 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 "url_map_value" in http_call[1] + str(body) - assert compute.UrlMapsValidateRequest.to_json( url_maps_validate_request_resource, including_default_value_fields=False, @@ -1547,7 +1534,7 @@ def test_validate_rest_flattened(): def test_validate_rest_flattened_error(): - client = UrlMapsClient(credentials=credentials.AnonymousCredentials(),) + client = UrlMapsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1565,16 +1552,16 @@ def test_validate_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.UrlMapsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = UrlMapsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.UrlMapsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = UrlMapsClient( @@ -1584,7 +1571,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.UrlMapsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = UrlMapsClient( @@ -1595,7 +1582,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.UrlMapsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = UrlMapsClient(transport=transport) assert client.transport is transport @@ -1604,17 +1591,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.UrlMapsRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_url_maps_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.UrlMapsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1626,7 +1613,7 @@ def test_url_maps_base_transport(): ) as Transport: Transport.return_value = None transport = transports.UrlMapsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1647,15 +1634,40 @@ def test_url_maps_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_url_maps_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.url_maps.transports.UrlMapsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UrlMapsTransport( + 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_url_maps_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.url_maps.transports.UrlMapsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.UrlMapsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1671,19 +1683,36 @@ def test_url_maps_base_transport_with_credentials_file(): def test_url_maps_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.url_maps.transports.UrlMapsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.UrlMapsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_url_maps_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + UrlMapsClient() + 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_url_maps_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) UrlMapsClient() adc.assert_called_once_with( scopes=( @@ -1695,7 +1724,7 @@ def test_url_maps_auth_adc(): def test_url_maps_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1707,7 +1736,7 @@ def test_url_maps_http_transport_client_cert_source_for_mtls(): def test_url_maps_host_no_port(): client = UrlMapsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1717,7 +1746,7 @@ def test_url_maps_host_no_port(): def test_url_maps_host_with_port(): client = UrlMapsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1727,7 +1756,6 @@ def test_url_maps_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1748,7 +1776,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = UrlMapsClient.common_folder_path(folder) assert expected == actual @@ -1767,7 +1794,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = UrlMapsClient.common_organization_path(organization) assert expected == actual @@ -1786,7 +1812,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = UrlMapsClient.common_project_path(project) assert expected == actual @@ -1806,7 +1831,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1833,7 +1857,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.UrlMapsTransport, "_prep_wrapped_messages" ) as prep: client = UrlMapsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1842,6 +1866,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = UrlMapsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_vpn_gateways.py b/tests/unit/gapic/compute_v1/test_vpn_gateways.py index 157af53ec..35b1b4092 100644 --- a/tests/unit/gapic/compute_v1/test_vpn_gateways.py +++ b/tests/unit/gapic/compute_v1/test_vpn_gateways.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -84,7 +113,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [VpnGatewaysClient,]) def test_vpn_gateways_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -99,7 +128,7 @@ def test_vpn_gateways_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [VpnGatewaysClient,]) def test_vpn_gateways_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -138,7 +167,7 @@ def test_vpn_gateways_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(VpnGatewaysClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -374,7 +403,7 @@ def test_aggregated_list_rest( transport: str = "rest", request_type=compute.AggregatedListVpnGatewaysRequest ): client = VpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -401,17 +430,16 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.VpnGatewayAggregatedList.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 == { @@ -433,7 +461,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = VpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = VpnGatewaysClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -456,12 +484,11 @@ def test_aggregated_list_rest_flattened(): 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 = VpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = VpnGatewaysClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -472,12 +499,11 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = VpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = VpnGatewaysClient(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.VpnGatewayAggregatedList( items={ @@ -498,7 +524,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -520,7 +545,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -541,7 +565,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteVpnGatewayRequest ): client = VpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -576,17 +600,16 @@ def test_delete_rest( 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" @@ -620,7 +643,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = VpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = VpnGatewaysClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -647,16 +670,13 @@ def test_delete_rest_flattened(): 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 "vpn_gateway_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = VpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = VpnGatewaysClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -671,7 +691,7 @@ def test_delete_rest_flattened_error(): def test_get_rest(transport: str = "rest", request_type=compute.GetVpnGatewayRequest): client = VpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -694,17 +714,16 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetVpnGatewayReq self_link="self_link_value", vpn_interfaces=[compute.VpnGatewayVpnGatewayInterface(id=205)], ) + # Wrap the value into a proper Response obj json_return_value = compute.VpnGateway.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.VpnGateway) assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" @@ -724,7 +743,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = VpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = VpnGatewaysClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -751,16 +770,13 @@ def test_get_rest_flattened(): 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 "vpn_gateway_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = VpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = VpnGatewaysClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -777,7 +793,7 @@ def test_get_status_rest( transport: str = "rest", request_type=compute.GetStatusVpnGatewayRequest ): client = VpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -796,17 +812,16 @@ def test_get_status_rest( ] ), ) + # Wrap the value into a proper Response obj json_return_value = compute.VpnGatewaysGetStatusResponse.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_status(request) # Establish that the response is the type that we expect. - assert isinstance(response, compute.VpnGatewaysGetStatusResponse) assert response.result == compute.VpnGatewayStatus( vpn_connections=[ @@ -822,7 +837,7 @@ def test_get_status_rest_from_dict(): def test_get_status_rest_flattened(): - client = VpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = VpnGatewaysClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -849,16 +864,13 @@ def test_get_status_rest_flattened(): 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 "vpn_gateway_value" in http_call[1] + str(body) def test_get_status_rest_flattened_error(): - client = VpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = VpnGatewaysClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -875,7 +887,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertVpnGatewayRequest ): client = VpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -910,17 +922,16 @@ def test_insert_rest( 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" @@ -954,7 +965,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = VpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = VpnGatewaysClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -973,7 +984,6 @@ def test_insert_rest_flattened(): vpn_gateway_resource = compute.VpnGateway( creation_timestamp="creation_timestamp_value" ) - client.insert( project="project_value", region="region_value", @@ -985,11 +995,8 @@ def test_insert_rest_flattened(): 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.VpnGateway.to_json( vpn_gateway_resource, including_default_value_fields=False, @@ -998,7 +1005,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = VpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = VpnGatewaysClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1017,7 +1024,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListVpnGatewaysRequest ): client = VpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1035,17 +1042,16 @@ def test_list_rest( 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.VpnGatewayList.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 == [ @@ -1062,7 +1068,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = VpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = VpnGatewaysClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1087,14 +1093,12 @@ def test_list_rest_flattened(): 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 = VpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = VpnGatewaysClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1107,12 +1111,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = VpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = VpnGatewaysClient(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.VpnGatewayList( items=[ @@ -1130,7 +1133,6 @@ def test_list_pager(): items=[compute.VpnGateway(), compute.VpnGateway(),], ), ) - # Two responses for two calls response = response + response @@ -1149,7 +1151,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.VpnGateway) for i in results) pages = list(client.list(request={}).pages) @@ -1161,7 +1162,7 @@ def test_set_labels_rest( transport: str = "rest", request_type=compute.SetLabelsVpnGatewayRequest ): client = VpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1196,17 +1197,16 @@ def test_set_labels_rest( 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" @@ -1240,7 +1240,7 @@ def test_set_labels_rest_from_dict(): def test_set_labels_rest_flattened(): - client = VpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = VpnGatewaysClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1259,7 +1259,6 @@ def test_set_labels_rest_flattened(): region_set_labels_request_resource = compute.RegionSetLabelsRequest( label_fingerprint="label_fingerprint_value" ) - client.set_labels( project="project_value", region="region_value", @@ -1272,13 +1271,9 @@ def test_set_labels_rest_flattened(): 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, @@ -1287,7 +1282,7 @@ def test_set_labels_rest_flattened(): def test_set_labels_rest_flattened_error(): - client = VpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = VpnGatewaysClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1307,7 +1302,7 @@ def test_test_iam_permissions_rest( transport: str = "rest", request_type=compute.TestIamPermissionsVpnGatewayRequest ): client = VpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1320,17 +1315,16 @@ def test_test_iam_permissions_rest( 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"] @@ -1340,7 +1334,7 @@ def test_test_iam_permissions_rest_from_dict(): def test_test_iam_permissions_rest_flattened(): - client = VpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = VpnGatewaysClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1359,7 +1353,6 @@ def test_test_iam_permissions_rest_flattened(): test_permissions_request_resource = compute.TestPermissionsRequest( permissions=["permissions_value"] ) - client.test_iam_permissions( project="project_value", region="region_value", @@ -1372,13 +1365,9 @@ def test_test_iam_permissions_rest_flattened(): 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.TestPermissionsRequest.to_json( test_permissions_request_resource, including_default_value_fields=False, @@ -1387,7 +1376,7 @@ def test_test_iam_permissions_rest_flattened(): def test_test_iam_permissions_rest_flattened_error(): - client = VpnGatewaysClient(credentials=credentials.AnonymousCredentials(),) + client = VpnGatewaysClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1406,16 +1395,16 @@ def test_test_iam_permissions_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.VpnGatewaysRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = VpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.VpnGatewaysRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = VpnGatewaysClient( @@ -1425,7 +1414,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.VpnGatewaysRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = VpnGatewaysClient( @@ -1436,7 +1425,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.VpnGatewaysRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = VpnGatewaysClient(transport=transport) assert client.transport is transport @@ -1445,17 +1434,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.VpnGatewaysRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_vpn_gateways_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.VpnGatewaysTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1467,7 +1456,7 @@ def test_vpn_gateways_base_transport(): ) as Transport: Transport.return_value = None transport = transports.VpnGatewaysTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1487,15 +1476,40 @@ def test_vpn_gateways_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_vpn_gateways_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.vpn_gateways.transports.VpnGatewaysTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VpnGatewaysTransport( + 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_vpn_gateways_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.vpn_gateways.transports.VpnGatewaysTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.VpnGatewaysTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1511,19 +1525,36 @@ def test_vpn_gateways_base_transport_with_credentials_file(): def test_vpn_gateways_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.vpn_gateways.transports.VpnGatewaysTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.VpnGatewaysTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_vpn_gateways_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + VpnGatewaysClient() + 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_vpn_gateways_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) VpnGatewaysClient() adc.assert_called_once_with( scopes=( @@ -1535,7 +1566,7 @@ def test_vpn_gateways_auth_adc(): def test_vpn_gateways_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1547,7 +1578,7 @@ def test_vpn_gateways_http_transport_client_cert_source_for_mtls(): def test_vpn_gateways_host_no_port(): client = VpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1557,7 +1588,7 @@ def test_vpn_gateways_host_no_port(): def test_vpn_gateways_host_with_port(): client = VpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1567,7 +1598,6 @@ def test_vpn_gateways_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1588,7 +1618,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = VpnGatewaysClient.common_folder_path(folder) assert expected == actual @@ -1607,7 +1636,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = VpnGatewaysClient.common_organization_path(organization) assert expected == actual @@ -1626,7 +1654,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = VpnGatewaysClient.common_project_path(project) assert expected == actual @@ -1646,7 +1673,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1673,7 +1699,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.VpnGatewaysTransport, "_prep_wrapped_messages" ) as prep: client = VpnGatewaysClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1682,6 +1708,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = VpnGatewaysClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_vpn_tunnels.py b/tests/unit/gapic/compute_v1/test_vpn_tunnels.py index 0dd5be446..732e5ed8f 100644 --- a/tests/unit/gapic/compute_v1/test_vpn_tunnels.py +++ b/tests/unit/gapic/compute_v1/test_vpn_tunnels.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -84,7 +113,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [VpnTunnelsClient,]) def test_vpn_tunnels_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -99,7 +128,7 @@ def test_vpn_tunnels_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [VpnTunnelsClient,]) def test_vpn_tunnels_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -138,7 +167,7 @@ def test_vpn_tunnels_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(VpnTunnelsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -374,7 +403,7 @@ def test_aggregated_list_rest( transport: str = "rest", request_type=compute.AggregatedListVpnTunnelsRequest ): client = VpnTunnelsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -399,17 +428,16 @@ def test_aggregated_list_rest( unreachables=["unreachables_value"], warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) + # Wrap the value into a proper Response obj json_return_value = compute.VpnTunnelAggregatedList.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 == { @@ -431,7 +459,7 @@ def test_aggregated_list_rest_from_dict(): def test_aggregated_list_rest_flattened(): - client = VpnTunnelsClient(credentials=credentials.AnonymousCredentials(),) + client = VpnTunnelsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -454,12 +482,11 @@ def test_aggregated_list_rest_flattened(): 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 = VpnTunnelsClient(credentials=credentials.AnonymousCredentials(),) + client = VpnTunnelsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -470,12 +497,11 @@ def test_aggregated_list_rest_flattened_error(): def test_aggregated_list_pager(): - client = VpnTunnelsClient(credentials=credentials.AnonymousCredentials(),) + client = VpnTunnelsClient(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.VpnTunnelAggregatedList( items={ @@ -496,7 +522,6 @@ def test_aggregated_list_pager(): }, ), ) - # Two responses for two calls response = response + response @@ -518,7 +543,6 @@ def test_aggregated_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, tuple) for i in results) for result in results: assert isinstance(result, tuple) @@ -536,7 +560,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteVpnTunnelRequest ): client = VpnTunnelsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -571,17 +595,16 @@ def test_delete_rest( 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" @@ -615,7 +638,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = VpnTunnelsClient(credentials=credentials.AnonymousCredentials(),) + client = VpnTunnelsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -642,16 +665,13 @@ def test_delete_rest_flattened(): 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 "vpn_tunnel_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = VpnTunnelsClient(credentials=credentials.AnonymousCredentials(),) + client = VpnTunnelsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -666,7 +686,7 @@ def test_delete_rest_flattened_error(): def test_get_rest(transport: str = "rest", request_type=compute.GetVpnTunnelRequest): client = VpnTunnelsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -700,17 +720,16 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetVpnTunnelRequ vpn_gateway="vpn_gateway_value", vpn_gateway_interface=2229, ) + # Wrap the value into a proper Response obj json_return_value = compute.VpnTunnel.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.VpnTunnel) assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" @@ -741,7 +760,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = VpnTunnelsClient(credentials=credentials.AnonymousCredentials(),) + client = VpnTunnelsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -768,16 +787,13 @@ def test_get_rest_flattened(): 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 "vpn_tunnel_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = VpnTunnelsClient(credentials=credentials.AnonymousCredentials(),) + client = VpnTunnelsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -794,7 +810,7 @@ def test_insert_rest( transport: str = "rest", request_type=compute.InsertVpnTunnelRequest ): client = VpnTunnelsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -829,17 +845,16 @@ def test_insert_rest( 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" @@ -873,7 +888,7 @@ def test_insert_rest_from_dict(): def test_insert_rest_flattened(): - client = VpnTunnelsClient(credentials=credentials.AnonymousCredentials(),) + client = VpnTunnelsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -892,7 +907,6 @@ def test_insert_rest_flattened(): vpn_tunnel_resource = compute.VpnTunnel( creation_timestamp="creation_timestamp_value" ) - client.insert( project="project_value", region="region_value", @@ -904,11 +918,8 @@ def test_insert_rest_flattened(): 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.VpnTunnel.to_json( vpn_tunnel_resource, including_default_value_fields=False, @@ -917,7 +928,7 @@ def test_insert_rest_flattened(): def test_insert_rest_flattened_error(): - client = VpnTunnelsClient(credentials=credentials.AnonymousCredentials(),) + client = VpnTunnelsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -934,7 +945,7 @@ def test_insert_rest_flattened_error(): def test_list_rest(transport: str = "rest", request_type=compute.ListVpnTunnelsRequest): client = VpnTunnelsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -952,17 +963,16 @@ def test_list_rest(transport: str = "rest", request_type=compute.ListVpnTunnelsR 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.VpnTunnelList.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 == [ @@ -979,7 +989,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = VpnTunnelsClient(credentials=credentials.AnonymousCredentials(),) + client = VpnTunnelsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -1004,14 +1014,12 @@ def test_list_rest_flattened(): 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 = VpnTunnelsClient(credentials=credentials.AnonymousCredentials(),) + client = VpnTunnelsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1024,12 +1032,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = VpnTunnelsClient(credentials=credentials.AnonymousCredentials(),) + client = VpnTunnelsClient(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.VpnTunnelList( items=[compute.VpnTunnel(), compute.VpnTunnel(), compute.VpnTunnel(),], @@ -1039,7 +1046,6 @@ def test_list_pager(): compute.VpnTunnelList(items=[compute.VpnTunnel(),], next_page_token="ghi",), compute.VpnTunnelList(items=[compute.VpnTunnel(), compute.VpnTunnel(),],), ) - # Two responses for two calls response = response + response @@ -1058,7 +1064,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.VpnTunnel) for i in results) pages = list(client.list(request={}).pages) @@ -1069,16 +1074,16 @@ def test_list_pager(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.VpnTunnelsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = VpnTunnelsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.VpnTunnelsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = VpnTunnelsClient( @@ -1088,7 +1093,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.VpnTunnelsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = VpnTunnelsClient( @@ -1099,7 +1104,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.VpnTunnelsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = VpnTunnelsClient(transport=transport) assert client.transport is transport @@ -1108,17 +1113,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.VpnTunnelsRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_vpn_tunnels_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.VpnTunnelsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1130,7 +1135,7 @@ def test_vpn_tunnels_base_transport(): ) as Transport: Transport.return_value = None transport = transports.VpnTunnelsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1147,15 +1152,40 @@ def test_vpn_tunnels_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_vpn_tunnels_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.vpn_tunnels.transports.VpnTunnelsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VpnTunnelsTransport( + 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_vpn_tunnels_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.vpn_tunnels.transports.VpnTunnelsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.VpnTunnelsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1171,19 +1201,36 @@ def test_vpn_tunnels_base_transport_with_credentials_file(): def test_vpn_tunnels_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.vpn_tunnels.transports.VpnTunnelsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.VpnTunnelsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_vpn_tunnels_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + VpnTunnelsClient() + 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_vpn_tunnels_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) VpnTunnelsClient() adc.assert_called_once_with( scopes=( @@ -1195,7 +1242,7 @@ def test_vpn_tunnels_auth_adc(): def test_vpn_tunnels_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -1207,7 +1254,7 @@ def test_vpn_tunnels_http_transport_client_cert_source_for_mtls(): def test_vpn_tunnels_host_no_port(): client = VpnTunnelsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1217,7 +1264,7 @@ def test_vpn_tunnels_host_no_port(): def test_vpn_tunnels_host_with_port(): client = VpnTunnelsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1227,7 +1274,6 @@ def test_vpn_tunnels_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1248,7 +1294,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = VpnTunnelsClient.common_folder_path(folder) assert expected == actual @@ -1267,7 +1312,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = VpnTunnelsClient.common_organization_path(organization) assert expected == actual @@ -1286,7 +1330,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = VpnTunnelsClient.common_project_path(project) assert expected == actual @@ -1306,7 +1349,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1333,7 +1375,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.VpnTunnelsTransport, "_prep_wrapped_messages" ) as prep: client = VpnTunnelsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1342,6 +1384,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = VpnTunnelsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_zone_operations.py b/tests/unit/gapic/compute_v1/test_zone_operations.py index 544dd93eb..57ddbeb46 100644 --- a/tests/unit/gapic/compute_v1/test_zone_operations.py +++ b/tests/unit/gapic/compute_v1/test_zone_operations.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,61 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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, +) 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 +# - 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", +) + +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(): @@ -87,7 +116,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [ZoneOperationsClient,]) def test_zone_operations_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -102,7 +131,7 @@ def test_zone_operations_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [ZoneOperationsClient,]) def test_zone_operations_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -143,7 +172,7 @@ def test_zone_operations_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(ZoneOperationsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -381,7 +410,7 @@ def test_delete_rest( transport: str = "rest", request_type=compute.DeleteZoneOperationRequest ): client = ZoneOperationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -392,17 +421,16 @@ def test_delete_rest( with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. return_value = compute.DeleteZoneOperationResponse() + # Wrap the value into a proper Response obj json_return_value = compute.DeleteZoneOperationResponse.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.DeleteZoneOperationResponse) @@ -411,7 +439,7 @@ def test_delete_rest_from_dict(): def test_delete_rest_flattened(): - client = ZoneOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = ZoneOperationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -436,16 +464,13 @@ def test_delete_rest_flattened(): 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 "operation_value" in http_call[1] + str(body) def test_delete_rest_flattened_error(): - client = ZoneOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = ZoneOperationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -462,7 +487,7 @@ def test_get_rest( transport: str = "rest", request_type=compute.GetZoneOperationRequest ): client = ZoneOperationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -497,17 +522,16 @@ def test_get_rest( 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.get(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" @@ -541,7 +565,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = ZoneOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = ZoneOperationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -566,16 +590,13 @@ def test_get_rest_flattened(): 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 "operation_value" in http_call[1] + str(body) def test_get_rest_flattened_error(): - client = ZoneOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = ZoneOperationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -592,7 +613,7 @@ def test_list_rest( transport: str = "rest", request_type=compute.ListZoneOperationsRequest ): client = ZoneOperationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -610,17 +631,16 @@ def test_list_rest( 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.OperationList.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 == [ @@ -637,7 +657,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = ZoneOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = ZoneOperationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -662,14 +682,12 @@ def test_list_rest_flattened(): 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) def test_list_rest_flattened_error(): - client = ZoneOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = ZoneOperationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -682,12 +700,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = ZoneOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = ZoneOperationsClient(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.OperationList( items=[compute.Operation(), compute.Operation(), compute.Operation(),], @@ -697,7 +714,6 @@ def test_list_pager(): compute.OperationList(items=[compute.Operation(),], next_page_token="ghi",), compute.OperationList(items=[compute.Operation(), compute.Operation(),],), ) - # Two responses for two calls response = response + response @@ -716,7 +732,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.Operation) for i in results) pages = list(client.list(request={}).pages) @@ -728,7 +743,7 @@ def test_wait_rest( transport: str = "rest", request_type=compute.WaitZoneOperationRequest ): client = ZoneOperationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -763,17 +778,16 @@ def test_wait_rest( 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.wait(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" @@ -807,7 +821,7 @@ def test_wait_rest_from_dict(): def test_wait_rest_flattened(): - client = ZoneOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = ZoneOperationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -832,16 +846,13 @@ def test_wait_rest_flattened(): 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 "operation_value" in http_call[1] + str(body) def test_wait_rest_flattened_error(): - client = ZoneOperationsClient(credentials=credentials.AnonymousCredentials(),) + client = ZoneOperationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -857,16 +868,16 @@ def test_wait_rest_flattened_error(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ZoneOperationsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ZoneOperationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.ZoneOperationsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ZoneOperationsClient( @@ -876,7 +887,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ZoneOperationsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ZoneOperationsClient( @@ -887,7 +898,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ZoneOperationsRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ZoneOperationsClient(transport=transport) assert client.transport is transport @@ -896,17 +907,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.ZoneOperationsRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_zone_operations_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ZoneOperationsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -918,7 +929,7 @@ def test_zone_operations_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ZoneOperationsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -934,15 +945,40 @@ def test_zone_operations_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_zone_operations_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.zone_operations.transports.ZoneOperationsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ZoneOperationsTransport( + 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_zone_operations_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.zone_operations.transports.ZoneOperationsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ZoneOperationsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -958,19 +994,36 @@ def test_zone_operations_base_transport_with_credentials_file(): def test_zone_operations_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.zone_operations.transports.ZoneOperationsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ZoneOperationsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_zone_operations_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ZoneOperationsClient() + 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_zone_operations_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) ZoneOperationsClient() adc.assert_called_once_with( scopes=( @@ -982,7 +1035,7 @@ def test_zone_operations_auth_adc(): def test_zone_operations_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -994,7 +1047,7 @@ def test_zone_operations_http_transport_client_cert_source_for_mtls(): def test_zone_operations_host_no_port(): client = ZoneOperationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -1004,7 +1057,7 @@ def test_zone_operations_host_no_port(): def test_zone_operations_host_with_port(): client = ZoneOperationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -1014,7 +1067,6 @@ def test_zone_operations_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1035,7 +1087,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = ZoneOperationsClient.common_folder_path(folder) assert expected == actual @@ -1054,7 +1105,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = ZoneOperationsClient.common_organization_path(organization) assert expected == actual @@ -1073,7 +1123,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = ZoneOperationsClient.common_project_path(project) assert expected == actual @@ -1093,7 +1142,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1120,7 +1168,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ZoneOperationsTransport, "_prep_wrapped_messages" ) as prep: client = ZoneOperationsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1129,6 +1177,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ZoneOperationsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/compute_v1/test_zones.py b/tests/unit/gapic/compute_v1/test_zones.py index ff94d158c..c4436babc 100644 --- a/tests/unit/gapic/compute_v1/test_zones.py +++ b/tests/unit/gapic/compute_v1/test_zones.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,31 +13,57 @@ # 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 import auth from google.api_core import client_options -from google.api_core import exceptions +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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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 +# - 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", +) + +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(): @@ -81,7 +106,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [ZonesClient,]) def test_zones_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -96,7 +121,7 @@ def test_zones_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [ZonesClient,]) def test_zones_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -133,7 +158,7 @@ def test_zones_client_get_transport_class(): def test_zones_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(ZonesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -367,7 +392,7 @@ def test_zones_client_client_options_credentials_file( def test_get_rest(transport: str = "rest", request_type=compute.GetZoneRequest): client = ZonesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -389,17 +414,16 @@ def test_get_rest(transport: str = "rest", request_type=compute.GetZoneRequest): self_link="self_link_value", status=compute.Zone.Status.DOWN, ) + # Wrap the value into a proper Response obj json_return_value = compute.Zone.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.Zone) assert response.available_cpu_platforms == ["available_cpu_platforms_value"] assert response.creation_timestamp == "creation_timestamp_value" @@ -418,7 +442,7 @@ def test_get_rest_from_dict(): def test_get_rest_flattened(): - client = ZonesClient(credentials=credentials.AnonymousCredentials(),) + client = ZonesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -443,14 +467,12 @@ def test_get_rest_flattened(): 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) def test_get_rest_flattened_error(): - client = ZonesClient(credentials=credentials.AnonymousCredentials(),) + client = ZonesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -462,7 +484,7 @@ def test_get_rest_flattened_error(): def test_list_rest(transport: str = "rest", request_type=compute.ListZonesRequest): client = ZonesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -482,17 +504,16 @@ def test_list_rest(transport: str = "rest", request_type=compute.ListZonesReques 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.ZoneList.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 == [ @@ -509,7 +530,7 @@ def test_list_rest_from_dict(): def test_list_rest_flattened(): - client = ZonesClient(credentials=credentials.AnonymousCredentials(),) + client = ZonesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: @@ -532,12 +553,11 @@ def test_list_rest_flattened(): 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 = ZonesClient(credentials=credentials.AnonymousCredentials(),) + client = ZonesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -548,12 +568,11 @@ def test_list_rest_flattened_error(): def test_list_pager(): - client = ZonesClient(credentials=credentials.AnonymousCredentials(),) + client = ZonesClient(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.ZoneList( items=[compute.Zone(), compute.Zone(), compute.Zone(),], @@ -563,7 +582,6 @@ def test_list_pager(): compute.ZoneList(items=[compute.Zone(),], next_page_token="ghi",), compute.ZoneList(items=[compute.Zone(), compute.Zone(),],), ) - # Two responses for two calls response = response + response @@ -582,7 +600,6 @@ def test_list_pager(): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, compute.Zone) for i in results) pages = list(client.list(request={}).pages) @@ -593,16 +610,16 @@ def test_list_pager(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ZonesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ZonesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.ZonesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ZonesClient( @@ -612,7 +629,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ZonesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ZonesClient( @@ -623,7 +640,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ZonesRestTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ZonesClient(transport=transport) assert client.transport is transport @@ -632,17 +649,17 @@ def test_transport_instance(): @pytest.mark.parametrize("transport_class", [transports.ZonesRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_zones_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ZonesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -654,7 +671,7 @@ def test_zones_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ZonesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -668,15 +685,41 @@ def test_zones_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_zones_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.zones.transports.ZonesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ZonesTransport( + 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.readonly", + "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_zones_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.zones.transports.ZonesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ZonesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -693,19 +736,37 @@ def test_zones_base_transport_with_credentials_file(): def test_zones_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.zones.transports.ZonesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ZonesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_zones_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ZonesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/compute.readonly", + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_zones_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) ZonesClient() adc.assert_called_once_with( scopes=( @@ -718,7 +779,7 @@ def test_zones_auth_adc(): def test_zones_http_transport_client_cert_source_for_mtls(): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: @@ -730,7 +791,7 @@ def test_zones_http_transport_client_cert_source_for_mtls(): def test_zones_host_no_port(): client = ZonesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), @@ -740,7 +801,7 @@ def test_zones_host_no_port(): def test_zones_host_with_port(): client = ZonesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), @@ -750,7 +811,6 @@ def test_zones_host_with_port(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -771,7 +831,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = ZonesClient.common_folder_path(folder) assert expected == actual @@ -790,7 +849,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = ZonesClient.common_organization_path(organization) assert expected == actual @@ -809,7 +867,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = ZonesClient.common_project_path(project) assert expected == actual @@ -829,7 +886,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -854,13 +910,13 @@ def test_client_withDEFAULT_CLIENT_INFO(): with mock.patch.object(transports.ZonesTransport, "_prep_wrapped_messages") as prep: client = ZonesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) with mock.patch.object(transports.ZonesTransport, "_prep_wrapped_messages") as prep: transport_class = ZonesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info)