From aedbee98cc6e56543c008ed5dc7f997d65e33944 Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Tue, 30 Jun 2026 06:42:13 +0000 Subject: [PATCH 01/23] feat: apply PEP 0810 lazy imports to google-cloud-compute --- .../google/cloud/compute_v1/__init__.py | 129 ++++++++++++++++++ 1 file changed, 129 insertions(+) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py index f66c8a775ee4..77cfaeedf3c2 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py @@ -23,6 +23,135 @@ from importlib import metadata +if sys.version_info >= (3, 15): + __lazy_modules__ = { + f"{__name__}.services.accelerator_types", + f"{__name__}.services.addresses", + f"{__name__}.services.advice", + f"{__name__}.services.autoscalers", + f"{__name__}.services.backend_buckets", + f"{__name__}.services.backend_services", + f"{__name__}.services.cross_site_networks", + f"{__name__}.services.disk_types", + f"{__name__}.services.disks", + f"{__name__}.services.external_vpn_gateways", + f"{__name__}.services.firewall_policies", + f"{__name__}.services.firewalls", + f"{__name__}.services.forwarding_rules", + f"{__name__}.services.future_reservations", + f"{__name__}.services.global_addresses", + f"{__name__}.services.global_forwarding_rules", + f"{__name__}.services.global_network_endpoint_groups", + f"{__name__}.services.global_operations", + f"{__name__}.services.global_organization_operations", + f"{__name__}.services.global_public_delegated_prefixes", + f"{__name__}.services.global_vm_extension_policies", + f"{__name__}.services.health_checks", + f"{__name__}.services.image_family_views", + f"{__name__}.services.images", + f"{__name__}.services.instance_group_manager_resize_requests", + f"{__name__}.services.instance_group_managers", + f"{__name__}.services.instance_groups", + f"{__name__}.services.instance_settings_service", + f"{__name__}.services.instance_templates", + f"{__name__}.services.instances", + f"{__name__}.services.instant_snapshot_groups", + f"{__name__}.services.instant_snapshots", + f"{__name__}.services.interconnect_attachment_groups", + f"{__name__}.services.interconnect_attachments", + f"{__name__}.services.interconnect_groups", + f"{__name__}.services.interconnect_locations", + f"{__name__}.services.interconnect_remote_locations", + f"{__name__}.services.interconnects", + f"{__name__}.services.license_codes", + f"{__name__}.services.licenses", + f"{__name__}.services.machine_images", + f"{__name__}.services.machine_types", + f"{__name__}.services.network_attachments", + f"{__name__}.services.network_edge_security_services", + f"{__name__}.services.network_endpoint_groups", + f"{__name__}.services.network_firewall_policies", + f"{__name__}.services.network_profiles", + f"{__name__}.services.networks", + f"{__name__}.services.node_groups", + f"{__name__}.services.node_templates", + f"{__name__}.services.node_types", + f"{__name__}.services.organization_security_policies", + f"{__name__}.services.packet_mirrorings", + f"{__name__}.services.preview_features", + f"{__name__}.services.projects", + f"{__name__}.services.public_advertised_prefixes", + f"{__name__}.services.public_delegated_prefixes", + f"{__name__}.services.region_autoscalers", + f"{__name__}.services.region_backend_buckets", + f"{__name__}.services.region_backend_services", + f"{__name__}.services.region_commitments", + f"{__name__}.services.region_composite_health_checks", + f"{__name__}.services.region_disk_types", + f"{__name__}.services.region_disks", + f"{__name__}.services.region_health_aggregation_policies", + f"{__name__}.services.region_health_check_services", + f"{__name__}.services.region_health_checks", + f"{__name__}.services.region_health_sources", + f"{__name__}.services.region_instance_group_manager_resize_requests", + f"{__name__}.services.region_instance_group_managers", + f"{__name__}.services.region_instance_groups", + f"{__name__}.services.region_instance_templates", + f"{__name__}.services.region_instances", + f"{__name__}.services.region_instant_snapshot_groups", + f"{__name__}.services.region_instant_snapshots", + f"{__name__}.services.region_network_endpoint_groups", + f"{__name__}.services.region_network_firewall_policies", + f"{__name__}.services.region_notification_endpoints", + f"{__name__}.services.region_operations", + f"{__name__}.services.region_security_policies", + f"{__name__}.services.region_snapshot_settings", + f"{__name__}.services.region_snapshots", + f"{__name__}.services.region_ssl_certificates", + f"{__name__}.services.region_ssl_policies", + f"{__name__}.services.region_target_http_proxies", + f"{__name__}.services.region_target_https_proxies", + f"{__name__}.services.region_target_tcp_proxies", + f"{__name__}.services.region_url_maps", + f"{__name__}.services.region_zones", + f"{__name__}.services.regions", + f"{__name__}.services.reservation_blocks", + f"{__name__}.services.reservation_slots", + f"{__name__}.services.reservation_sub_blocks", + f"{__name__}.services.reservations", + f"{__name__}.services.resource_policies", + f"{__name__}.services.rollout_plans", + f"{__name__}.services.rollouts", + f"{__name__}.services.routers", + f"{__name__}.services.routes", + f"{__name__}.services.security_policies", + f"{__name__}.services.service_attachments", + f"{__name__}.services.snapshot_settings_service", + f"{__name__}.services.snapshots", + f"{__name__}.services.ssl_certificates", + f"{__name__}.services.ssl_policies", + f"{__name__}.services.storage_pool_types", + f"{__name__}.services.storage_pools", + f"{__name__}.services.subnetworks", + f"{__name__}.services.target_grpc_proxies", + f"{__name__}.services.target_http_proxies", + f"{__name__}.services.target_https_proxies", + f"{__name__}.services.target_instances", + f"{__name__}.services.target_pools", + f"{__name__}.services.target_ssl_proxies", + f"{__name__}.services.target_tcp_proxies", + f"{__name__}.services.target_vpn_gateways", + f"{__name__}.services.url_maps", + f"{__name__}.services.vpn_gateways", + f"{__name__}.services.vpn_tunnels", + f"{__name__}.services.wire_groups", + f"{__name__}.services.zone_operations", + f"{__name__}.services.zone_vm_extension_policies", + f"{__name__}.services.zones", + f"{__name__}.types.compute", + } + + from .services.accelerator_types import AcceleratorTypesClient from .services.addresses import AddressesClient from .services.advice import AdviceClient From 4b3ba9d94992660c889d6d8ce456be69dfc10457 Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Tue, 30 Jun 2026 17:46:39 +0000 Subject: [PATCH 02/23] fix: remove python version guard for PEP 810 lazy imports --- .../google/cloud/compute_v1/__init__.py | 257 +++++++++--------- 1 file changed, 130 insertions(+), 127 deletions(-) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py index 77cfaeedf3c2..0e7172248bd9 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py @@ -23,133 +23,136 @@ from importlib import metadata -if sys.version_info >= (3, 15): - __lazy_modules__ = { - f"{__name__}.services.accelerator_types", - f"{__name__}.services.addresses", - f"{__name__}.services.advice", - f"{__name__}.services.autoscalers", - f"{__name__}.services.backend_buckets", - f"{__name__}.services.backend_services", - f"{__name__}.services.cross_site_networks", - f"{__name__}.services.disk_types", - f"{__name__}.services.disks", - f"{__name__}.services.external_vpn_gateways", - f"{__name__}.services.firewall_policies", - f"{__name__}.services.firewalls", - f"{__name__}.services.forwarding_rules", - f"{__name__}.services.future_reservations", - f"{__name__}.services.global_addresses", - f"{__name__}.services.global_forwarding_rules", - f"{__name__}.services.global_network_endpoint_groups", - f"{__name__}.services.global_operations", - f"{__name__}.services.global_organization_operations", - f"{__name__}.services.global_public_delegated_prefixes", - f"{__name__}.services.global_vm_extension_policies", - f"{__name__}.services.health_checks", - f"{__name__}.services.image_family_views", - f"{__name__}.services.images", - f"{__name__}.services.instance_group_manager_resize_requests", - f"{__name__}.services.instance_group_managers", - f"{__name__}.services.instance_groups", - f"{__name__}.services.instance_settings_service", - f"{__name__}.services.instance_templates", - f"{__name__}.services.instances", - f"{__name__}.services.instant_snapshot_groups", - f"{__name__}.services.instant_snapshots", - f"{__name__}.services.interconnect_attachment_groups", - f"{__name__}.services.interconnect_attachments", - f"{__name__}.services.interconnect_groups", - f"{__name__}.services.interconnect_locations", - f"{__name__}.services.interconnect_remote_locations", - f"{__name__}.services.interconnects", - f"{__name__}.services.license_codes", - f"{__name__}.services.licenses", - f"{__name__}.services.machine_images", - f"{__name__}.services.machine_types", - f"{__name__}.services.network_attachments", - f"{__name__}.services.network_edge_security_services", - f"{__name__}.services.network_endpoint_groups", - f"{__name__}.services.network_firewall_policies", - f"{__name__}.services.network_profiles", - f"{__name__}.services.networks", - f"{__name__}.services.node_groups", - f"{__name__}.services.node_templates", - f"{__name__}.services.node_types", - f"{__name__}.services.organization_security_policies", - f"{__name__}.services.packet_mirrorings", - f"{__name__}.services.preview_features", - f"{__name__}.services.projects", - f"{__name__}.services.public_advertised_prefixes", - f"{__name__}.services.public_delegated_prefixes", - f"{__name__}.services.region_autoscalers", - f"{__name__}.services.region_backend_buckets", - f"{__name__}.services.region_backend_services", - f"{__name__}.services.region_commitments", - f"{__name__}.services.region_composite_health_checks", - f"{__name__}.services.region_disk_types", - f"{__name__}.services.region_disks", - f"{__name__}.services.region_health_aggregation_policies", - f"{__name__}.services.region_health_check_services", - f"{__name__}.services.region_health_checks", - f"{__name__}.services.region_health_sources", - f"{__name__}.services.region_instance_group_manager_resize_requests", - f"{__name__}.services.region_instance_group_managers", - f"{__name__}.services.region_instance_groups", - f"{__name__}.services.region_instance_templates", - f"{__name__}.services.region_instances", - f"{__name__}.services.region_instant_snapshot_groups", - f"{__name__}.services.region_instant_snapshots", - f"{__name__}.services.region_network_endpoint_groups", - f"{__name__}.services.region_network_firewall_policies", - f"{__name__}.services.region_notification_endpoints", - f"{__name__}.services.region_operations", - f"{__name__}.services.region_security_policies", - f"{__name__}.services.region_snapshot_settings", - f"{__name__}.services.region_snapshots", - f"{__name__}.services.region_ssl_certificates", - f"{__name__}.services.region_ssl_policies", - f"{__name__}.services.region_target_http_proxies", - f"{__name__}.services.region_target_https_proxies", - f"{__name__}.services.region_target_tcp_proxies", - f"{__name__}.services.region_url_maps", - f"{__name__}.services.region_zones", - f"{__name__}.services.regions", - f"{__name__}.services.reservation_blocks", - f"{__name__}.services.reservation_slots", - f"{__name__}.services.reservation_sub_blocks", - f"{__name__}.services.reservations", - f"{__name__}.services.resource_policies", - f"{__name__}.services.rollout_plans", - f"{__name__}.services.rollouts", - f"{__name__}.services.routers", - f"{__name__}.services.routes", - f"{__name__}.services.security_policies", - f"{__name__}.services.service_attachments", - f"{__name__}.services.snapshot_settings_service", - f"{__name__}.services.snapshots", - f"{__name__}.services.ssl_certificates", - f"{__name__}.services.ssl_policies", - f"{__name__}.services.storage_pool_types", - f"{__name__}.services.storage_pools", - f"{__name__}.services.subnetworks", - f"{__name__}.services.target_grpc_proxies", - f"{__name__}.services.target_http_proxies", - f"{__name__}.services.target_https_proxies", - f"{__name__}.services.target_instances", - f"{__name__}.services.target_pools", - f"{__name__}.services.target_ssl_proxies", - f"{__name__}.services.target_tcp_proxies", - f"{__name__}.services.target_vpn_gateways", - f"{__name__}.services.url_maps", - f"{__name__}.services.vpn_gateways", - f"{__name__}.services.vpn_tunnels", - f"{__name__}.services.wire_groups", - f"{__name__}.services.zone_operations", - f"{__name__}.services.zone_vm_extension_policies", - f"{__name__}.services.zones", - f"{__name__}.types.compute", - } +# PEP 0810: Global Lazy Imports Control +# This variable provides a migration path for library maintainers. +# Python 3.15+ natively intercepts and defers these imports. +# Older Python versions safely ignore this variable. +__lazy_modules__ = { + f"{__name__}.services.accelerator_types", + f"{__name__}.services.addresses", + f"{__name__}.services.advice", + f"{__name__}.services.autoscalers", + f"{__name__}.services.backend_buckets", + f"{__name__}.services.backend_services", + f"{__name__}.services.cross_site_networks", + f"{__name__}.services.disk_types", + f"{__name__}.services.disks", + f"{__name__}.services.external_vpn_gateways", + f"{__name__}.services.firewall_policies", + f"{__name__}.services.firewalls", + f"{__name__}.services.forwarding_rules", + f"{__name__}.services.future_reservations", + f"{__name__}.services.global_addresses", + f"{__name__}.services.global_forwarding_rules", + f"{__name__}.services.global_network_endpoint_groups", + f"{__name__}.services.global_operations", + f"{__name__}.services.global_organization_operations", + f"{__name__}.services.global_public_delegated_prefixes", + f"{__name__}.services.global_vm_extension_policies", + f"{__name__}.services.health_checks", + f"{__name__}.services.image_family_views", + f"{__name__}.services.images", + f"{__name__}.services.instance_group_manager_resize_requests", + f"{__name__}.services.instance_group_managers", + f"{__name__}.services.instance_groups", + f"{__name__}.services.instance_settings_service", + f"{__name__}.services.instance_templates", + f"{__name__}.services.instances", + f"{__name__}.services.instant_snapshot_groups", + f"{__name__}.services.instant_snapshots", + f"{__name__}.services.interconnect_attachment_groups", + f"{__name__}.services.interconnect_attachments", + f"{__name__}.services.interconnect_groups", + f"{__name__}.services.interconnect_locations", + f"{__name__}.services.interconnect_remote_locations", + f"{__name__}.services.interconnects", + f"{__name__}.services.license_codes", + f"{__name__}.services.licenses", + f"{__name__}.services.machine_images", + f"{__name__}.services.machine_types", + f"{__name__}.services.network_attachments", + f"{__name__}.services.network_edge_security_services", + f"{__name__}.services.network_endpoint_groups", + f"{__name__}.services.network_firewall_policies", + f"{__name__}.services.network_profiles", + f"{__name__}.services.networks", + f"{__name__}.services.node_groups", + f"{__name__}.services.node_templates", + f"{__name__}.services.node_types", + f"{__name__}.services.organization_security_policies", + f"{__name__}.services.packet_mirrorings", + f"{__name__}.services.preview_features", + f"{__name__}.services.projects", + f"{__name__}.services.public_advertised_prefixes", + f"{__name__}.services.public_delegated_prefixes", + f"{__name__}.services.region_autoscalers", + f"{__name__}.services.region_backend_buckets", + f"{__name__}.services.region_backend_services", + f"{__name__}.services.region_commitments", + f"{__name__}.services.region_composite_health_checks", + f"{__name__}.services.region_disk_types", + f"{__name__}.services.region_disks", + f"{__name__}.services.region_health_aggregation_policies", + f"{__name__}.services.region_health_check_services", + f"{__name__}.services.region_health_checks", + f"{__name__}.services.region_health_sources", + f"{__name__}.services.region_instance_group_manager_resize_requests", + f"{__name__}.services.region_instance_group_managers", + f"{__name__}.services.region_instance_groups", + f"{__name__}.services.region_instance_templates", + f"{__name__}.services.region_instances", + f"{__name__}.services.region_instant_snapshot_groups", + f"{__name__}.services.region_instant_snapshots", + f"{__name__}.services.region_network_endpoint_groups", + f"{__name__}.services.region_network_firewall_policies", + f"{__name__}.services.region_notification_endpoints", + f"{__name__}.services.region_operations", + f"{__name__}.services.region_security_policies", + f"{__name__}.services.region_snapshot_settings", + f"{__name__}.services.region_snapshots", + f"{__name__}.services.region_ssl_certificates", + f"{__name__}.services.region_ssl_policies", + f"{__name__}.services.region_target_http_proxies", + f"{__name__}.services.region_target_https_proxies", + f"{__name__}.services.region_target_tcp_proxies", + f"{__name__}.services.region_url_maps", + f"{__name__}.services.region_zones", + f"{__name__}.services.regions", + f"{__name__}.services.reservation_blocks", + f"{__name__}.services.reservation_slots", + f"{__name__}.services.reservation_sub_blocks", + f"{__name__}.services.reservations", + f"{__name__}.services.resource_policies", + f"{__name__}.services.rollout_plans", + f"{__name__}.services.rollouts", + f"{__name__}.services.routers", + f"{__name__}.services.routes", + f"{__name__}.services.security_policies", + f"{__name__}.services.service_attachments", + f"{__name__}.services.snapshot_settings_service", + f"{__name__}.services.snapshots", + f"{__name__}.services.ssl_certificates", + f"{__name__}.services.ssl_policies", + f"{__name__}.services.storage_pool_types", + f"{__name__}.services.storage_pools", + f"{__name__}.services.subnetworks", + f"{__name__}.services.target_grpc_proxies", + f"{__name__}.services.target_http_proxies", + f"{__name__}.services.target_https_proxies", + f"{__name__}.services.target_instances", + f"{__name__}.services.target_pools", + f"{__name__}.services.target_ssl_proxies", + f"{__name__}.services.target_tcp_proxies", + f"{__name__}.services.target_vpn_gateways", + f"{__name__}.services.url_maps", + f"{__name__}.services.vpn_gateways", + f"{__name__}.services.vpn_tunnels", + f"{__name__}.services.wire_groups", + f"{__name__}.services.zone_operations", + f"{__name__}.services.zone_vm_extension_policies", + f"{__name__}.services.zones", + f"{__name__}.types.compute", +} from .services.accelerator_types import AcceleratorTypesClient From c60e977e8f42c9c5d30113451ab88699325c1ccd Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Mon, 6 Jul 2026 06:25:56 +0000 Subject: [PATCH 03/23] feat: centralize service-agnostic boilerplate into api_core for GAPIC clients --- .../google/api_core/gapic_v1/__init__.py | 3 + .../api_core/gapic_v1/client_helpers.py | 128 ++++++++++++++++++ .../services/key_management_service/client.py | 69 +++------- 3 files changed, 148 insertions(+), 52 deletions(-) create mode 100644 packages/google-api-core/google/api_core/gapic_v1/client_helpers.py diff --git a/packages/google-api-core/google/api_core/gapic_v1/__init__.py b/packages/google-api-core/google/api_core/gapic_v1/__init__.py index e5b7ad352ee6..992dacff883d 100644 --- a/packages/google-api-core/google/api_core/gapic_v1/__init__.py +++ b/packages/google-api-core/google/api_core/gapic_v1/__init__.py @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +from google.api_core.gapic_v1 import client_helpers from google.api_core.gapic_v1 import client_info from google.api_core.gapic_v1 import config from google.api_core.gapic_v1 import config_async @@ -20,6 +21,7 @@ from google.api_core.gapic_v1 import routing_header __all__ = [ + "client_helpers", "client_info", "config", "config_async", @@ -27,3 +29,4 @@ "method_async", "routing_header", ] + diff --git a/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py b/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py new file mode 100644 index 000000000000..79d5afc28b1e --- /dev/null +++ b/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py @@ -0,0 +1,128 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +"""Helpers for GAPIC client initialization.""" + +import os +import re +from typing import Optional + +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore + + + +def get_default_mtls_endpoint(api_endpoint: Optional[str]) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls_group, sandbox, googledomain = m.groups() + if mtls_group or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + +def use_client_cert_effective() -> bool: + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + +def get_api_endpoint( + api_override: Optional[str], + client_cert_source: Optional[bytes], + universe_domain: str, + use_mtls_endpoint: str, + default_universe: str, + default_mtls_endpoint: Optional[str], + default_endpoint_template: str, +) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (Optional[str]): The API endpoint override. + client_cert_source (Optional[bytes]): The client certificate source. + universe_domain (str): The universe domain. + use_mtls_endpoint (str): How to use the mTLS endpoint. + default_universe (str): The default universe. + default_mtls_endpoint (Optional[str]): The default mTLS endpoint. + default_endpoint_template (str): The default endpoint template. + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + if universe_domain != default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {default_universe}." + ) + api_endpoint = default_mtls_endpoint + else: + api_endpoint = default_endpoint_template.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py index 61224eacb11a..0309806577b0 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py @@ -145,28 +145,7 @@ def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: Returns: Optional[str]: converted mTLS api endpoint. """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - if m is None: - # Could not parse api_endpoint; return as-is. - return api_endpoint - - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + return gapic_v1.client_helpers.get_default_mtls_endpoint(api_endpoint) # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. DEFAULT_ENDPOINT = "cloudkms.googleapis.com" @@ -190,20 +169,10 @@ def _use_client_cert_effective(): ValueError: (If using a version of google-auth without should_use_client_cert and GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) """ - # check if google-auth version supports should_use_client_cert for automatic mTLS enablement - if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER - return mtls.should_use_client_cert() - else: # pragma: NO COVER - # if unsupported, fallback to reading from env var - use_client_cert_str = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() - if use_client_cert_str not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" - " either `true` or `false`" - ) - return use_client_cert_str == "true" + return gapic_v1.client_helpers.use_client_cert_effective() + + + @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -600,22 +569,18 @@ def _get_api_endpoint( Returns: str: The API endpoint to be used by the client. """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): - _default_universe = KeyManagementServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError( - f"mTLS is not supported in any universe other than {_default_universe}." - ) - api_endpoint = KeyManagementServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = KeyManagementServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=universe_domain - ) - return api_endpoint + return gapic_v1.client_helpers.get_api_endpoint( + api_override, + client_cert_source, + universe_domain, + use_mtls_endpoint, + KeyManagementServiceClient._DEFAULT_UNIVERSE, + KeyManagementServiceClient.DEFAULT_MTLS_ENDPOINT, + KeyManagementServiceClient._DEFAULT_ENDPOINT_TEMPLATE, + ) + + + @staticmethod def _get_universe_domain( From 4463094f7fabed0471ee2418ba88ee3801d73594 Mon Sep 17 00:00:00 2001 From: Heba Alazzeh <137334116+hebaalazzeh@users.noreply.github.com> Date: Sun, 5 Jul 2026 23:33:00 -0700 Subject: [PATCH 04/23] Update packages/google-api-core/google/api_core/gapic_v1/client_helpers.py Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com> --- .../google-api-core/google/api_core/gapic_v1/client_helpers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py b/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py index 79d5afc28b1e..68a3d3791717 100644 --- a/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py +++ b/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py @@ -18,7 +18,7 @@ import os import re -from typing import Optional +from typing import Any, Optional from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.auth.transport import mtls # type: ignore From 4d9bea23809f0f7340ae16002a0ad06a76d55bf9 Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Mon, 6 Jul 2026 06:38:09 +0000 Subject: [PATCH 05/23] refactor: optimize regex and update type hints in client_helpers --- .../api_core/gapic_v1/client_helpers.py | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py b/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py index 68a3d3791717..5d983e8a9ff1 100644 --- a/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py +++ b/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py @@ -23,6 +23,11 @@ from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.auth.transport import mtls # type: ignore +_MTLS_ENDPOINT_RE = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" +) + + def get_default_mtls_endpoint(api_endpoint: Optional[str]) -> Optional[str]: @@ -38,11 +43,7 @@ def get_default_mtls_endpoint(api_endpoint: Optional[str]) -> Optional[str]: if not api_endpoint: return api_endpoint - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) + m = _MTLS_ENDPOINT_RE.match(api_endpoint) if m is None: # Could not parse api_endpoint; return as-is. return api_endpoint @@ -89,18 +90,18 @@ def use_client_cert_effective() -> bool: def get_api_endpoint( api_override: Optional[str], - client_cert_source: Optional[bytes], + client_cert_source: Optional[Any], universe_domain: str, use_mtls_endpoint: str, default_universe: str, default_mtls_endpoint: Optional[str], default_endpoint_template: str, -) -> str: +) -> Optional[str]: """Return the API endpoint used by the client. Args: api_override (Optional[str]): The API endpoint override. - client_cert_source (Optional[bytes]): The client certificate source. + client_cert_source (Optional[Any]): The client certificate source. universe_domain (str): The universe domain. use_mtls_endpoint (str): How to use the mTLS endpoint. default_universe (str): The default universe. @@ -108,7 +109,7 @@ def get_api_endpoint( default_endpoint_template (str): The default endpoint template. Returns: - str: The API endpoint to be used by the client. + Optional[str]: The API endpoint to be used by the client. """ if api_override is not None: api_endpoint = api_override From 54cf6a043be4cff8e4033c90847e02211fd22d95 Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Mon, 6 Jul 2026 06:46:53 +0000 Subject: [PATCH 06/23] style: run black formatter on client_helpers.py --- .../google/api_core/gapic_v1/client_helpers.py | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py b/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py index 5d983e8a9ff1..4790f2ca0f6e 100644 --- a/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py +++ b/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py @@ -28,8 +28,6 @@ ) - - def get_default_mtls_endpoint(api_endpoint: Optional[str]) -> Optional[str]: """Converts api endpoint to mTLS endpoint. @@ -122,8 +120,5 @@ def get_api_endpoint( ) api_endpoint = default_mtls_endpoint else: - api_endpoint = default_endpoint_template.format( - UNIVERSE_DOMAIN=universe_domain - ) + api_endpoint = default_endpoint_template.format(UNIVERSE_DOMAIN=universe_domain) return api_endpoint - From 69260e514532934e73e86d1e75fcf345560243a1 Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Mon, 6 Jul 2026 06:53:11 +0000 Subject: [PATCH 07/23] fix: address lint and mypy issues in api_core and kms --- .../google-api-core/google/api_core/gapic_v1/__init__.py | 1 - .../google/api_core/gapic_v1/client_helpers.py | 8 ++++---- .../kms_v1/services/key_management_service/client.py | 6 ------ 3 files changed, 4 insertions(+), 11 deletions(-) diff --git a/packages/google-api-core/google/api_core/gapic_v1/__init__.py b/packages/google-api-core/google/api_core/gapic_v1/__init__.py index 992dacff883d..e8cae980d58a 100644 --- a/packages/google-api-core/google/api_core/gapic_v1/__init__.py +++ b/packages/google-api-core/google/api_core/gapic_v1/__init__.py @@ -29,4 +29,3 @@ "method_async", "routing_header", ] - diff --git a/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py b/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py index 4790f2ca0f6e..d34a8f1ad819 100644 --- a/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py +++ b/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py @@ -110,7 +110,7 @@ def get_api_endpoint( Optional[str]: The API endpoint to be used by the client. """ if api_override is not None: - api_endpoint = api_override + return api_override elif use_mtls_endpoint == "always" or ( use_mtls_endpoint == "auto" and client_cert_source ): @@ -118,7 +118,7 @@ def get_api_endpoint( raise MutualTLSChannelError( f"mTLS is not supported in any universe other than {default_universe}." ) - api_endpoint = default_mtls_endpoint + return default_mtls_endpoint else: - api_endpoint = default_endpoint_template.format(UNIVERSE_DOMAIN=universe_domain) - return api_endpoint + return default_endpoint_template.format(UNIVERSE_DOMAIN=universe_domain) + diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py index 0309806577b0..15ada5dff26d 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py @@ -171,9 +171,6 @@ def _use_client_cert_effective(): """ return gapic_v1.client_helpers.use_client_cert_effective() - - - @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -579,9 +576,6 @@ def _get_api_endpoint( KeyManagementServiceClient._DEFAULT_ENDPOINT_TEMPLATE, ) - - - @staticmethod def _get_universe_domain( client_universe_domain: Optional[str], universe_domain_env: Optional[str] From 46e07972677a7175c4bb3fd2e8dea3ceb149e374 Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Mon, 6 Jul 2026 07:19:49 +0000 Subject: [PATCH 08/23] fix: address black formatting issue in client_helpers.py --- .../google-api-core/google/api_core/gapic_v1/client_helpers.py | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py b/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py index d34a8f1ad819..3a50885150ae 100644 --- a/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py +++ b/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py @@ -121,4 +121,3 @@ def get_api_endpoint( return default_mtls_endpoint else: return default_endpoint_template.format(UNIVERSE_DOMAIN=universe_domain) - From a4513c44bc5eac473831119267eea5ce579f3163 Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Mon, 6 Jul 2026 15:52:15 +0000 Subject: [PATCH 09/23] fix: add underscore prefix to internal helpers in client_helpers.py --- .../google/api_core/gapic_v1/client_helpers.py | 6 +++--- .../cloud/kms_v1/services/key_management_service/client.py | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py b/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py index 3a50885150ae..3e0756364662 100644 --- a/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py +++ b/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py @@ -28,7 +28,7 @@ ) -def get_default_mtls_endpoint(api_endpoint: Optional[str]) -> Optional[str]: +def _get_default_mtls_endpoint(api_endpoint: Optional[str]) -> Optional[str]: """Converts api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to @@ -58,7 +58,7 @@ def get_default_mtls_endpoint(api_endpoint: Optional[str]) -> Optional[str]: return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") -def use_client_cert_effective() -> bool: +def _use_client_cert_effective() -> bool: """Returns whether client certificate should be used for mTLS if the google-auth version supports should_use_client_cert automatic mTLS enablement. @@ -86,7 +86,7 @@ def use_client_cert_effective() -> bool: return use_client_cert_str == "true" -def get_api_endpoint( +def _get_api_endpoint( api_override: Optional[str], client_cert_source: Optional[Any], universe_domain: str, diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py index 15ada5dff26d..e50e52d21355 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py @@ -145,7 +145,7 @@ def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: Returns: Optional[str]: converted mTLS api endpoint. """ - return gapic_v1.client_helpers.get_default_mtls_endpoint(api_endpoint) + return gapic_v1.client_helpers._get_default_mtls_endpoint(api_endpoint) # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. DEFAULT_ENDPOINT = "cloudkms.googleapis.com" @@ -169,7 +169,7 @@ def _use_client_cert_effective(): ValueError: (If using a version of google-auth without should_use_client_cert and GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) """ - return gapic_v1.client_helpers.use_client_cert_effective() + return gapic_v1.client_helpers._use_client_cert_effective() @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -566,7 +566,7 @@ def _get_api_endpoint( Returns: str: The API endpoint to be used by the client. """ - return gapic_v1.client_helpers.get_api_endpoint( + return gapic_v1.client_helpers._get_api_endpoint( api_override, client_cert_source, universe_domain, From ad1c01fc5410cd8bc751d4b61b9f6e4e2f5b5aa2 Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Mon, 6 Jul 2026 21:21:16 +0000 Subject: [PATCH 10/23] test: add unit tests for gapic client_helpers --- .../tests/unit/gapic/test_client_helpers.py | 133 ++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 packages/google-api-core/tests/unit/gapic/test_client_helpers.py diff --git a/packages/google-api-core/tests/unit/gapic/test_client_helpers.py b/packages/google-api-core/tests/unit/gapic/test_client_helpers.py new file mode 100644 index 000000000000..ad5d49a17649 --- /dev/null +++ b/packages/google-api-core/tests/unit/gapic/test_client_helpers.py @@ -0,0 +1,133 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +from unittest import mock +import pytest + +from google.api_core.gapic_v1 import client_helpers +from google.auth.exceptions import MutualTLSChannelError + + +def test__get_default_mtls_endpoint(): + # Test valid API endpoints + assert client_helpers._get_default_mtls_endpoint("foo.googleapis.com") == "foo.mtls.googleapis.com" + assert client_helpers._get_default_mtls_endpoint("foo.sandbox.googleapis.com") == "foo.mtls.sandbox.googleapis.com" + + # Test endpoints that shouldn't be converted + assert client_helpers._get_default_mtls_endpoint("foo.mtls.googleapis.com") == "foo.mtls.googleapis.com" + assert client_helpers._get_default_mtls_endpoint("foo.com") == "foo.com" + + # Test empty/None endpoints + assert client_helpers._get_default_mtls_endpoint("") == "" + assert client_helpers._get_default_mtls_endpoint(None) is None + + +@mock.patch("google.auth.transport.mtls.should_use_client_cert", autospec=True) +def test__use_client_cert_effective_with_google_auth(mock_should_use_client_cert): + # Test when google-auth supports the method + mock_should_use_client_cert.return_value = True + assert client_helpers._use_client_cert_effective() is True + + mock_should_use_client_cert.return_value = False + assert client_helpers._use_client_cert_effective() is False + + +@mock.patch.dict(os.environ, {}, clear=True) +def test__use_client_cert_effective_fallback(): + # We must patch hasattr to simulate google-auth lacking the method + with mock.patch("google.api_core.gapic_v1.client_helpers.hasattr", return_value=False): + # Default is false + assert client_helpers._use_client_cert_effective() is False + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert client_helpers._use_client_cert_effective() is True + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert client_helpers._use_client_cert_effective() is False + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "invalid"}): + with pytest.raises(ValueError, match="must be either `true` or `false`"): + client_helpers._use_client_cert_effective() + + +def test__get_api_endpoint_override(): + # If api_override is provided, it should be returned regardless of other args + endpoint = client_helpers._get_api_endpoint( + api_override="custom.endpoint.com", + client_cert_source=None, + universe_domain="googleapis.com", + use_mtls_endpoint="auto", + default_universe="googleapis.com", + default_mtls_endpoint="foo.mtls.googleapis.com", + default_endpoint_template="foo.{UNIVERSE_DOMAIN}", + ) + assert endpoint == "custom.endpoint.com" + + +def test__get_api_endpoint_mtls_always(): + # use_mtls_endpoint == "always" should use the default mtls endpoint + endpoint = client_helpers._get_api_endpoint( + api_override=None, + client_cert_source=None, + universe_domain="googleapis.com", + use_mtls_endpoint="always", + default_universe="googleapis.com", + default_mtls_endpoint="foo.mtls.googleapis.com", + default_endpoint_template="foo.{UNIVERSE_DOMAIN}", + ) + assert endpoint == "foo.mtls.googleapis.com" + + +def test__get_api_endpoint_mtls_auto_with_cert(): + # "auto" with client_cert_source should use mtls + endpoint = client_helpers._get_api_endpoint( + api_override=None, + client_cert_source=mock.Mock(), + universe_domain="googleapis.com", + use_mtls_endpoint="auto", + default_universe="googleapis.com", + default_mtls_endpoint="foo.mtls.googleapis.com", + default_endpoint_template="foo.{UNIVERSE_DOMAIN}", + ) + assert endpoint == "foo.mtls.googleapis.com" + + +def test__get_api_endpoint_mtls_auto_no_cert(): + # "auto" without client_cert_source should use the default template + endpoint = client_helpers._get_api_endpoint( + api_override=None, + client_cert_source=None, + universe_domain="googleapis.com", + use_mtls_endpoint="auto", + default_universe="googleapis.com", + default_mtls_endpoint="foo.mtls.googleapis.com", + default_endpoint_template="foo.{UNIVERSE_DOMAIN}", + ) + assert endpoint == "foo.googleapis.com" + + +def test__get_api_endpoint_mtls_universe_mismatch(): + # mTLS is only supported in the default universe + with pytest.raises(MutualTLSChannelError, match="mTLS is not supported"): + client_helpers._get_api_endpoint( + api_override=None, + client_cert_source=mock.Mock(), + universe_domain="custom-universe.com", + use_mtls_endpoint="auto", + default_universe="googleapis.com", + default_mtls_endpoint="foo.mtls.googleapis.com", + default_endpoint_template="foo.{UNIVERSE_DOMAIN}", + ) From 1456ead1dec1011b42f948c992e89aa38a6b0b0f Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Mon, 6 Jul 2026 21:49:28 +0000 Subject: [PATCH 11/23] chore: revert experimental kms validation changes --- .../services/key_management_service/client.py | 63 +++++++++++++++---- 1 file changed, 52 insertions(+), 11 deletions(-) diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py index e50e52d21355..61224eacb11a 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py @@ -145,7 +145,28 @@ def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: Returns: Optional[str]: converted mTLS api endpoint. """ - return gapic_v1.client_helpers._get_default_mtls_endpoint(api_endpoint) + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. DEFAULT_ENDPOINT = "cloudkms.googleapis.com" @@ -169,7 +190,20 @@ def _use_client_cert_effective(): ValueError: (If using a version of google-auth without should_use_client_cert and GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) """ - return gapic_v1.client_helpers._use_client_cert_effective() + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -566,15 +600,22 @@ def _get_api_endpoint( Returns: str: The API endpoint to be used by the client. """ - return gapic_v1.client_helpers._get_api_endpoint( - api_override, - client_cert_source, - universe_domain, - use_mtls_endpoint, - KeyManagementServiceClient._DEFAULT_UNIVERSE, - KeyManagementServiceClient.DEFAULT_MTLS_ENDPOINT, - KeyManagementServiceClient._DEFAULT_ENDPOINT_TEMPLATE, - ) + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = KeyManagementServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = KeyManagementServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = KeyManagementServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint @staticmethod def _get_universe_domain( From 0ffcdd39d2533fca64f221e9fe95687b120e6723 Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Mon, 6 Jul 2026 21:57:48 +0000 Subject: [PATCH 12/23] fix: resolve flake8 line length issues in tests --- .../tests/unit/gapic/test_client_helpers.py | 54 ++++++++++++------- 1 file changed, 36 insertions(+), 18 deletions(-) diff --git a/packages/google-api-core/tests/unit/gapic/test_client_helpers.py b/packages/google-api-core/tests/unit/gapic/test_client_helpers.py index ad5d49a17649..39a37ded1ed1 100644 --- a/packages/google-api-core/tests/unit/gapic/test_client_helpers.py +++ b/packages/google-api-core/tests/unit/gapic/test_client_helpers.py @@ -23,48 +23,66 @@ def test__get_default_mtls_endpoint(): # Test valid API endpoints - assert client_helpers._get_default_mtls_endpoint("foo.googleapis.com") == "foo.mtls.googleapis.com" - assert client_helpers._get_default_mtls_endpoint("foo.sandbox.googleapis.com") == "foo.mtls.sandbox.googleapis.com" - + assert ( + client_helpers._get_default_mtls_endpoint("foo.googleapis.com") + == "foo.mtls.googleapis.com" + ) + assert ( + client_helpers._get_default_mtls_endpoint("foo.sandbox.googleapis.com") + == "foo.mtls.sandbox.googleapis.com" + ) + # Test endpoints that shouldn't be converted - assert client_helpers._get_default_mtls_endpoint("foo.mtls.googleapis.com") == "foo.mtls.googleapis.com" + assert ( + client_helpers._get_default_mtls_endpoint("foo.mtls.googleapis.com") + == "foo.mtls.googleapis.com" + ) assert client_helpers._get_default_mtls_endpoint("foo.com") == "foo.com" - + # Test empty/None endpoints assert client_helpers._get_default_mtls_endpoint("") == "" assert client_helpers._get_default_mtls_endpoint(None) is None @mock.patch("google.auth.transport.mtls.should_use_client_cert", autospec=True) -def test__use_client_cert_effective_with_google_auth(mock_should_use_client_cert): +def test__use_client_cert_effective_with_google_auth(mock_method): # Test when google-auth supports the method - mock_should_use_client_cert.return_value = True + mock_method.return_value = True assert client_helpers._use_client_cert_effective() is True - - mock_should_use_client_cert.return_value = False + + mock_method.return_value = False assert client_helpers._use_client_cert_effective() is False @mock.patch.dict(os.environ, {}, clear=True) def test__use_client_cert_effective_fallback(): # We must patch hasattr to simulate google-auth lacking the method - with mock.patch("google.api_core.gapic_v1.client_helpers.hasattr", return_value=False): + with mock.patch( + "google.api_core.gapic_v1.client_helpers.hasattr", return_value=False + ): # Default is false assert client_helpers._use_client_cert_effective() is False - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + + env_true = {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"} + with mock.patch.dict(os.environ, env_true): assert client_helpers._use_client_cert_effective() is True - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} + ): assert client_helpers._use_client_cert_effective() is False - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "invalid"}): - with pytest.raises(ValueError, match="must be either `true` or `false`"): + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "invalid"} + ): + match_str = "must be either `true` or `false`" + with pytest.raises(ValueError, match=match_str): client_helpers._use_client_cert_effective() def test__get_api_endpoint_override(): - # If api_override is provided, it should be returned regardless of other args + # If api_override is provided, it should be returned + # regardless of other args endpoint = client_helpers._get_api_endpoint( api_override="custom.endpoint.com", client_cert_source=None, From 2168bc012bc921cb9833a76bbce3be39984175a8 Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Mon, 6 Jul 2026 22:05:45 +0000 Subject: [PATCH 13/23] chore: revert experimental PEP 0810 lazy loading in compute --- .../google/cloud/compute_v1/__init__.py | 132 ------------------ 1 file changed, 132 deletions(-) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py index 0e7172248bd9..f66c8a775ee4 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py @@ -23,138 +23,6 @@ from importlib import metadata -# PEP 0810: Global Lazy Imports Control -# This variable provides a migration path for library maintainers. -# Python 3.15+ natively intercepts and defers these imports. -# Older Python versions safely ignore this variable. -__lazy_modules__ = { - f"{__name__}.services.accelerator_types", - f"{__name__}.services.addresses", - f"{__name__}.services.advice", - f"{__name__}.services.autoscalers", - f"{__name__}.services.backend_buckets", - f"{__name__}.services.backend_services", - f"{__name__}.services.cross_site_networks", - f"{__name__}.services.disk_types", - f"{__name__}.services.disks", - f"{__name__}.services.external_vpn_gateways", - f"{__name__}.services.firewall_policies", - f"{__name__}.services.firewalls", - f"{__name__}.services.forwarding_rules", - f"{__name__}.services.future_reservations", - f"{__name__}.services.global_addresses", - f"{__name__}.services.global_forwarding_rules", - f"{__name__}.services.global_network_endpoint_groups", - f"{__name__}.services.global_operations", - f"{__name__}.services.global_organization_operations", - f"{__name__}.services.global_public_delegated_prefixes", - f"{__name__}.services.global_vm_extension_policies", - f"{__name__}.services.health_checks", - f"{__name__}.services.image_family_views", - f"{__name__}.services.images", - f"{__name__}.services.instance_group_manager_resize_requests", - f"{__name__}.services.instance_group_managers", - f"{__name__}.services.instance_groups", - f"{__name__}.services.instance_settings_service", - f"{__name__}.services.instance_templates", - f"{__name__}.services.instances", - f"{__name__}.services.instant_snapshot_groups", - f"{__name__}.services.instant_snapshots", - f"{__name__}.services.interconnect_attachment_groups", - f"{__name__}.services.interconnect_attachments", - f"{__name__}.services.interconnect_groups", - f"{__name__}.services.interconnect_locations", - f"{__name__}.services.interconnect_remote_locations", - f"{__name__}.services.interconnects", - f"{__name__}.services.license_codes", - f"{__name__}.services.licenses", - f"{__name__}.services.machine_images", - f"{__name__}.services.machine_types", - f"{__name__}.services.network_attachments", - f"{__name__}.services.network_edge_security_services", - f"{__name__}.services.network_endpoint_groups", - f"{__name__}.services.network_firewall_policies", - f"{__name__}.services.network_profiles", - f"{__name__}.services.networks", - f"{__name__}.services.node_groups", - f"{__name__}.services.node_templates", - f"{__name__}.services.node_types", - f"{__name__}.services.organization_security_policies", - f"{__name__}.services.packet_mirrorings", - f"{__name__}.services.preview_features", - f"{__name__}.services.projects", - f"{__name__}.services.public_advertised_prefixes", - f"{__name__}.services.public_delegated_prefixes", - f"{__name__}.services.region_autoscalers", - f"{__name__}.services.region_backend_buckets", - f"{__name__}.services.region_backend_services", - f"{__name__}.services.region_commitments", - f"{__name__}.services.region_composite_health_checks", - f"{__name__}.services.region_disk_types", - f"{__name__}.services.region_disks", - f"{__name__}.services.region_health_aggregation_policies", - f"{__name__}.services.region_health_check_services", - f"{__name__}.services.region_health_checks", - f"{__name__}.services.region_health_sources", - f"{__name__}.services.region_instance_group_manager_resize_requests", - f"{__name__}.services.region_instance_group_managers", - f"{__name__}.services.region_instance_groups", - f"{__name__}.services.region_instance_templates", - f"{__name__}.services.region_instances", - f"{__name__}.services.region_instant_snapshot_groups", - f"{__name__}.services.region_instant_snapshots", - f"{__name__}.services.region_network_endpoint_groups", - f"{__name__}.services.region_network_firewall_policies", - f"{__name__}.services.region_notification_endpoints", - f"{__name__}.services.region_operations", - f"{__name__}.services.region_security_policies", - f"{__name__}.services.region_snapshot_settings", - f"{__name__}.services.region_snapshots", - f"{__name__}.services.region_ssl_certificates", - f"{__name__}.services.region_ssl_policies", - f"{__name__}.services.region_target_http_proxies", - f"{__name__}.services.region_target_https_proxies", - f"{__name__}.services.region_target_tcp_proxies", - f"{__name__}.services.region_url_maps", - f"{__name__}.services.region_zones", - f"{__name__}.services.regions", - f"{__name__}.services.reservation_blocks", - f"{__name__}.services.reservation_slots", - f"{__name__}.services.reservation_sub_blocks", - f"{__name__}.services.reservations", - f"{__name__}.services.resource_policies", - f"{__name__}.services.rollout_plans", - f"{__name__}.services.rollouts", - f"{__name__}.services.routers", - f"{__name__}.services.routes", - f"{__name__}.services.security_policies", - f"{__name__}.services.service_attachments", - f"{__name__}.services.snapshot_settings_service", - f"{__name__}.services.snapshots", - f"{__name__}.services.ssl_certificates", - f"{__name__}.services.ssl_policies", - f"{__name__}.services.storage_pool_types", - f"{__name__}.services.storage_pools", - f"{__name__}.services.subnetworks", - f"{__name__}.services.target_grpc_proxies", - f"{__name__}.services.target_http_proxies", - f"{__name__}.services.target_https_proxies", - f"{__name__}.services.target_instances", - f"{__name__}.services.target_pools", - f"{__name__}.services.target_ssl_proxies", - f"{__name__}.services.target_tcp_proxies", - f"{__name__}.services.target_vpn_gateways", - f"{__name__}.services.url_maps", - f"{__name__}.services.vpn_gateways", - f"{__name__}.services.vpn_tunnels", - f"{__name__}.services.wire_groups", - f"{__name__}.services.zone_operations", - f"{__name__}.services.zone_vm_extension_policies", - f"{__name__}.services.zones", - f"{__name__}.types.compute", -} - - from .services.accelerator_types import AcceleratorTypesClient from .services.addresses import AddressesClient from .services.advice import AdviceClient From 5abeb855cda83a30f72bafea6a9d35ac62589375 Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Mon, 6 Jul 2026 22:25:21 +0000 Subject: [PATCH 14/23] feat: centralize additional client helpers to api_core --- .../api_core/gapic_v1/client_helpers.py | 144 ++++++++++++++++-- .../tests/unit/gapic/test_client_helpers.py | 109 +++++++++++++ 2 files changed, 243 insertions(+), 10 deletions(-) diff --git a/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py b/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py index 3e0756364662..82aad16b1580 100644 --- a/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py +++ b/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py @@ -18,13 +18,15 @@ import os import re -from typing import Any, Optional +import uuid +from typing import Any, Optional, Tuple from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.auth.transport import mtls # type: ignore _MTLS_ENDPOINT_RE = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?" + r"(?P\.googleapis\.com)?" ) @@ -60,17 +62,20 @@ def _get_default_mtls_endpoint(api_endpoint: Optional[str]) -> Optional[str]: def _use_client_cert_effective() -> bool: """Returns whether client certificate should be used for mTLS if the - google-auth version supports should_use_client_cert automatic mTLS enablement. + google-auth version supports should_use_client_cert automatic mTLS + enablement. Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. Returns: bool: whether client certificate should be used for mTLS Raises: - ValueError: (If using a version of google-auth without should_use_client_cert and - GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + ValueError: (If using a version of google-auth without + should_use_client_cert and GOOGLE_API_USE_CLIENT_CERTIFICATE is + set to an unexpected value.) """ - # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + # check if google-auth version supports should_use_client_cert for + # automatic mTLS enablement if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER return mtls.should_use_client_cert() else: # pragma: NO COVER @@ -80,8 +85,8 @@ def _use_client_cert_effective() -> bool: ).lower() if use_client_cert_str not in ("true", "false"): raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" - " either `true` or `false`" + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` " + "must be either `true` or `false`" ) return use_client_cert_str == "true" @@ -116,8 +121,127 @@ def _get_api_endpoint( ): if universe_domain != default_universe: raise MutualTLSChannelError( - f"mTLS is not supported in any universe other than {default_universe}." + f"mTLS is not supported in any universe other than " + f"{default_universe}." ) return default_mtls_endpoint else: - return default_endpoint_template.format(UNIVERSE_DOMAIN=universe_domain) + return default_endpoint_template.format( + UNIVERSE_DOMAIN=universe_domain + ) + + +def _read_environment_variables() -> Tuple[bool, str, Optional[str]]: + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, Optional[str]]: returns the + GOOGLE_API_USE_CLIENT_CERTIFICATE, GOOGLE_API_USE_MTLS_ENDPOINT, + and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If + GOOGLE_API_USE_MTLS_ENDPOINT is not any of + ["auto", "never", "always"]. + """ + use_client_cert = _use_client_cert_effective() + use_mtls_endpoint = os.getenv( + "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" + ).lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` " + "must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + +def _get_client_cert_source( + provided_cert_source: Optional[Any], use_cert_flag: bool +) -> Optional[Any]: + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the + client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif ( + hasattr(mtls, "has_default_client_cert_source") + and mtls.has_default_client_cert_source() + ): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + +def _get_universe_domain( + client_universe_domain: Optional[str], + universe_domain_env: Optional[str], + default_universe: str, +) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain + configured via the client options. + universe_domain_env (Optional[str]): The universe domain + configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" env var. + default_universe (str): The default universe domain. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = default_universe + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + +def _setup_request_id( + request: Any, field_name: str, is_proto3_optional: bool +) -> None: + """Populate a UUID4 field in the request if it is not already set. + + Args: + request (Union[google.protobuf.message.Message, dict]): The + request object. + field_name (str): The name of the field to populate. + is_proto3_optional (bool): Whether the field is proto3 optional. + """ + if isinstance(request, dict): + if is_proto3_optional: + if field_name not in request: + request[field_name] = str(uuid.uuid4()) + elif not request.get(field_name): + request[field_name] = str(uuid.uuid4()) + return + + if is_proto3_optional: + try: + # Pure protobuf messages + if not request.HasField(field_name): + setattr(request, field_name, str(uuid.uuid4())) + except (AttributeError, ValueError): + # Proto-plus messages or other objects + if field_name not in request: + setattr(request, field_name, str(uuid.uuid4())) + else: + if not getattr(request, field_name): + setattr(request, field_name, str(uuid.uuid4())) diff --git a/packages/google-api-core/tests/unit/gapic/test_client_helpers.py b/packages/google-api-core/tests/unit/gapic/test_client_helpers.py index 39a37ded1ed1..c43c51df029b 100644 --- a/packages/google-api-core/tests/unit/gapic/test_client_helpers.py +++ b/packages/google-api-core/tests/unit/gapic/test_client_helpers.py @@ -149,3 +149,112 @@ def test__get_api_endpoint_mtls_universe_mismatch(): default_mtls_endpoint="foo.mtls.googleapis.com", default_endpoint_template="foo.{UNIVERSE_DOMAIN}", ) + + +@mock.patch( + "google.api_core.gapic_v1.client_helpers._use_client_cert_effective" +) +@mock.patch.dict(os.environ, clear=True) +def test__read_environment_variables(mock_effective): + mock_effective.return_value = True + os.environ["GOOGLE_API_USE_MTLS_ENDPOINT"] = "always" + os.environ["GOOGLE_CLOUD_UNIVERSE_DOMAIN"] = "custom.com" + + cert, mtls, domain = client_helpers._read_environment_variables() + assert cert is True + assert mtls == "always" + assert domain == "custom.com" + + +@mock.patch.dict(os.environ, clear=True) +def test__read_environment_variables_invalid_mtls(): + os.environ["GOOGLE_API_USE_MTLS_ENDPOINT"] = "invalid" + with pytest.raises( + MutualTLSChannelError, match="must be `never`, `auto` or `always`" + ): + client_helpers._read_environment_variables() + + +@mock.patch("google.auth.transport.mtls.has_default_client_cert_source") +@mock.patch("google.auth.transport.mtls.default_client_cert_source") +def test__get_client_cert_source(mock_default, mock_has_default): + mock_default.return_value = b"default_cert" + mock_has_default.return_value = True + + # When use_cert_flag is False, return None + assert client_helpers._get_client_cert_source(b"provided", False) is None + + # When provided_cert_source is given, return provided + assert ( + client_helpers._get_client_cert_source(b"provided", True) + == b"provided" + ) + + # When no provided cert but default is available + assert ( + client_helpers._get_client_cert_source(None, True) == b"default_cert" + ) + + +def test__get_universe_domain(): + # client_universe_domain takes precedence + assert ( + client_helpers._get_universe_domain( + "client.com", "env.com", "default.com" + ) + == "client.com" + ) + + # env takes precedence over default + assert ( + client_helpers._get_universe_domain(None, "env.com", "default.com") + == "env.com" + ) + + # fallback to default + assert ( + client_helpers._get_universe_domain(None, None, "default.com") + == "default.com" + ) + + +def test__get_universe_domain_empty(): + with pytest.raises(ValueError, match="cannot be an empty string"): + client_helpers._get_universe_domain("", None, "default.com") + + +def test__setup_request_id(): + import uuid + + # test dict request + req = {} + client_helpers._setup_request_id(req, "request_id", True) + assert "request_id" in req + uuid_str = req["request_id"] + uuid.UUID(uuid_str) # verify it is a valid UUID + + # test dict request when already set + req = {"request_id": "existing"} + client_helpers._setup_request_id(req, "request_id", True) + assert req["request_id"] == "existing" + + class DummyRequest: + def __init__(self): + self.request_id = "" + + def HasField(self, field_name): + if not hasattr(self, field_name): + raise ValueError() + return bool(getattr(self, field_name)) + + # test object request proto3 optional true + req_obj = DummyRequest() + client_helpers._setup_request_id(req_obj, "request_id", True) + assert req_obj.request_id != "" + uuid.UUID(req_obj.request_id) + + # test object request proto3 optional false + req_obj2 = DummyRequest() + client_helpers._setup_request_id(req_obj2, "request_id", False) + assert req_obj2.request_id != "" + uuid.UUID(req_obj2.request_id) From 09243e92724d464ea4b4cd1732a61dc5c75ff394 Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Mon, 6 Jul 2026 22:41:51 +0000 Subject: [PATCH 15/23] test: mock missing google-auth mtls attributes --- .../tests/unit/gapic/test_client_helpers.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/google-api-core/tests/unit/gapic/test_client_helpers.py b/packages/google-api-core/tests/unit/gapic/test_client_helpers.py index c43c51df029b..658ecb82f5ca 100644 --- a/packages/google-api-core/tests/unit/gapic/test_client_helpers.py +++ b/packages/google-api-core/tests/unit/gapic/test_client_helpers.py @@ -175,8 +175,12 @@ def test__read_environment_variables_invalid_mtls(): client_helpers._read_environment_variables() -@mock.patch("google.auth.transport.mtls.has_default_client_cert_source") -@mock.patch("google.auth.transport.mtls.default_client_cert_source") +@mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", create=True +) +@mock.patch( + "google.auth.transport.mtls.default_client_cert_source", create=True +) def test__get_client_cert_source(mock_default, mock_has_default): mock_default.return_value = b"default_cert" mock_has_default.return_value = True From be2b472a773f28800469ca53011769713e426d57 Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Mon, 6 Jul 2026 22:48:15 +0000 Subject: [PATCH 16/23] style: remove manual 79-char line breaks to satisfy black --- .../api_core/gapic_v1/client_helpers.py | 12 ++----- .../tests/unit/gapic/test_client_helpers.py | 31 +++++-------------- 2 files changed, 11 insertions(+), 32 deletions(-) diff --git a/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py b/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py index 82aad16b1580..0bc8d8cd1ae1 100644 --- a/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py +++ b/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py @@ -126,9 +126,7 @@ def _get_api_endpoint( ) return default_mtls_endpoint else: - return default_endpoint_template.format( - UNIVERSE_DOMAIN=universe_domain - ) + return default_endpoint_template.format(UNIVERSE_DOMAIN=universe_domain) def _read_environment_variables() -> Tuple[bool, str, Optional[str]]: @@ -147,9 +145,7 @@ def _read_environment_variables() -> Tuple[bool, str, Optional[str]]: ["auto", "never", "always"]. """ use_client_cert = _use_client_cert_effective() - use_mtls_endpoint = os.getenv( - "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" - ).lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( @@ -214,9 +210,7 @@ def _get_universe_domain( return universe_domain -def _setup_request_id( - request: Any, field_name: str, is_proto3_optional: bool -) -> None: +def _setup_request_id(request: Any, field_name: str, is_proto3_optional: bool) -> None: """Populate a UUID4 field in the request if it is not already set. Args: diff --git a/packages/google-api-core/tests/unit/gapic/test_client_helpers.py b/packages/google-api-core/tests/unit/gapic/test_client_helpers.py index 658ecb82f5ca..1c6928cfe010 100644 --- a/packages/google-api-core/tests/unit/gapic/test_client_helpers.py +++ b/packages/google-api-core/tests/unit/gapic/test_client_helpers.py @@ -151,9 +151,7 @@ def test__get_api_endpoint_mtls_universe_mismatch(): ) -@mock.patch( - "google.api_core.gapic_v1.client_helpers._use_client_cert_effective" -) +@mock.patch("google.api_core.gapic_v1.client_helpers._use_client_cert_effective") @mock.patch.dict(os.environ, clear=True) def test__read_environment_variables(mock_effective): mock_effective.return_value = True @@ -175,12 +173,8 @@ def test__read_environment_variables_invalid_mtls(): client_helpers._read_environment_variables() -@mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", create=True -) -@mock.patch( - "google.auth.transport.mtls.default_client_cert_source", create=True -) +@mock.patch("google.auth.transport.mtls.has_default_client_cert_source", create=True) +@mock.patch("google.auth.transport.mtls.default_client_cert_source", create=True) def test__get_client_cert_source(mock_default, mock_has_default): mock_default.return_value = b"default_cert" mock_has_default.return_value = True @@ -189,36 +183,27 @@ def test__get_client_cert_source(mock_default, mock_has_default): assert client_helpers._get_client_cert_source(b"provided", False) is None # When provided_cert_source is given, return provided - assert ( - client_helpers._get_client_cert_source(b"provided", True) - == b"provided" - ) + assert client_helpers._get_client_cert_source(b"provided", True) == b"provided" # When no provided cert but default is available - assert ( - client_helpers._get_client_cert_source(None, True) == b"default_cert" - ) + assert client_helpers._get_client_cert_source(None, True) == b"default_cert" def test__get_universe_domain(): # client_universe_domain takes precedence assert ( - client_helpers._get_universe_domain( - "client.com", "env.com", "default.com" - ) + client_helpers._get_universe_domain("client.com", "env.com", "default.com") == "client.com" ) # env takes precedence over default assert ( - client_helpers._get_universe_domain(None, "env.com", "default.com") - == "env.com" + client_helpers._get_universe_domain(None, "env.com", "default.com") == "env.com" ) # fallback to default assert ( - client_helpers._get_universe_domain(None, None, "default.com") - == "default.com" + client_helpers._get_universe_domain(None, None, "default.com") == "default.com" ) From d386dfe73a5c389ed5d2fdea96c18b4cf4bb4fd4 Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Tue, 7 Jul 2026 19:24:23 +0000 Subject: [PATCH 17/23] refactor: remove underscore prefix from gapic client helpers --- .../api_core/gapic_v1/client_helpers.py | 26 +++-- .../tests/unit/gapic/test_client_helpers.py | 107 ++++++++++-------- 2 files changed, 76 insertions(+), 57 deletions(-) diff --git a/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py b/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py index 0bc8d8cd1ae1..0ae5929b6a93 100644 --- a/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py +++ b/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py @@ -30,7 +30,7 @@ ) -def _get_default_mtls_endpoint(api_endpoint: Optional[str]) -> Optional[str]: +def get_default_mtls_endpoint(api_endpoint: Optional[str]) -> Optional[str]: """Converts api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to @@ -60,7 +60,7 @@ def _get_default_mtls_endpoint(api_endpoint: Optional[str]) -> Optional[str]: return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") -def _use_client_cert_effective() -> bool: +def use_client_cert_effective() -> bool: """Returns whether client certificate should be used for mTLS if the google-auth version supports should_use_client_cert automatic mTLS enablement. @@ -91,7 +91,7 @@ def _use_client_cert_effective() -> bool: return use_client_cert_str == "true" -def _get_api_endpoint( +def get_api_endpoint( api_override: Optional[str], client_cert_source: Optional[Any], universe_domain: str, @@ -126,10 +126,12 @@ def _get_api_endpoint( ) return default_mtls_endpoint else: - return default_endpoint_template.format(UNIVERSE_DOMAIN=universe_domain) + return default_endpoint_template.format( + UNIVERSE_DOMAIN=universe_domain + ) -def _read_environment_variables() -> Tuple[bool, str, Optional[str]]: +def read_environment_variables() -> Tuple[bool, str, Optional[str]]: """Returns the environment variables used by the client. Returns: @@ -144,8 +146,10 @@ def _read_environment_variables() -> Tuple[bool, str, Optional[str]]: GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = _use_client_cert_effective() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + use_client_cert = use_client_cert_effective() + use_mtls_endpoint = os.getenv( + "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" + ).lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( @@ -155,7 +159,7 @@ def _read_environment_variables() -> Tuple[bool, str, Optional[str]]: return use_client_cert, use_mtls_endpoint, universe_domain_env -def _get_client_cert_source( +def get_client_cert_source( provided_cert_source: Optional[Any], use_cert_flag: bool ) -> Optional[Any]: """Return the client cert source to be used by the client. @@ -180,7 +184,7 @@ def _get_client_cert_source( return client_cert_source -def _get_universe_domain( +def get_universe_domain( client_universe_domain: Optional[str], universe_domain_env: Optional[str], default_universe: str, @@ -210,7 +214,9 @@ def _get_universe_domain( return universe_domain -def _setup_request_id(request: Any, field_name: str, is_proto3_optional: bool) -> None: +def setup_request_id( + request: Any, field_name: str, is_proto3_optional: bool +) -> None: """Populate a UUID4 field in the request if it is not already set. Args: diff --git a/packages/google-api-core/tests/unit/gapic/test_client_helpers.py b/packages/google-api-core/tests/unit/gapic/test_client_helpers.py index 1c6928cfe010..db7360dc193a 100644 --- a/packages/google-api-core/tests/unit/gapic/test_client_helpers.py +++ b/packages/google-api-core/tests/unit/gapic/test_client_helpers.py @@ -21,69 +21,69 @@ from google.auth.exceptions import MutualTLSChannelError -def test__get_default_mtls_endpoint(): +def test_get_default_mtls_endpoint(): # Test valid API endpoints assert ( - client_helpers._get_default_mtls_endpoint("foo.googleapis.com") + client_helpers.get_default_mtls_endpoint("foo.googleapis.com") == "foo.mtls.googleapis.com" ) assert ( - client_helpers._get_default_mtls_endpoint("foo.sandbox.googleapis.com") + client_helpers.get_default_mtls_endpoint("foo.sandbox.googleapis.com") == "foo.mtls.sandbox.googleapis.com" ) # Test endpoints that shouldn't be converted assert ( - client_helpers._get_default_mtls_endpoint("foo.mtls.googleapis.com") + client_helpers.get_default_mtls_endpoint("foo.mtls.googleapis.com") == "foo.mtls.googleapis.com" ) - assert client_helpers._get_default_mtls_endpoint("foo.com") == "foo.com" + assert client_helpers.get_default_mtls_endpoint("foo.com") == "foo.com" # Test empty/None endpoints - assert client_helpers._get_default_mtls_endpoint("") == "" - assert client_helpers._get_default_mtls_endpoint(None) is None + assert client_helpers.get_default_mtls_endpoint("") == "" + assert client_helpers.get_default_mtls_endpoint(None) is None @mock.patch("google.auth.transport.mtls.should_use_client_cert", autospec=True) -def test__use_client_cert_effective_with_google_auth(mock_method): +def test_use_client_cert_effective_with_google_auth(mock_method): # Test when google-auth supports the method mock_method.return_value = True - assert client_helpers._use_client_cert_effective() is True + assert client_helpers.use_client_cert_effective() is True mock_method.return_value = False - assert client_helpers._use_client_cert_effective() is False + assert client_helpers.use_client_cert_effective() is False @mock.patch.dict(os.environ, {}, clear=True) -def test__use_client_cert_effective_fallback(): +def test_use_client_cert_effective_fallback(): # We must patch hasattr to simulate google-auth lacking the method with mock.patch( "google.api_core.gapic_v1.client_helpers.hasattr", return_value=False ): # Default is false - assert client_helpers._use_client_cert_effective() is False + assert client_helpers.use_client_cert_effective() is False env_true = {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"} with mock.patch.dict(os.environ, env_true): - assert client_helpers._use_client_cert_effective() is True + assert client_helpers.use_client_cert_effective() is True with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} ): - assert client_helpers._use_client_cert_effective() is False + assert client_helpers.use_client_cert_effective() is False with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "invalid"} ): match_str = "must be either `true` or `false`" with pytest.raises(ValueError, match=match_str): - client_helpers._use_client_cert_effective() + client_helpers.use_client_cert_effective() -def test__get_api_endpoint_override(): +def test_get_api_endpoint_override(): # If api_override is provided, it should be returned # regardless of other args - endpoint = client_helpers._get_api_endpoint( + endpoint = client_helpers.get_api_endpoint( api_override="custom.endpoint.com", client_cert_source=None, universe_domain="googleapis.com", @@ -95,9 +95,9 @@ def test__get_api_endpoint_override(): assert endpoint == "custom.endpoint.com" -def test__get_api_endpoint_mtls_always(): +def test_get_api_endpoint_mtls_always(): # use_mtls_endpoint == "always" should use the default mtls endpoint - endpoint = client_helpers._get_api_endpoint( + endpoint = client_helpers.get_api_endpoint( api_override=None, client_cert_source=None, universe_domain="googleapis.com", @@ -109,9 +109,9 @@ def test__get_api_endpoint_mtls_always(): assert endpoint == "foo.mtls.googleapis.com" -def test__get_api_endpoint_mtls_auto_with_cert(): +def test_get_api_endpoint_mtls_auto_with_cert(): # "auto" with client_cert_source should use mtls - endpoint = client_helpers._get_api_endpoint( + endpoint = client_helpers.get_api_endpoint( api_override=None, client_cert_source=mock.Mock(), universe_domain="googleapis.com", @@ -123,9 +123,9 @@ def test__get_api_endpoint_mtls_auto_with_cert(): assert endpoint == "foo.mtls.googleapis.com" -def test__get_api_endpoint_mtls_auto_no_cert(): +def test_get_api_endpoint_mtls_auto_no_cert(): # "auto" without client_cert_source should use the default template - endpoint = client_helpers._get_api_endpoint( + endpoint = client_helpers.get_api_endpoint( api_override=None, client_cert_source=None, universe_domain="googleapis.com", @@ -137,10 +137,10 @@ def test__get_api_endpoint_mtls_auto_no_cert(): assert endpoint == "foo.googleapis.com" -def test__get_api_endpoint_mtls_universe_mismatch(): +def test_get_api_endpoint_mtls_universe_mismatch(): # mTLS is only supported in the default universe with pytest.raises(MutualTLSChannelError, match="mTLS is not supported"): - client_helpers._get_api_endpoint( + client_helpers.get_api_endpoint( api_override=None, client_cert_source=mock.Mock(), universe_domain="custom-universe.com", @@ -151,80 +151,93 @@ def test__get_api_endpoint_mtls_universe_mismatch(): ) -@mock.patch("google.api_core.gapic_v1.client_helpers._use_client_cert_effective") +@mock.patch( + "google.api_core.gapic_v1.client_helpers.use_client_cert_effective" +) @mock.patch.dict(os.environ, clear=True) -def test__read_environment_variables(mock_effective): +def test_read_environment_variables(mock_effective): mock_effective.return_value = True os.environ["GOOGLE_API_USE_MTLS_ENDPOINT"] = "always" os.environ["GOOGLE_CLOUD_UNIVERSE_DOMAIN"] = "custom.com" - cert, mtls, domain = client_helpers._read_environment_variables() + cert, mtls, domain = client_helpers.read_environment_variables() assert cert is True assert mtls == "always" assert domain == "custom.com" @mock.patch.dict(os.environ, clear=True) -def test__read_environment_variables_invalid_mtls(): +def test_read_environment_variables_invalid_mtls(): os.environ["GOOGLE_API_USE_MTLS_ENDPOINT"] = "invalid" with pytest.raises( MutualTLSChannelError, match="must be `never`, `auto` or `always`" ): - client_helpers._read_environment_variables() + client_helpers.read_environment_variables() -@mock.patch("google.auth.transport.mtls.has_default_client_cert_source", create=True) -@mock.patch("google.auth.transport.mtls.default_client_cert_source", create=True) -def test__get_client_cert_source(mock_default, mock_has_default): +@mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", create=True +) +@mock.patch( + "google.auth.transport.mtls.default_client_cert_source", create=True +) +def test_get_client_cert_source(mock_default, mock_has_default): mock_default.return_value = b"default_cert" mock_has_default.return_value = True # When use_cert_flag is False, return None - assert client_helpers._get_client_cert_source(b"provided", False) is None + assert client_helpers.get_client_cert_source(b"provided", False) is None # When provided_cert_source is given, return provided - assert client_helpers._get_client_cert_source(b"provided", True) == b"provided" + assert ( + client_helpers.get_client_cert_source(b"provided", True) + == b"provided" + ) # When no provided cert but default is available - assert client_helpers._get_client_cert_source(None, True) == b"default_cert" + assert client_helpers.get_client_cert_source(None, True) == b"default_cert" -def test__get_universe_domain(): +def test_get_universe_domain(): # client_universe_domain takes precedence assert ( - client_helpers._get_universe_domain("client.com", "env.com", "default.com") + client_helpers.get_universe_domain( + "client.com", "env.com", "default.com" + ) == "client.com" ) # env takes precedence over default assert ( - client_helpers._get_universe_domain(None, "env.com", "default.com") == "env.com" + client_helpers.get_universe_domain(None, "env.com", "default.com") + == "env.com" ) # fallback to default assert ( - client_helpers._get_universe_domain(None, None, "default.com") == "default.com" + client_helpers.get_universe_domain(None, None, "default.com") + == "default.com" ) -def test__get_universe_domain_empty(): +def test_get_universe_domain_empty(): with pytest.raises(ValueError, match="cannot be an empty string"): - client_helpers._get_universe_domain("", None, "default.com") + client_helpers.get_universe_domain("", None, "default.com") -def test__setup_request_id(): +def test_setup_request_id(): import uuid # test dict request req = {} - client_helpers._setup_request_id(req, "request_id", True) + client_helpers.setup_request_id(req, "request_id", True) assert "request_id" in req uuid_str = req["request_id"] uuid.UUID(uuid_str) # verify it is a valid UUID # test dict request when already set req = {"request_id": "existing"} - client_helpers._setup_request_id(req, "request_id", True) + client_helpers.setup_request_id(req, "request_id", True) assert req["request_id"] == "existing" class DummyRequest: @@ -238,12 +251,12 @@ def HasField(self, field_name): # test object request proto3 optional true req_obj = DummyRequest() - client_helpers._setup_request_id(req_obj, "request_id", True) + client_helpers.setup_request_id(req_obj, "request_id", True) assert req_obj.request_id != "" uuid.UUID(req_obj.request_id) # test object request proto3 optional false req_obj2 = DummyRequest() - client_helpers._setup_request_id(req_obj2, "request_id", False) + client_helpers.setup_request_id(req_obj2, "request_id", False) assert req_obj2.request_id != "" uuid.UUID(req_obj2.request_id) From 72d6561dd8339c298093706810405b908b15cfb5 Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Tue, 7 Jul 2026 20:36:38 +0000 Subject: [PATCH 18/23] fix: linting issues and add backward compatibility aliases for internal client_helpers methods --- .../google/api_core/gapic_v1/client_helpers.py | 16 +++++++++++++--- .../tests/unit/gapic/test_client_helpers.py | 17 ++++++++--------- 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py b/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py index 0ae5929b6a93..feaa44c2752a 100644 --- a/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py +++ b/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py @@ -128,7 +128,7 @@ def get_api_endpoint( else: return default_endpoint_template.format( UNIVERSE_DOMAIN=universe_domain - ) + ) # noqa: E501 def read_environment_variables() -> Tuple[bool, str, Optional[str]]: @@ -149,7 +149,7 @@ def read_environment_variables() -> Tuple[bool, str, Optional[str]]: use_client_cert = use_client_cert_effective() use_mtls_endpoint = os.getenv( "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" - ).lower() + ).lower() # noqa: E501 universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") if use_mtls_endpoint not in ("auto", "never", "always"): raise MutualTLSChannelError( @@ -216,7 +216,7 @@ def get_universe_domain( def setup_request_id( request: Any, field_name: str, is_proto3_optional: bool -) -> None: +) -> None: # noqa: E501 """Populate a UUID4 field in the request if it is not already set. Args: @@ -245,3 +245,13 @@ def setup_request_id( else: if not getattr(request, field_name): setattr(request, field_name, str(uuid.uuid4())) + + +# Backward compatibility aliases for private methods +# Previously, gapic-generator-python generated clients used these methods +_use_client_cert_effective = use_client_cert_effective +_get_default_mtls_endpoint = get_default_mtls_endpoint +_read_environment_variables = read_environment_variables +_get_client_cert_source = get_client_cert_source +_get_universe_domain = get_universe_domain +_setup_request_id = setup_request_id diff --git a/packages/google-api-core/tests/unit/gapic/test_client_helpers.py b/packages/google-api-core/tests/unit/gapic/test_client_helpers.py index db7360dc193a..aba4a20dc38c 100644 --- a/packages/google-api-core/tests/unit/gapic/test_client_helpers.py +++ b/packages/google-api-core/tests/unit/gapic/test_client_helpers.py @@ -153,7 +153,7 @@ def test_get_api_endpoint_mtls_universe_mismatch(): @mock.patch( "google.api_core.gapic_v1.client_helpers.use_client_cert_effective" -) +) # noqa: E501 @mock.patch.dict(os.environ, clear=True) def test_read_environment_variables(mock_effective): mock_effective.return_value = True @@ -177,10 +177,10 @@ def test_read_environment_variables_invalid_mtls(): @mock.patch( "google.auth.transport.mtls.has_default_client_cert_source", create=True -) +) # noqa: E501 @mock.patch( "google.auth.transport.mtls.default_client_cert_source", create=True -) +) # noqa: E501 def test_get_client_cert_source(mock_default, mock_has_default): mock_default.return_value = b"default_cert" mock_has_default.return_value = True @@ -190,9 +190,8 @@ def test_get_client_cert_source(mock_default, mock_has_default): # When provided_cert_source is given, return provided assert ( - client_helpers.get_client_cert_source(b"provided", True) - == b"provided" - ) + client_helpers.get_client_cert_source(b"provided", True) == b"provided" + ) # noqa: E501 # When no provided cert but default is available assert client_helpers.get_client_cert_source(None, True) == b"default_cert" @@ -203,20 +202,20 @@ def test_get_universe_domain(): assert ( client_helpers.get_universe_domain( "client.com", "env.com", "default.com" - ) + ) # noqa: E501 == "client.com" ) # env takes precedence over default assert ( client_helpers.get_universe_domain(None, "env.com", "default.com") - == "env.com" + == "env.com" # noqa: E501 ) # fallback to default assert ( client_helpers.get_universe_domain(None, None, "default.com") - == "default.com" + == "default.com" # noqa: E501 ) From 6a442829db933f9cc3efdf8f4900dbdab77e9faf Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Tue, 7 Jul 2026 20:44:27 +0000 Subject: [PATCH 19/23] fix: skip test_client_helpers in non-grpc environments --- .../google-api-core/tests/unit/gapic/test_client_helpers.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/packages/google-api-core/tests/unit/gapic/test_client_helpers.py b/packages/google-api-core/tests/unit/gapic/test_client_helpers.py index aba4a20dc38c..a162533add08 100644 --- a/packages/google-api-core/tests/unit/gapic/test_client_helpers.py +++ b/packages/google-api-core/tests/unit/gapic/test_client_helpers.py @@ -17,6 +17,11 @@ from unittest import mock import pytest +try: + import grpc # noqa: F401 +except ImportError: + pytest.skip("No GRPC", allow_module_level=True) + from google.api_core.gapic_v1 import client_helpers from google.auth.exceptions import MutualTLSChannelError From 2353e8227760e3dafa5bad0663a42de6f3c1bf3b Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Tue, 7 Jul 2026 20:53:08 +0000 Subject: [PATCH 20/23] fix: mock patch missing attribute in old google-auth versions --- .../google-api-core/tests/unit/gapic/test_client_helpers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/google-api-core/tests/unit/gapic/test_client_helpers.py b/packages/google-api-core/tests/unit/gapic/test_client_helpers.py index a162533add08..41826cbd1e5f 100644 --- a/packages/google-api-core/tests/unit/gapic/test_client_helpers.py +++ b/packages/google-api-core/tests/unit/gapic/test_client_helpers.py @@ -49,7 +49,7 @@ def test_get_default_mtls_endpoint(): assert client_helpers.get_default_mtls_endpoint(None) is None -@mock.patch("google.auth.transport.mtls.should_use_client_cert", autospec=True) +@mock.patch("google.auth.transport.mtls.should_use_client_cert", create=True) def test_use_client_cert_effective_with_google_auth(mock_method): # Test when google-auth supports the method mock_method.return_value = True From 7208833165619a3e05c48da9d74b40460c89cf24 Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Thu, 9 Jul 2026 19:17:33 +0000 Subject: [PATCH 21/23] feat: split client_helpers into domain-specific modules Splits the monolithic client_helpers.py into routing.py, client_cert.py, config_helpers.py, and method_helpers.py to improve readability and maintainability. Updates gapic_v1 exports and test imports accordingly. --- .../google/api_core/gapic_v1/__init__.py | 16 +- .../google/api_core/gapic_v1/_client_cert.py | 84 ++++++ .../api_core/gapic_v1/_config_helpers.py | 56 ++++ .../api_core/gapic_v1/_method_helpers.py | 58 ++++ .../google/api_core/gapic_v1/_routing.py | 106 ++++++++ .../api_core/gapic_v1/client_helpers.py | 257 ------------------ .../tests/unit/gapic/test_client_helpers.py | 85 +++--- 7 files changed, 353 insertions(+), 309 deletions(-) create mode 100644 packages/google-api-core/google/api_core/gapic_v1/_client_cert.py create mode 100644 packages/google-api-core/google/api_core/gapic_v1/_config_helpers.py create mode 100644 packages/google-api-core/google/api_core/gapic_v1/_method_helpers.py create mode 100644 packages/google-api-core/google/api_core/gapic_v1/_routing.py delete mode 100644 packages/google-api-core/google/api_core/gapic_v1/client_helpers.py diff --git a/packages/google-api-core/google/api_core/gapic_v1/__init__.py b/packages/google-api-core/google/api_core/gapic_v1/__init__.py index e8cae980d58a..d5ee314d3946 100644 --- a/packages/google-api-core/google/api_core/gapic_v1/__init__.py +++ b/packages/google-api-core/google/api_core/gapic_v1/__init__.py @@ -12,20 +12,20 @@ # See the License for the specific language governing permissions and # limitations under the License. -from google.api_core.gapic_v1 import client_helpers -from google.api_core.gapic_v1 import client_info -from google.api_core.gapic_v1 import config -from google.api_core.gapic_v1 import config_async -from google.api_core.gapic_v1 import method -from google.api_core.gapic_v1 import method_async -from google.api_core.gapic_v1 import routing_header +from google.api_core.gapic_v1 import (_client_cert, _config_helpers, + _method_helpers, _routing, client_info, + config, config_async, method, + method_async, routing_header) __all__ = [ - "client_helpers", + "_client_cert", "client_info", "config", "config_async", + "_config_helpers", "method", "method_async", + "_method_helpers", + "_routing", "routing_header", ] diff --git a/packages/google-api-core/google/api_core/gapic_v1/_client_cert.py b/packages/google-api-core/google/api_core/gapic_v1/_client_cert.py new file mode 100644 index 000000000000..267e9503c5d1 --- /dev/null +++ b/packages/google-api-core/google/api_core/gapic_v1/_client_cert.py @@ -0,0 +1,84 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +"""Helpers for client certificate handling and mTLS authentication.""" + +import os +from typing import Any, Optional + +from google.auth.transport import mtls # type: ignore + + +def use_client_cert_effective() -> bool: + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS + enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without + should_use_client_cert and GOOGLE_API_USE_CLIENT_CERTIFICATE is + set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for + # automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` " + "must be either `true` or `false`" + ) + return use_client_cert_str == "true" + + +def get_client_cert_source( + provided_cert_source: Optional[Any], use_cert_flag: bool +) -> Optional[Any]: + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the + client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif ( + hasattr(mtls, "has_default_client_cert_source") + and mtls.has_default_client_cert_source() + ): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + +# Backward compatibility aliases for private methods +# Previously, gapic-generator-python generated clients used these methods +_use_client_cert_effective = use_client_cert_effective +_get_client_cert_source = get_client_cert_source diff --git a/packages/google-api-core/google/api_core/gapic_v1/_config_helpers.py b/packages/google-api-core/google/api_core/gapic_v1/_config_helpers.py new file mode 100644 index 000000000000..0cd9a7f24b8d --- /dev/null +++ b/packages/google-api-core/google/api_core/gapic_v1/_config_helpers.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +"""Helpers for parsing environment variables.""" + +import os +from typing import Optional, Tuple + +from google.api_core.gapic_v1._client_cert import use_client_cert_effective +from google.auth.exceptions import MutualTLSChannelError # type: ignore + + +def read_environment_variables() -> Tuple[bool, str, Optional[str]]: + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, Optional[str]]: returns the + GOOGLE_API_USE_CLIENT_CERTIFICATE, GOOGLE_API_USE_MTLS_ENDPOINT, + and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If + GOOGLE_API_USE_MTLS_ENDPOINT is not any of + ["auto", "never", "always"]. + """ + use_client_cert = use_client_cert_effective() + use_mtls_endpoint = os.getenv( + "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" + ).lower() # noqa: E501 + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` " + "must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + +# Backward compatibility aliases for private methods +# Previously, gapic-generator-python generated clients used these methods +_read_environment_variables = read_environment_variables diff --git a/packages/google-api-core/google/api_core/gapic_v1/_method_helpers.py b/packages/google-api-core/google/api_core/gapic_v1/_method_helpers.py new file mode 100644 index 000000000000..cd362cec6d8a --- /dev/null +++ b/packages/google-api-core/google/api_core/gapic_v1/_method_helpers.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +"""Helpers for method requests.""" + +import uuid +from typing import Any + + +def setup_request_id( + request: Any, field_name: str, is_proto3_optional: bool +) -> None: # noqa: E501 + """Populate a UUID4 field in the request if it is not already set. + + Args: + request (Union[google.protobuf.message.Message, dict]): The + request object. + field_name (str): The name of the field to populate. + is_proto3_optional (bool): Whether the field is proto3 optional. + """ + if isinstance(request, dict): + if is_proto3_optional: + if field_name not in request: + request[field_name] = str(uuid.uuid4()) + elif not request.get(field_name): + request[field_name] = str(uuid.uuid4()) + return + + if is_proto3_optional: + try: + # Pure protobuf messages + if not request.HasField(field_name): + setattr(request, field_name, str(uuid.uuid4())) + except (AttributeError, ValueError): + # Proto-plus messages or other objects + if field_name not in request: + setattr(request, field_name, str(uuid.uuid4())) + else: + if not getattr(request, field_name): + setattr(request, field_name, str(uuid.uuid4())) + + +# Backward compatibility aliases for private methods +# Previously, gapic-generator-python generated clients used these methods +_setup_request_id = setup_request_id diff --git a/packages/google-api-core/google/api_core/gapic_v1/_routing.py b/packages/google-api-core/google/api_core/gapic_v1/_routing.py new file mode 100644 index 000000000000..831345032881 --- /dev/null +++ b/packages/google-api-core/google/api_core/gapic_v1/_routing.py @@ -0,0 +1,106 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +"""Helpers for routing and endpoint resolution.""" + +import re +from typing import Any, Optional + +from google.auth.exceptions import MutualTLSChannelError # type: ignore + +_MTLS_ENDPOINT_RE = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?" + r"(?P\.googleapis\.com)?" +) + + +def get_default_mtls_endpoint(api_endpoint: Optional[str]) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + m = _MTLS_ENDPOINT_RE.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls_group, sandbox, googledomain = m.groups() + if mtls_group or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + +def get_api_endpoint( + api_override: Optional[str], + client_cert_source: Optional[Any], + universe_domain: str, + use_mtls_endpoint: str, + default_universe: str, + default_mtls_endpoint: Optional[str], + default_endpoint_template: str, +) -> Optional[str]: + """Return the API endpoint used by the client.""" + if api_override is not None: + return api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + if universe_domain != default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than " + f"{default_universe}." + ) + return default_mtls_endpoint + else: + return default_endpoint_template.format( + UNIVERSE_DOMAIN=universe_domain + ) # noqa: E501 + + +def get_universe_domain( + client_universe_domain: Optional[str], + universe_domain_env: Optional[str], + default_universe: str, +) -> str: + """Return the universe domain used by the client.""" + universe_domain = default_universe + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + +# Backward compatibility aliases for private methods +# Previously, gapic-generator-python generated clients used these methods +_get_default_mtls_endpoint = get_default_mtls_endpoint +_get_universe_domain = get_universe_domain diff --git a/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py b/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py deleted file mode 100644 index feaa44c2752a..000000000000 --- a/packages/google-api-core/google/api_core/gapic_v1/client_helpers.py +++ /dev/null @@ -1,257 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -"""Helpers for GAPIC client initialization.""" - -import os -import re -import uuid -from typing import Any, Optional, Tuple - -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.auth.transport import mtls # type: ignore - -_MTLS_ENDPOINT_RE = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?" - r"(?P\.googleapis\.com)?" -) - - -def get_default_mtls_endpoint(api_endpoint: Optional[str]) -> Optional[str]: - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - Optional[str]: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - m = _MTLS_ENDPOINT_RE.match(api_endpoint) - if m is None: - # Could not parse api_endpoint; return as-is. - return api_endpoint - - name, mtls_group, sandbox, googledomain = m.groups() - if mtls_group or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - -def use_client_cert_effective() -> bool: - """Returns whether client certificate should be used for mTLS if the - google-auth version supports should_use_client_cert automatic mTLS - enablement. - - Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. - - Returns: - bool: whether client certificate should be used for mTLS - Raises: - ValueError: (If using a version of google-auth without - should_use_client_cert and GOOGLE_API_USE_CLIENT_CERTIFICATE is - set to an unexpected value.) - """ - # check if google-auth version supports should_use_client_cert for - # automatic mTLS enablement - if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER - return mtls.should_use_client_cert() - else: # pragma: NO COVER - # if unsupported, fallback to reading from env var - use_client_cert_str = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() - if use_client_cert_str not in ("true", "false"): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` " - "must be either `true` or `false`" - ) - return use_client_cert_str == "true" - - -def get_api_endpoint( - api_override: Optional[str], - client_cert_source: Optional[Any], - universe_domain: str, - use_mtls_endpoint: str, - default_universe: str, - default_mtls_endpoint: Optional[str], - default_endpoint_template: str, -) -> Optional[str]: - """Return the API endpoint used by the client. - - Args: - api_override (Optional[str]): The API endpoint override. - client_cert_source (Optional[Any]): The client certificate source. - universe_domain (str): The universe domain. - use_mtls_endpoint (str): How to use the mTLS endpoint. - default_universe (str): The default universe. - default_mtls_endpoint (Optional[str]): The default mTLS endpoint. - default_endpoint_template (str): The default endpoint template. - - Returns: - Optional[str]: The API endpoint to be used by the client. - """ - if api_override is not None: - return api_override - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): - if universe_domain != default_universe: - raise MutualTLSChannelError( - f"mTLS is not supported in any universe other than " - f"{default_universe}." - ) - return default_mtls_endpoint - else: - return default_endpoint_template.format( - UNIVERSE_DOMAIN=universe_domain - ) # noqa: E501 - - -def read_environment_variables() -> Tuple[bool, str, Optional[str]]: - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, Optional[str]]: returns the - GOOGLE_API_USE_CLIENT_CERTIFICATE, GOOGLE_API_USE_MTLS_ENDPOINT, - and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If - GOOGLE_API_USE_MTLS_ENDPOINT is not any of - ["auto", "never", "always"]. - """ - use_client_cert = use_client_cert_effective() - use_mtls_endpoint = os.getenv( - "GOOGLE_API_USE_MTLS_ENDPOINT", "auto" - ).lower() # noqa: E501 - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` " - "must be `never`, `auto` or `always`" - ) - return use_client_cert, use_mtls_endpoint, universe_domain_env - - -def get_client_cert_source( - provided_cert_source: Optional[Any], use_cert_flag: bool -) -> Optional[Any]: - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the - client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif ( - hasattr(mtls, "has_default_client_cert_source") - and mtls.has_default_client_cert_source() - ): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - -def get_universe_domain( - client_universe_domain: Optional[str], - universe_domain_env: Optional[str], - default_universe: str, -) -> str: - """Return the universe domain used by the client. - - Args: - client_universe_domain (Optional[str]): The universe domain - configured via the client options. - universe_domain_env (Optional[str]): The universe domain - configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" env var. - default_universe (str): The default universe domain. - - Returns: - str: The universe domain to be used by the client. - - Raises: - ValueError: If the universe domain is an empty string. - """ - universe_domain = default_universe - if client_universe_domain is not None: - universe_domain = client_universe_domain - elif universe_domain_env is not None: - universe_domain = universe_domain_env - if len(universe_domain.strip()) == 0: - raise ValueError("Universe Domain cannot be an empty string.") - return universe_domain - - -def setup_request_id( - request: Any, field_name: str, is_proto3_optional: bool -) -> None: # noqa: E501 - """Populate a UUID4 field in the request if it is not already set. - - Args: - request (Union[google.protobuf.message.Message, dict]): The - request object. - field_name (str): The name of the field to populate. - is_proto3_optional (bool): Whether the field is proto3 optional. - """ - if isinstance(request, dict): - if is_proto3_optional: - if field_name not in request: - request[field_name] = str(uuid.uuid4()) - elif not request.get(field_name): - request[field_name] = str(uuid.uuid4()) - return - - if is_proto3_optional: - try: - # Pure protobuf messages - if not request.HasField(field_name): - setattr(request, field_name, str(uuid.uuid4())) - except (AttributeError, ValueError): - # Proto-plus messages or other objects - if field_name not in request: - setattr(request, field_name, str(uuid.uuid4())) - else: - if not getattr(request, field_name): - setattr(request, field_name, str(uuid.uuid4())) - - -# Backward compatibility aliases for private methods -# Previously, gapic-generator-python generated clients used these methods -_use_client_cert_effective = use_client_cert_effective -_get_default_mtls_endpoint = get_default_mtls_endpoint -_read_environment_variables = read_environment_variables -_get_client_cert_source = get_client_cert_source -_get_universe_domain = get_universe_domain -_setup_request_id = setup_request_id diff --git a/packages/google-api-core/tests/unit/gapic/test_client_helpers.py b/packages/google-api-core/tests/unit/gapic/test_client_helpers.py index 41826cbd1e5f..8f8bbd982e61 100644 --- a/packages/google-api-core/tests/unit/gapic/test_client_helpers.py +++ b/packages/google-api-core/tests/unit/gapic/test_client_helpers.py @@ -15,6 +15,7 @@ import os from unittest import mock + import pytest try: @@ -22,73 +23,77 @@ except ImportError: pytest.skip("No GRPC", allow_module_level=True) -from google.api_core.gapic_v1 import client_helpers from google.auth.exceptions import MutualTLSChannelError +from google.api_core.gapic_v1._client_cert import (get_client_cert_source, + use_client_cert_effective) +from google.api_core.gapic_v1._config_helpers import read_environment_variables +from google.api_core.gapic_v1._method_helpers import setup_request_id +from google.api_core.gapic_v1._routing import (get_api_endpoint, + get_default_mtls_endpoint, + get_universe_domain) + def test_get_default_mtls_endpoint(): # Test valid API endpoints + assert get_default_mtls_endpoint("foo.googleapis.com") == "foo.mtls.googleapis.com" assert ( - client_helpers.get_default_mtls_endpoint("foo.googleapis.com") - == "foo.mtls.googleapis.com" - ) - assert ( - client_helpers.get_default_mtls_endpoint("foo.sandbox.googleapis.com") + get_default_mtls_endpoint("foo.sandbox.googleapis.com") == "foo.mtls.sandbox.googleapis.com" ) # Test endpoints that shouldn't be converted assert ( - client_helpers.get_default_mtls_endpoint("foo.mtls.googleapis.com") + get_default_mtls_endpoint("foo.mtls.googleapis.com") == "foo.mtls.googleapis.com" ) - assert client_helpers.get_default_mtls_endpoint("foo.com") == "foo.com" + assert get_default_mtls_endpoint("foo.com") == "foo.com" # Test empty/None endpoints - assert client_helpers.get_default_mtls_endpoint("") == "" - assert client_helpers.get_default_mtls_endpoint(None) is None + assert get_default_mtls_endpoint("") == "" + assert get_default_mtls_endpoint(None) is None @mock.patch("google.auth.transport.mtls.should_use_client_cert", create=True) def test_use_client_cert_effective_with_google_auth(mock_method): # Test when google-auth supports the method mock_method.return_value = True - assert client_helpers.use_client_cert_effective() is True + assert use_client_cert_effective() is True mock_method.return_value = False - assert client_helpers.use_client_cert_effective() is False + assert use_client_cert_effective() is False @mock.patch.dict(os.environ, {}, clear=True) def test_use_client_cert_effective_fallback(): # We must patch hasattr to simulate google-auth lacking the method with mock.patch( - "google.api_core.gapic_v1.client_helpers.hasattr", return_value=False + "google.api_core.gapic_v1._client_cert.hasattr", return_value=False ): # Default is false - assert client_helpers.use_client_cert_effective() is False + assert use_client_cert_effective() is False env_true = {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"} with mock.patch.dict(os.environ, env_true): - assert client_helpers.use_client_cert_effective() is True + assert use_client_cert_effective() is True with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} ): - assert client_helpers.use_client_cert_effective() is False + assert use_client_cert_effective() is False with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "invalid"} ): match_str = "must be either `true` or `false`" with pytest.raises(ValueError, match=match_str): - client_helpers.use_client_cert_effective() + use_client_cert_effective() def test_get_api_endpoint_override(): # If api_override is provided, it should be returned # regardless of other args - endpoint = client_helpers.get_api_endpoint( + endpoint = get_api_endpoint( api_override="custom.endpoint.com", client_cert_source=None, universe_domain="googleapis.com", @@ -102,7 +107,7 @@ def test_get_api_endpoint_override(): def test_get_api_endpoint_mtls_always(): # use_mtls_endpoint == "always" should use the default mtls endpoint - endpoint = client_helpers.get_api_endpoint( + endpoint = get_api_endpoint( api_override=None, client_cert_source=None, universe_domain="googleapis.com", @@ -116,7 +121,7 @@ def test_get_api_endpoint_mtls_always(): def test_get_api_endpoint_mtls_auto_with_cert(): # "auto" with client_cert_source should use mtls - endpoint = client_helpers.get_api_endpoint( + endpoint = get_api_endpoint( api_override=None, client_cert_source=mock.Mock(), universe_domain="googleapis.com", @@ -130,7 +135,7 @@ def test_get_api_endpoint_mtls_auto_with_cert(): def test_get_api_endpoint_mtls_auto_no_cert(): # "auto" without client_cert_source should use the default template - endpoint = client_helpers.get_api_endpoint( + endpoint = get_api_endpoint( api_override=None, client_cert_source=None, universe_domain="googleapis.com", @@ -145,7 +150,7 @@ def test_get_api_endpoint_mtls_auto_no_cert(): def test_get_api_endpoint_mtls_universe_mismatch(): # mTLS is only supported in the default universe with pytest.raises(MutualTLSChannelError, match="mTLS is not supported"): - client_helpers.get_api_endpoint( + get_api_endpoint( api_override=None, client_cert_source=mock.Mock(), universe_domain="custom-universe.com", @@ -157,7 +162,7 @@ def test_get_api_endpoint_mtls_universe_mismatch(): @mock.patch( - "google.api_core.gapic_v1.client_helpers.use_client_cert_effective" + "google.api_core.gapic_v1._config_helpers.use_client_cert_effective" ) # noqa: E501 @mock.patch.dict(os.environ, clear=True) def test_read_environment_variables(mock_effective): @@ -165,7 +170,7 @@ def test_read_environment_variables(mock_effective): os.environ["GOOGLE_API_USE_MTLS_ENDPOINT"] = "always" os.environ["GOOGLE_CLOUD_UNIVERSE_DOMAIN"] = "custom.com" - cert, mtls, domain = client_helpers.read_environment_variables() + cert, mtls, domain = read_environment_variables() assert cert is True assert mtls == "always" assert domain == "custom.com" @@ -177,7 +182,7 @@ def test_read_environment_variables_invalid_mtls(): with pytest.raises( MutualTLSChannelError, match="must be `never`, `auto` or `always`" ): - client_helpers.read_environment_variables() + read_environment_variables() @mock.patch( @@ -191,42 +196,34 @@ def test_get_client_cert_source(mock_default, mock_has_default): mock_has_default.return_value = True # When use_cert_flag is False, return None - assert client_helpers.get_client_cert_source(b"provided", False) is None + assert get_client_cert_source(b"provided", False) is None # When provided_cert_source is given, return provided - assert ( - client_helpers.get_client_cert_source(b"provided", True) == b"provided" - ) # noqa: E501 + assert get_client_cert_source(b"provided", True) == b"provided" # noqa: E501 # When no provided cert but default is available - assert client_helpers.get_client_cert_source(None, True) == b"default_cert" + assert get_client_cert_source(None, True) == b"default_cert" def test_get_universe_domain(): # client_universe_domain takes precedence assert ( - client_helpers.get_universe_domain( - "client.com", "env.com", "default.com" - ) # noqa: E501 + get_universe_domain("client.com", "env.com", "default.com") # noqa: E501 == "client.com" ) # env takes precedence over default assert ( - client_helpers.get_universe_domain(None, "env.com", "default.com") - == "env.com" # noqa: E501 + get_universe_domain(None, "env.com", "default.com") == "env.com" # noqa: E501 ) # fallback to default - assert ( - client_helpers.get_universe_domain(None, None, "default.com") - == "default.com" # noqa: E501 - ) + assert get_universe_domain(None, None, "default.com") == "default.com" # noqa: E501 def test_get_universe_domain_empty(): with pytest.raises(ValueError, match="cannot be an empty string"): - client_helpers.get_universe_domain("", None, "default.com") + get_universe_domain("", None, "default.com") def test_setup_request_id(): @@ -234,14 +231,14 @@ def test_setup_request_id(): # test dict request req = {} - client_helpers.setup_request_id(req, "request_id", True) + setup_request_id(req, "request_id", True) assert "request_id" in req uuid_str = req["request_id"] uuid.UUID(uuid_str) # verify it is a valid UUID # test dict request when already set req = {"request_id": "existing"} - client_helpers.setup_request_id(req, "request_id", True) + setup_request_id(req, "request_id", True) assert req["request_id"] == "existing" class DummyRequest: @@ -255,12 +252,12 @@ def HasField(self, field_name): # test object request proto3 optional true req_obj = DummyRequest() - client_helpers.setup_request_id(req_obj, "request_id", True) + setup_request_id(req_obj, "request_id", True) assert req_obj.request_id != "" uuid.UUID(req_obj.request_id) # test object request proto3 optional false req_obj2 = DummyRequest() - client_helpers.setup_request_id(req_obj2, "request_id", False) + setup_request_id(req_obj2, "request_id", False) assert req_obj2.request_id != "" uuid.UUID(req_obj2.request_id) From 65861d98ac3b47bdacbc407bb329dd3c79db1fc0 Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Fri, 10 Jul 2026 01:37:43 +0000 Subject: [PATCH 22/23] chore: fix lint and formatting --- .../ibis_compiler/scalar_op_registry.py | 3 +- .../bigframes/core/compile/polars/compiler.py | 1 + .../sqlglot/expressions/generic_ops.py | 4 +- packages/gapic-generator/noxfile.py | 20 +- .../asset/google/cloud/asset_v1/__init__.py | 230 +- .../services/asset_service/async_client.py | 871 +-- .../asset_v1/services/asset_service/client.py | 1049 +-- .../services/asset_service/transports/base.py | 397 +- .../services/asset_service/transports/rest.py | 3215 ++++++--- .../tests/integration/goldens/asset/setup.py | 11 +- .../google/iam/credentials_v1/__init__.py | 84 +- .../services/iam_credentials/async_client.py | 259 +- .../services/iam_credentials/client.py | 412 +- .../iam_credentials/transports/base.py | 134 +- .../iam_credentials/transports/rest.py | 609 +- .../integration/goldens/credentials/setup.py | 11 +- .../google/cloud/eventarc_v1/__init__.py | 208 +- .../services/eventarc/async_client.py | 1641 +++-- .../eventarc_v1/services/eventarc/client.py | 1921 +++--- .../services/eventarc/transports/base.py | 612 +- .../services/eventarc/transports/rest.py | 5771 +++++++++++------ .../integration/goldens/eventarc/setup.py | 13 +- .../google/cloud/logging_v2/__init__.py | 228 +- .../config_service_v2/async_client.py | 1099 ++-- .../services/config_service_v2/client.py | 1232 ++-- .../config_service_v2/transports/base.py | 496 +- .../logging_service_v2/async_client.py | 316 +- .../services/logging_service_v2/client.py | 460 +- .../logging_service_v2/transports/base.py | 179 +- .../metrics_service_v2/async_client.py | 316 +- .../services/metrics_service_v2/client.py | 461 +- .../metrics_service_v2/transports/base.py | 162 +- .../integration/goldens/logging/setup.py | 11 +- .../google/cloud/logging_v2/__init__.py | 228 +- .../config_service_v2/async_client.py | 1103 ++-- .../services/config_service_v2/client.py | 1232 ++-- .../config_service_v2/transports/base.py | 496 +- .../logging_service_v2/async_client.py | 316 +- .../services/logging_service_v2/client.py | 460 +- .../logging_service_v2/transports/base.py | 179 +- .../metrics_service_v2/async_client.py | 320 +- .../services/metrics_service_v2/client.py | 461 +- .../metrics_service_v2/transports/base.py | 162 +- .../goldens/logging_internal/setup.py | 11 +- .../redis/google/cloud/redis_v1/__init__.py | 122 +- .../services/cloud_redis/async_client.py | 565 +- .../redis_v1/services/cloud_redis/client.py | 713 +- .../services/cloud_redis/transports/base.py | 248 +- .../services/cloud_redis/transports/rest.py | 2166 ++++--- .../cloud_redis/transports/rest_asyncio.py | 2284 ++++--- .../tests/integration/goldens/redis/setup.py | 12 +- .../google/cloud/redis_v1/__init__.py | 108 +- .../services/cloud_redis/async_client.py | 339 +- .../redis_v1/services/cloud_redis/client.py | 511 +- .../services/cloud_redis/transports/base.py | 174 +- .../services/cloud_redis/transports/rest.py | 1427 ++-- .../cloud_redis/transports/rest_asyncio.py | 1510 +++-- .../goldens/redis_selective/setup.py | 12 +- .../storagebatchoperations_v1/__init__.py | 124 +- .../storage_batch_operations/async_client.py | 452 +- .../storage_batch_operations/client.py | 619 +- .../transports/base.py | 210 +- .../transports/rest.py | 1602 +++-- .../goldens/storagebatchoperations/setup.py | 13 +- .../google/api_core/gapic_v1/__init__.py | 16 +- .../tests/unit/gapic/test_client_helpers.py | 14 +- .../chat_v1/services/chat_service/client.py | 8 +- .../services/chat_service/transports/grpc.py | 24 +- .../chat_service/transports/grpc_asyncio.py | 24 +- .../services/chat_service/transports/rest.py | 38 +- .../unit/gapic/chat_v1/test_chat_service.py | 237 +- packages/google-auth/system_tests/noxfile.py | 15 +- .../test_hive_metastore_service.py | 189 +- .../binauthz_management_service_v1/client.py | 18 +- .../transports/rest.py | 28 +- .../services/system_policy_v1/client.py | 12 +- .../system_policy_v1/transports/rest.py | 4 +- .../services/validation_helper_v1/client.py | 12 +- .../validation_helper_v1/transports/grpc.py | 12 +- .../transports/grpc_asyncio.py | 12 +- .../validation_helper_v1/transports/rest.py | 13 +- .../binaryauthorization_v1/types/resources.py | 54 +- .../client.py | 18 +- .../transports/rest.py | 28 +- .../services/system_policy_v1_beta1/client.py | 12 +- .../system_policy_v1_beta1/transports/rest.py | 4 +- .../types/resources.py | 54 +- .../test_binauthz_management_service_v1.py | 21 +- .../test_system_policy_v1.py | 33 +- .../test_validation_helper_v1.py | 21 +- ...st_binauthz_management_service_v1_beta1.py | 21 +- .../test_system_policy_v1_beta1.py | 33 +- .../services/dataform/async_client.py | 8 +- .../dataform_v1/services/dataform/client.py | 8 +- .../cloud/dataform_v1/types/dataform.py | 60 +- .../unit/gapic/dataform_v1/test_dataform.py | 393 +- .../cloud/dataproc_v1/types/clusters.py | 24 +- .../dataproc_v1/test_cluster_controller.py | 33 +- .../dataproc_v1/test_node_group_controller.py | 45 +- .../test_workflow_template_service.py | 33 +- .../cloud/dialogflow_v2/types/conversation.py | 28 +- .../cloud/dialogflow_v2/types/session.py | 84 +- .../dialogflow_v2beta1/types/conversation.py | 28 +- .../cloud/dialogflow_v2beta1/types/session.py | 84 +- .../services/key_management_service/client.py | 12 +- .../google/cloud/kms_v1/types/service.py | 12 +- .../kms_v1/test_key_management_service.py | 153 +- .../services/memorystore/client.py | 8 +- .../services/memorystore/transports/base.py | 10 +- .../services/memorystore/transports/grpc.py | 12 +- .../memorystore/transports/grpc_asyncio.py | 12 +- .../services/memorystore/transports/rest.py | 38 +- .../cloud/memorystore_v1/types/memorystore.py | 24 +- .../gapic/memorystore_v1/test_memorystore.py | 45 +- .../cloud/modelarmor_v1/types/service.py | 12 +- .../gapic/modelarmor_v1/test_model_armor.py | 57 +- .../services/secure_source_manager/client.py | 12 +- .../test_secure_source_manager.py | 285 +- .../cloud/support_v2/types/case_service.py | 12 +- .../support_v2beta/types/case_service.py | 12 +- 120 files changed, 26671 insertions(+), 16463 deletions(-) diff --git a/packages/bigframes/bigframes/core/compile/ibis_compiler/scalar_op_registry.py b/packages/bigframes/bigframes/core/compile/ibis_compiler/scalar_op_registry.py index 3f9fcb5b75df..ce97c659632a 100644 --- a/packages/bigframes/bigframes/core/compile/ibis_compiler/scalar_op_registry.py +++ b/packages/bigframes/bigframes/core/compile/ibis_compiler/scalar_op_registry.py @@ -1017,7 +1017,8 @@ def remote_function_op_impl(*values: ibis_types.Value, op: ops.RemoteFunctionOp) signature=ibis_py_sig, param_name_overrides=arg_names, ) - def udf(*inputs): ... + def udf(*inputs): + ... return udf(*values) diff --git a/packages/bigframes/bigframes/core/compile/polars/compiler.py b/packages/bigframes/bigframes/core/compile/polars/compiler.py index 3f899478873c..adc3ef90b2c5 100644 --- a/packages/bigframes/bigframes/core/compile/polars/compiler.py +++ b/packages/bigframes/bigframes/core/compile/polars/compiler.py @@ -597,6 +597,7 @@ def handler(py_struct): args = list(py_struct.values()) series_arg = function_template.get_pd_series(args[0]) return code(series_arg, *args[1:]) + else: def handler(py_struct): diff --git a/packages/bigframes/bigframes/core/compile/sqlglot/expressions/generic_ops.py b/packages/bigframes/bigframes/core/compile/sqlglot/expressions/generic_ops.py index 2cc27cb8e5a2..bf94d19b7f96 100644 --- a/packages/bigframes/bigframes/core/compile/sqlglot/expressions/generic_ops.py +++ b/packages/bigframes/bigframes/core/compile/sqlglot/expressions/generic_ops.py @@ -83,7 +83,9 @@ def _(*operands: TypedExpr, op: ops.GoogleSqlScalarOp) -> sge.Expression: if i < len(op.args): arg_spec = op.args[i] else: - assert op.args[-1].is_vararg, ( + assert op.args[ + -1 + ].is_vararg, ( f"Too many arguments, for {op.sql_name}, expected {len(op.args)}" ) arg_spec = op.args[-1] diff --git a/packages/gapic-generator/noxfile.py b/packages/gapic-generator/noxfile.py index 84d273023968..2fc78662c48a 100644 --- a/packages/gapic-generator/noxfile.py +++ b/packages/gapic-generator/noxfile.py @@ -725,7 +725,7 @@ def lint(session): """ # TODO(https://github.com/googleapis/google-cloud-python/issues/16186): - # SKIP: This session was not enforced in the standalone (split) repo + # SKIP: This session was not enforced in the standalone (split) repo # and is disabled here to ensure a "move-only" migration. session.skip( "Linting was not enforced in the split repo. " @@ -755,9 +755,11 @@ def lint(session): @nox.session(python=NEWEST_PYTHON) def lint_setup_py(session): # TODO(https://github.com/googleapis/google-cloud-python/issues/16186): - # SKIP: This session was not enforced in the standalone (split) repo + # SKIP: This session was not enforced in the standalone (split) repo # and is disabled here to ensure a "move-only" migration. - session.skip("Skipping now to avoid changing code during migration. See Issue #16186") + session.skip( + "Skipping now to avoid changing code during migration. See Issue #16186" + ) @nox.session(python="3.10") @@ -832,9 +834,11 @@ def prerelease_deps(session, protobuf_implementation): """ Run all tests with pre-release versions of dependencies installed. """ - # TODO(https://github.com/googleapis/google-cloud-python/issues/16184): + # TODO(https://github.com/googleapis/google-cloud-python/issues/16184): # Implement pre-release dependency logic to test against upcoming runtime changes. - session.skip("prerelease_deps session is not yet implemented for gapic-generator-python.") + session.skip( + "prerelease_deps session is not yet implemented for gapic-generator-python." + ) @nox.session(python=NEWEST_PYTHON) @@ -844,6 +848,8 @@ def prerelease_deps(session, protobuf_implementation): ) def core_deps_from_source(session, protobuf_implementation): """Run all tests with core dependencies installed from source.""" - # TODO(https://github.com/googleapis/google-cloud-python/issues/16185): + # TODO(https://github.com/googleapis/google-cloud-python/issues/16185): # Implement logic to install core packages directly from the mono-repo directories. - session.skip("core_deps_from_source session is not yet implemented for gapic-generator-python.") \ No newline at end of file + session.skip( + "core_deps_from_source session is not yet implemented for gapic-generator-python." + ) diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/__init__.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/__init__.py index f272a61b7a4e..a43cebeedcc8 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/__init__.py @@ -108,10 +108,12 @@ from .types.assets import TimeWindow from .types.assets import VersionedResource -if hasattr(api_core, "check_python_version") and hasattr(api_core, "check_dependency_versions"): # pragma: NO COVER - api_core.check_python_version("google.cloud.asset_v1") # type: ignore - api_core.check_dependency_versions("google.cloud.asset_v1") # type: ignore -else: # pragma: NO COVER +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.cloud.asset_v1") # type: ignore + api_core.check_dependency_versions("google.cloud.asset_v1") # type: ignore +else: # pragma: NO COVER # An older version of api_core is installed which does not define the # functions above. We do equivalent checks manually. try: @@ -120,12 +122,14 @@ _py_version_str = sys.version.split()[0] _package_label = "google.cloud.asset_v1" if sys.version_info < (3, 10): - warnings.warn("You are using a non-supported Python version " + - f"({_py_version_str}). Google will not post any further " + - f"updates to {_package_label} supporting this Python version. " + - "Please upgrade to the latest Python version, or at " + - f"least to Python 3.10, and then update {_package_label}.", - FutureWarning) + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.10, and then update {_package_label}.", + FutureWarning, + ) def parse_version_to_tuple(version_string: str): """Safely converts a semantic version string to a comparable tuple of integers. @@ -163,108 +167,112 @@ def _get_version(dependency_name): _recommendation = " (we recommend 7.x)" (_version_used, _version_used_string) = _get_version(_dependency_package) if _version_used and _version_used < _next_supported_version_tuple: - warnings.warn(f"Package {_package_label} depends on " + - f"{_dependency_package}, currently installed at version " + - f"{_version_used_string}. Future updates to " + - f"{_package_label} will require {_dependency_package} at " + - f"version {_next_supported_version} or higher{_recommendation}." + - " Please ensure " + - "that either (a) your Python environment doesn't pin the " + - f"version of {_dependency_package}, so that updates to " + - f"{_package_label} can require the higher version, or " + - "(b) you manually update your Python environment to use at " + - f"least version {_next_supported_version} of " + - f"{_dependency_package}.", - FutureWarning) + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) except Exception: - warnings.warn("Could not determine the version of Python " + - "currently being used. To continue receiving " + - "updates for {_package_label}, ensure you are " + - "using a supported version of Python; see " + - "https://devguide.python.org/versions/") + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) __all__ = ( - 'AssetServiceAsyncClient', -'AnalyzeIamPolicyLongrunningMetadata', -'AnalyzeIamPolicyLongrunningRequest', -'AnalyzeIamPolicyLongrunningResponse', -'AnalyzeIamPolicyRequest', -'AnalyzeIamPolicyResponse', -'AnalyzeMoveRequest', -'AnalyzeMoveResponse', -'AnalyzeOrgPoliciesRequest', -'AnalyzeOrgPoliciesResponse', -'AnalyzeOrgPolicyGovernedAssetsRequest', -'AnalyzeOrgPolicyGovernedAssetsResponse', -'AnalyzeOrgPolicyGovernedContainersRequest', -'AnalyzeOrgPolicyGovernedContainersResponse', -'AnalyzerOrgPolicy', -'AnalyzerOrgPolicyConstraint', -'Asset', -'AssetEnrichment', -'AssetServiceClient', -'AttachedResource', -'BatchGetAssetsHistoryRequest', -'BatchGetAssetsHistoryResponse', -'BatchGetEffectiveIamPoliciesRequest', -'BatchGetEffectiveIamPoliciesResponse', -'BigQueryDestination', -'ConditionEvaluation', -'ContentType', -'CreateFeedRequest', -'CreateSavedQueryRequest', -'DeleteFeedRequest', -'DeleteSavedQueryRequest', -'EffectiveTagDetails', -'ExportAssetsRequest', -'ExportAssetsResponse', -'Feed', -'FeedOutputConfig', -'GcsDestination', -'GcsOutputResult', -'GetFeedRequest', -'GetSavedQueryRequest', -'IamPolicyAnalysisOutputConfig', -'IamPolicyAnalysisQuery', -'IamPolicyAnalysisResult', -'IamPolicyAnalysisState', -'IamPolicySearchResult', -'ListAssetsRequest', -'ListAssetsResponse', -'ListFeedsRequest', -'ListFeedsResponse', -'ListSavedQueriesRequest', -'ListSavedQueriesResponse', -'MoveAnalysis', -'MoveAnalysisResult', -'MoveImpact', -'OutputConfig', -'OutputResult', -'PartitionSpec', -'PubsubDestination', -'QueryAssetsOutputConfig', -'QueryAssetsRequest', -'QueryAssetsResponse', -'QueryResult', -'RelatedAsset', -'RelatedAssets', -'RelatedResource', -'RelatedResources', -'RelationshipAttributes', -'Resource', -'ResourceOwners', -'ResourceSearchResult', -'SavedQuery', -'SearchAllIamPoliciesRequest', -'SearchAllIamPoliciesResponse', -'SearchAllResourcesRequest', -'SearchAllResourcesResponse', -'TableFieldSchema', -'TableSchema', -'Tag', -'TemporalAsset', -'TimeWindow', -'UpdateFeedRequest', -'UpdateSavedQueryRequest', -'VersionedResource', + "AssetServiceAsyncClient", + "AnalyzeIamPolicyLongrunningMetadata", + "AnalyzeIamPolicyLongrunningRequest", + "AnalyzeIamPolicyLongrunningResponse", + "AnalyzeIamPolicyRequest", + "AnalyzeIamPolicyResponse", + "AnalyzeMoveRequest", + "AnalyzeMoveResponse", + "AnalyzeOrgPoliciesRequest", + "AnalyzeOrgPoliciesResponse", + "AnalyzeOrgPolicyGovernedAssetsRequest", + "AnalyzeOrgPolicyGovernedAssetsResponse", + "AnalyzeOrgPolicyGovernedContainersRequest", + "AnalyzeOrgPolicyGovernedContainersResponse", + "AnalyzerOrgPolicy", + "AnalyzerOrgPolicyConstraint", + "Asset", + "AssetEnrichment", + "AssetServiceClient", + "AttachedResource", + "BatchGetAssetsHistoryRequest", + "BatchGetAssetsHistoryResponse", + "BatchGetEffectiveIamPoliciesRequest", + "BatchGetEffectiveIamPoliciesResponse", + "BigQueryDestination", + "ConditionEvaluation", + "ContentType", + "CreateFeedRequest", + "CreateSavedQueryRequest", + "DeleteFeedRequest", + "DeleteSavedQueryRequest", + "EffectiveTagDetails", + "ExportAssetsRequest", + "ExportAssetsResponse", + "Feed", + "FeedOutputConfig", + "GcsDestination", + "GcsOutputResult", + "GetFeedRequest", + "GetSavedQueryRequest", + "IamPolicyAnalysisOutputConfig", + "IamPolicyAnalysisQuery", + "IamPolicyAnalysisResult", + "IamPolicyAnalysisState", + "IamPolicySearchResult", + "ListAssetsRequest", + "ListAssetsResponse", + "ListFeedsRequest", + "ListFeedsResponse", + "ListSavedQueriesRequest", + "ListSavedQueriesResponse", + "MoveAnalysis", + "MoveAnalysisResult", + "MoveImpact", + "OutputConfig", + "OutputResult", + "PartitionSpec", + "PubsubDestination", + "QueryAssetsOutputConfig", + "QueryAssetsRequest", + "QueryAssetsResponse", + "QueryResult", + "RelatedAsset", + "RelatedAssets", + "RelatedResource", + "RelatedResources", + "RelationshipAttributes", + "Resource", + "ResourceOwners", + "ResourceSearchResult", + "SavedQuery", + "SearchAllIamPoliciesRequest", + "SearchAllIamPoliciesResponse", + "SearchAllResourcesRequest", + "SearchAllResourcesResponse", + "TableFieldSchema", + "TableSchema", + "Tag", + "TemporalAsset", + "TimeWindow", + "UpdateFeedRequest", + "UpdateSavedQueryRequest", + "VersionedResource", ) diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/async_client.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/async_client.py index 9a4746a2c994..630164d5ead1 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/async_client.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/async_client.py @@ -16,7 +16,18 @@ import logging as std_logging from collections import OrderedDict import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union +from typing import ( + Dict, + Callable, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) from google.cloud.asset_v1 import gapic_version as package_version @@ -24,8 +35,8 @@ from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf @@ -37,7 +48,7 @@ from google.cloud.asset_v1.services.asset_service import pagers from google.cloud.asset_v1.types import asset_service from google.cloud.asset_v1.types import assets -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.api_core.operation as operation # type: ignore import google.api_core.operation_async as operation_async # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore @@ -50,12 +61,14 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) + class AssetServiceAsyncClient: """Asset service definition.""" @@ -81,17 +94,29 @@ class AssetServiceAsyncClient: saved_query_path = staticmethod(AssetServiceClient.saved_query_path) parse_saved_query_path = staticmethod(AssetServiceClient.parse_saved_query_path) service_perimeter_path = staticmethod(AssetServiceClient.service_perimeter_path) - parse_service_perimeter_path = staticmethod(AssetServiceClient.parse_service_perimeter_path) - common_billing_account_path = staticmethod(AssetServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(AssetServiceClient.parse_common_billing_account_path) + parse_service_perimeter_path = staticmethod( + AssetServiceClient.parse_service_perimeter_path + ) + common_billing_account_path = staticmethod( + AssetServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + AssetServiceClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(AssetServiceClient.common_folder_path) parse_common_folder_path = staticmethod(AssetServiceClient.parse_common_folder_path) common_organization_path = staticmethod(AssetServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(AssetServiceClient.parse_common_organization_path) + parse_common_organization_path = staticmethod( + AssetServiceClient.parse_common_organization_path + ) common_project_path = staticmethod(AssetServiceClient.common_project_path) - parse_common_project_path = staticmethod(AssetServiceClient.parse_common_project_path) + parse_common_project_path = staticmethod( + AssetServiceClient.parse_common_project_path + ) common_location_path = staticmethod(AssetServiceClient.common_location_path) - parse_common_location_path = staticmethod(AssetServiceClient.parse_common_location_path) + parse_common_location_path = staticmethod( + AssetServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -133,7 +158,9 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): """Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -196,12 +223,16 @@ def universe_domain(self) -> str: get_transport_class = AssetServiceClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AssetServiceTransport, Callable[..., AssetServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, AssetServiceTransport, Callable[..., AssetServiceTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the asset service async client. Args: @@ -259,30 +290,38 @@ def __init__(self, *, transport=transport, client_options=client_options, client_info=client_info, - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.asset_v1.AssetServiceAsyncClient`.", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { "serviceName": "google.cloud.asset.v1.AssetService", "credentialsType": None, - } + }, ) - async def export_assets(self, - request: Optional[Union[asset_service.ExportAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def export_assets( + self, + request: Optional[Union[asset_service.ExportAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Exports assets with time and resource types to a given Cloud Storage location/BigQuery table. For Cloud Storage location destinations, the output format is newline-delimited JSON. Each @@ -361,14 +400,14 @@ async def sample_export_assets(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.export_assets] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.export_assets + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -393,14 +432,15 @@ async def sample_export_assets(): # Done; return the response. return response - async def list_assets(self, - request: Optional[Union[asset_service.ListAssetsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAssetsAsyncPager: + async def list_assets( + self, + request: Optional[Union[asset_service.ListAssetsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAssetsAsyncPager: r"""Lists assets with time and resource types and returns paged results in response. @@ -467,10 +507,14 @@ async def sample_list_assets(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -484,14 +528,14 @@ async def sample_list_assets(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_assets] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_assets + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -519,13 +563,16 @@ async def sample_list_assets(): # Done; return the response. return response - async def batch_get_assets_history(self, - request: Optional[Union[asset_service.BatchGetAssetsHistoryRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.BatchGetAssetsHistoryResponse: + async def batch_get_assets_history( + self, + request: Optional[ + Union[asset_service.BatchGetAssetsHistoryRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.BatchGetAssetsHistoryResponse: r"""Batch gets the update history of assets that overlap a time window. For IAM_POLICY content, this API outputs history when the asset and its attached IAM POLICY both exist. This can @@ -583,14 +630,14 @@ async def sample_batch_get_assets_history(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.batch_get_assets_history] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.batch_get_assets_history + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -607,14 +654,15 @@ async def sample_batch_get_assets_history(): # Done; return the response. return response - async def create_feed(self, - request: Optional[Union[asset_service.CreateFeedRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.Feed: + async def create_feed( + self, + request: Optional[Union[asset_service.CreateFeedRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.Feed: r"""Creates a feed in a parent project/folder/organization to listen to its asset updates. @@ -691,10 +739,14 @@ async def sample_create_feed(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -708,14 +760,14 @@ async def sample_create_feed(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_feed] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_feed + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -732,14 +784,15 @@ async def sample_create_feed(): # Done; return the response. return response - async def get_feed(self, - request: Optional[Union[asset_service.GetFeedRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.Feed: + async def get_feed( + self, + request: Optional[Union[asset_service.GetFeedRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.Feed: r"""Gets details about an asset feed. .. code-block:: python @@ -804,10 +857,14 @@ async def sample_get_feed(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -826,9 +883,7 @@ async def sample_get_feed(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -845,14 +900,15 @@ async def sample_get_feed(): # Done; return the response. return response - async def list_feeds(self, - request: Optional[Union[asset_service.ListFeedsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.ListFeedsResponse: + async def list_feeds( + self, + request: Optional[Union[asset_service.ListFeedsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.ListFeedsResponse: r"""Lists all asset feeds in a parent project/folder/organization. @@ -912,10 +968,14 @@ async def sample_list_feeds(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -929,14 +989,14 @@ async def sample_list_feeds(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_feeds] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_feeds + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -953,14 +1013,15 @@ async def sample_list_feeds(): # Done; return the response. return response - async def update_feed(self, - request: Optional[Union[asset_service.UpdateFeedRequest, dict]] = None, - *, - feed: Optional[asset_service.Feed] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.Feed: + async def update_feed( + self, + request: Optional[Union[asset_service.UpdateFeedRequest, dict]] = None, + *, + feed: Optional[asset_service.Feed] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.Feed: r"""Updates an asset feed configuration. .. code-block:: python @@ -1029,10 +1090,14 @@ async def sample_update_feed(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [feed] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1046,14 +1111,16 @@ async def sample_update_feed(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_feed] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_feed + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("feed.name", request.feed.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("feed.name", request.feed.name),) + ), ) # Validate the universe domain. @@ -1070,14 +1137,15 @@ async def sample_update_feed(): # Done; return the response. return response - async def delete_feed(self, - request: Optional[Union[asset_service.DeleteFeedRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def delete_feed( + self, + request: Optional[Union[asset_service.DeleteFeedRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes an asset feed. .. code-block:: python @@ -1127,10 +1195,14 @@ async def sample_delete_feed(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1144,14 +1216,14 @@ async def sample_delete_feed(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_feed] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_feed + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1165,16 +1237,17 @@ async def sample_delete_feed(): metadata=metadata, ) - async def search_all_resources(self, - request: Optional[Union[asset_service.SearchAllResourcesRequest, dict]] = None, - *, - scope: Optional[str] = None, - query: Optional[str] = None, - asset_types: Optional[MutableSequence[str]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.SearchAllResourcesAsyncPager: + async def search_all_resources( + self, + request: Optional[Union[asset_service.SearchAllResourcesRequest, dict]] = None, + *, + scope: Optional[str] = None, + query: Optional[str] = None, + asset_types: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.SearchAllResourcesAsyncPager: r"""Searches all Google Cloud resources within the specified scope, such as a project, folder, or organization. The caller must be granted the ``cloudasset.assets.searchAllResources`` permission @@ -1377,10 +1450,14 @@ async def sample_search_all_resources(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [scope, query, asset_types] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1398,14 +1475,14 @@ async def sample_search_all_resources(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.search_all_resources] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.search_all_resources + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scope", request.scope), - )), + gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), ) # Validate the universe domain. @@ -1433,15 +1510,18 @@ async def sample_search_all_resources(): # Done; return the response. return response - async def search_all_iam_policies(self, - request: Optional[Union[asset_service.SearchAllIamPoliciesRequest, dict]] = None, - *, - scope: Optional[str] = None, - query: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.SearchAllIamPoliciesAsyncPager: + async def search_all_iam_policies( + self, + request: Optional[ + Union[asset_service.SearchAllIamPoliciesRequest, dict] + ] = None, + *, + scope: Optional[str] = None, + query: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.SearchAllIamPoliciesAsyncPager: r"""Searches all IAM policies within the specified scope, such as a project, folder, or organization. The caller must be granted the ``cloudasset.assets.searchAllIamPolicies`` permission on the @@ -1571,10 +1651,14 @@ async def sample_search_all_iam_policies(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [scope, query] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1590,14 +1674,14 @@ async def sample_search_all_iam_policies(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.search_all_iam_policies] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.search_all_iam_policies + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scope", request.scope), - )), + gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), ) # Validate the universe domain. @@ -1625,13 +1709,14 @@ async def sample_search_all_iam_policies(): # Done; return the response. return response - async def analyze_iam_policy(self, - request: Optional[Union[asset_service.AnalyzeIamPolicyRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.AnalyzeIamPolicyResponse: + async def analyze_iam_policy( + self, + request: Optional[Union[asset_service.AnalyzeIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.AnalyzeIamPolicyResponse: r"""Analyzes IAM policies to answer which identities have what accesses on which resources. @@ -1690,14 +1775,16 @@ async def sample_analyze_iam_policy(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.analyze_iam_policy] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.analyze_iam_policy + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("analysis_query.scope", request.analysis_query.scope), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("analysis_query.scope", request.analysis_query.scope),) + ), ) # Validate the universe domain. @@ -1714,13 +1801,16 @@ async def sample_analyze_iam_policy(): # Done; return the response. return response - async def analyze_iam_policy_longrunning(self, - request: Optional[Union[asset_service.AnalyzeIamPolicyLongrunningRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def analyze_iam_policy_longrunning( + self, + request: Optional[ + Union[asset_service.AnalyzeIamPolicyLongrunningRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Analyzes IAM policies asynchronously to answer which identities have what accesses on which resources, and writes the analysis results to a Google Cloud Storage or a BigQuery destination. For @@ -1799,14 +1889,16 @@ async def sample_analyze_iam_policy_longrunning(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.analyze_iam_policy_longrunning] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.analyze_iam_policy_longrunning + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("analysis_query.scope", request.analysis_query.scope), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("analysis_query.scope", request.analysis_query.scope),) + ), ) # Validate the universe domain. @@ -1831,13 +1923,14 @@ async def sample_analyze_iam_policy_longrunning(): # Done; return the response. return response - async def analyze_move(self, - request: Optional[Union[asset_service.AnalyzeMoveRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.AnalyzeMoveResponse: + async def analyze_move( + self, + request: Optional[Union[asset_service.AnalyzeMoveRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.AnalyzeMoveResponse: r"""Analyze moving a resource to a specified destination without kicking off the actual move. The analysis is best effort depending on the user's permissions of @@ -1899,14 +1992,14 @@ async def sample_analyze_move(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.analyze_move] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.analyze_move + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), ) # Validate the universe domain. @@ -1923,13 +2016,14 @@ async def sample_analyze_move(): # Done; return the response. return response - async def query_assets(self, - request: Optional[Union[asset_service.QueryAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.QueryAssetsResponse: + async def query_assets( + self, + request: Optional[Union[asset_service.QueryAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.QueryAssetsResponse: r"""Issue a job that queries assets using a SQL statement compatible with `BigQuery SQL `__. @@ -1997,14 +2091,14 @@ async def sample_query_assets(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.query_assets] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.query_assets + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2021,16 +2115,17 @@ async def sample_query_assets(): # Done; return the response. return response - async def create_saved_query(self, - request: Optional[Union[asset_service.CreateSavedQueryRequest, dict]] = None, - *, - parent: Optional[str] = None, - saved_query: Optional[asset_service.SavedQuery] = None, - saved_query_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.SavedQuery: + async def create_saved_query( + self, + request: Optional[Union[asset_service.CreateSavedQueryRequest, dict]] = None, + *, + parent: Optional[str] = None, + saved_query: Optional[asset_service.SavedQuery] = None, + saved_query_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.SavedQuery: r"""Creates a saved query in a parent project/folder/organization. @@ -2116,10 +2211,14 @@ async def sample_create_saved_query(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, saved_query, saved_query_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2137,14 +2236,14 @@ async def sample_create_saved_query(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_saved_query] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_saved_query + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2161,14 +2260,15 @@ async def sample_create_saved_query(): # Done; return the response. return response - async def get_saved_query(self, - request: Optional[Union[asset_service.GetSavedQueryRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.SavedQuery: + async def get_saved_query( + self, + request: Optional[Union[asset_service.GetSavedQueryRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.SavedQuery: r"""Gets details about a saved query. .. code-block:: python @@ -2229,10 +2329,14 @@ async def sample_get_saved_query(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2246,14 +2350,14 @@ async def sample_get_saved_query(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_saved_query] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_saved_query + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2270,14 +2374,15 @@ async def sample_get_saved_query(): # Done; return the response. return response - async def list_saved_queries(self, - request: Optional[Union[asset_service.ListSavedQueriesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListSavedQueriesAsyncPager: + async def list_saved_queries( + self, + request: Optional[Union[asset_service.ListSavedQueriesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSavedQueriesAsyncPager: r"""Lists all saved queries in a parent project/folder/organization. @@ -2344,10 +2449,14 @@ async def sample_list_saved_queries(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2361,14 +2470,14 @@ async def sample_list_saved_queries(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_saved_queries] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_saved_queries + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2396,15 +2505,16 @@ async def sample_list_saved_queries(): # Done; return the response. return response - async def update_saved_query(self, - request: Optional[Union[asset_service.UpdateSavedQueryRequest, dict]] = None, - *, - saved_query: Optional[asset_service.SavedQuery] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.SavedQuery: + async def update_saved_query( + self, + request: Optional[Union[asset_service.UpdateSavedQueryRequest, dict]] = None, + *, + saved_query: Optional[asset_service.SavedQuery] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.SavedQuery: r"""Updates a saved query. .. code-block:: python @@ -2473,10 +2583,14 @@ async def sample_update_saved_query(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [saved_query, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2492,14 +2606,16 @@ async def sample_update_saved_query(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_saved_query] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_saved_query + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("saved_query.name", request.saved_query.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("saved_query.name", request.saved_query.name),) + ), ) # Validate the universe domain. @@ -2516,14 +2632,15 @@ async def sample_update_saved_query(): # Done; return the response. return response - async def delete_saved_query(self, - request: Optional[Union[asset_service.DeleteSavedQueryRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def delete_saved_query( + self, + request: Optional[Union[asset_service.DeleteSavedQueryRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a saved query. .. code-block:: python @@ -2575,10 +2692,14 @@ async def sample_delete_saved_query(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2592,14 +2713,14 @@ async def sample_delete_saved_query(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_saved_query] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_saved_query + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2613,13 +2734,16 @@ async def sample_delete_saved_query(): metadata=metadata, ) - async def batch_get_effective_iam_policies(self, - request: Optional[Union[asset_service.BatchGetEffectiveIamPoliciesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.BatchGetEffectiveIamPoliciesResponse: + async def batch_get_effective_iam_policies( + self, + request: Optional[ + Union[asset_service.BatchGetEffectiveIamPoliciesRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.BatchGetEffectiveIamPoliciesResponse: r"""Gets effective IAM policies for a batch of resources. .. code-block:: python @@ -2675,14 +2799,14 @@ async def sample_batch_get_effective_iam_policies(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.batch_get_effective_iam_policies] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.batch_get_effective_iam_policies + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scope", request.scope), - )), + gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), ) # Validate the universe domain. @@ -2699,16 +2823,17 @@ async def sample_batch_get_effective_iam_policies(): # Done; return the response. return response - async def analyze_org_policies(self, - request: Optional[Union[asset_service.AnalyzeOrgPoliciesRequest, dict]] = None, - *, - scope: Optional[str] = None, - constraint: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.AnalyzeOrgPoliciesAsyncPager: + async def analyze_org_policies( + self, + request: Optional[Union[asset_service.AnalyzeOrgPoliciesRequest, dict]] = None, + *, + scope: Optional[str] = None, + constraint: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.AnalyzeOrgPoliciesAsyncPager: r"""Analyzes organization policies under a scope. .. code-block:: python @@ -2802,10 +2927,14 @@ async def sample_analyze_org_policies(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [scope, constraint, filter] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2823,14 +2952,14 @@ async def sample_analyze_org_policies(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.analyze_org_policies] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.analyze_org_policies + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scope", request.scope), - )), + gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), ) # Validate the universe domain. @@ -2858,16 +2987,19 @@ async def sample_analyze_org_policies(): # Done; return the response. return response - async def analyze_org_policy_governed_containers(self, - request: Optional[Union[asset_service.AnalyzeOrgPolicyGovernedContainersRequest, dict]] = None, - *, - scope: Optional[str] = None, - constraint: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.AnalyzeOrgPolicyGovernedContainersAsyncPager: + async def analyze_org_policy_governed_containers( + self, + request: Optional[ + Union[asset_service.AnalyzeOrgPolicyGovernedContainersRequest, dict] + ] = None, + *, + scope: Optional[str] = None, + constraint: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.AnalyzeOrgPolicyGovernedContainersAsyncPager: r"""Analyzes organization policies governed containers (projects, folders or organization) under a scope. @@ -2962,14 +3094,20 @@ async def sample_analyze_org_policy_governed_containers(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [scope, constraint, filter] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, asset_service.AnalyzeOrgPolicyGovernedContainersRequest): + if not isinstance( + request, asset_service.AnalyzeOrgPolicyGovernedContainersRequest + ): request = asset_service.AnalyzeOrgPolicyGovernedContainersRequest(request) # If we have keyword arguments corresponding to fields on the @@ -2983,14 +3121,14 @@ async def sample_analyze_org_policy_governed_containers(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.analyze_org_policy_governed_containers] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.analyze_org_policy_governed_containers + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scope", request.scope), - )), + gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), ) # Validate the universe domain. @@ -3018,16 +3156,19 @@ async def sample_analyze_org_policy_governed_containers(): # Done; return the response. return response - async def analyze_org_policy_governed_assets(self, - request: Optional[Union[asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, dict]] = None, - *, - scope: Optional[str] = None, - constraint: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.AnalyzeOrgPolicyGovernedAssetsAsyncPager: + async def analyze_org_policy_governed_assets( + self, + request: Optional[ + Union[asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, dict] + ] = None, + *, + scope: Optional[str] = None, + constraint: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.AnalyzeOrgPolicyGovernedAssetsAsyncPager: r"""Analyzes organization policies governed assets (Google Cloud resources or policies) under a scope. This RPC supports custom constraints and the following canned constraints: @@ -3193,10 +3334,14 @@ async def sample_analyze_org_policy_governed_assets(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [scope, constraint, filter] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3214,14 +3359,14 @@ async def sample_analyze_org_policy_governed_assets(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.analyze_org_policy_governed_assets] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.analyze_org_policy_governed_assets + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scope", request.scope), - )), + gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), ) # Validate the universe domain. @@ -3291,8 +3436,7 @@ async def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -3300,7 +3444,11 @@ async def get_operation( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -3311,12 +3459,13 @@ async def __aenter__(self) -> "AssetServiceAsyncClient": async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "AssetServiceAsyncClient", -) +__all__ = ("AssetServiceAsyncClient",) diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py index f0f409cc217e..0ede4389a975 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py @@ -19,7 +19,19 @@ import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +from typing import ( + Dict, + Callable, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) import warnings from google.cloud.asset_v1 import gapic_version as package_version @@ -28,11 +40,11 @@ from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.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.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 import google.protobuf try: @@ -42,6 +54,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -51,7 +64,7 @@ from google.cloud.asset_v1.services.asset_service import pagers from google.cloud.asset_v1.types import asset_service from google.cloud.asset_v1.types import assets -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.api_core.operation as operation # type: ignore import google.api_core.operation_async as operation_async # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore @@ -71,14 +84,16 @@ class AssetServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ + _transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] _transport_registry["grpc"] = AssetServiceGrpcTransport _transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport _transport_registry["rest"] = AssetServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AssetServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[AssetServiceTransport]: """Returns an appropriate transport class. Args: @@ -154,14 +169,16 @@ def _use_client_cert_effective(): bool: whether client certificate should be used for mTLS Raises: ValueError: (If using a version of google-auth without should_use_client_cert and - GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) """ # check if google-auth version supports should_use_client_cert for automatic mTLS enablement if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER return mtls.should_use_client_cert() - else: # pragma: NO COVER + else: # pragma: NO COVER # if unsupported, fallback to reading from env var - use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() if use_client_cert_str not in ("true", "false"): raise ValueError( "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" @@ -200,8 +217,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AssetServiceClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -218,23 +234,36 @@ def transport(self) -> AssetServiceTransport: return self._transport @staticmethod - def access_level_path(access_policy: str,access_level: str,) -> str: + def access_level_path( + access_policy: str, + access_level: str, + ) -> str: """Returns a fully-qualified access_level string.""" - return "accessPolicies/{access_policy}/accessLevels/{access_level}".format(access_policy=access_policy, access_level=access_level, ) + return "accessPolicies/{access_policy}/accessLevels/{access_level}".format( + access_policy=access_policy, + access_level=access_level, + ) @staticmethod - def parse_access_level_path(path: str) -> Dict[str,str]: + def parse_access_level_path(path: str) -> Dict[str, str]: """Parses a access_level path into its component segments.""" - m = re.match(r"^accessPolicies/(?P.+?)/accessLevels/(?P.+?)$", path) + m = re.match( + r"^accessPolicies/(?P.+?)/accessLevels/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def access_policy_path(access_policy: str,) -> str: + def access_policy_path( + access_policy: str, + ) -> str: """Returns a fully-qualified access_policy string.""" - return "accessPolicies/{access_policy}".format(access_policy=access_policy, ) + return "accessPolicies/{access_policy}".format( + access_policy=access_policy, + ) @staticmethod - def parse_access_policy_path(path: str) -> Dict[str,str]: + def parse_access_policy_path(path: str) -> Dict[str, str]: """Parses a access_policy path into its component segments.""" m = re.match(r"^accessPolicies/(?P.+?)$", path) return m.groupdict() if m else {} @@ -245,112 +274,170 @@ def asset_path() -> str: return "*".format() @staticmethod - def parse_asset_path(path: str) -> Dict[str,str]: + def parse_asset_path(path: str) -> Dict[str, str]: """Parses a asset path into its component segments.""" m = re.match(r"^.*$", path) return m.groupdict() if m else {} @staticmethod - def feed_path(project: str,feed: str,) -> str: + def feed_path( + project: str, + feed: str, + ) -> str: """Returns a fully-qualified feed string.""" - return "projects/{project}/feeds/{feed}".format(project=project, feed=feed, ) + return "projects/{project}/feeds/{feed}".format( + project=project, + feed=feed, + ) @staticmethod - def parse_feed_path(path: str) -> Dict[str,str]: + def parse_feed_path(path: str) -> Dict[str, str]: """Parses a feed path into its component segments.""" m = re.match(r"^projects/(?P.+?)/feeds/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def inventory_path(project: str,location: str,instance: str,) -> str: + def inventory_path( + project: str, + location: str, + instance: str, + ) -> str: """Returns a fully-qualified inventory string.""" - return "projects/{project}/locations/{location}/instances/{instance}/inventory".format(project=project, location=location, instance=instance, ) + return "projects/{project}/locations/{location}/instances/{instance}/inventory".format( + project=project, + location=location, + instance=instance, + ) @staticmethod - def parse_inventory_path(path: str) -> Dict[str,str]: + def parse_inventory_path(path: str) -> Dict[str, str]: """Parses a inventory path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)/inventory$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)/inventory$", + path, + ) return m.groupdict() if m else {} @staticmethod - def saved_query_path(project: str,saved_query: str,) -> str: + def saved_query_path( + project: str, + saved_query: str, + ) -> str: """Returns a fully-qualified saved_query string.""" - return "projects/{project}/savedQueries/{saved_query}".format(project=project, saved_query=saved_query, ) + return "projects/{project}/savedQueries/{saved_query}".format( + project=project, + saved_query=saved_query, + ) @staticmethod - def parse_saved_query_path(path: str) -> Dict[str,str]: + def parse_saved_query_path(path: str) -> Dict[str, str]: """Parses a saved_query path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/savedQueries/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/savedQueries/(?P.+?)$", path + ) return m.groupdict() if m else {} @staticmethod - def service_perimeter_path(access_policy: str,service_perimeter: str,) -> str: + def service_perimeter_path( + access_policy: str, + service_perimeter: str, + ) -> str: """Returns a fully-qualified service_perimeter string.""" - return "accessPolicies/{access_policy}/servicePerimeters/{service_perimeter}".format(access_policy=access_policy, service_perimeter=service_perimeter, ) + return "accessPolicies/{access_policy}/servicePerimeters/{service_perimeter}".format( + access_policy=access_policy, + service_perimeter=service_perimeter, + ) @staticmethod - def parse_service_perimeter_path(path: str) -> Dict[str,str]: + def parse_service_perimeter_path(path: str) -> Dict[str, str]: """Parses a service_perimeter path into its component segments.""" - m = re.match(r"^accessPolicies/(?P.+?)/servicePerimeters/(?P.+?)$", path) + m = re.match( + r"^accessPolicies/(?P.+?)/servicePerimeters/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + def common_billing_account_path( + billing_account: str, + ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path(folder: str, ) -> str: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path(organization: str, ) -> str: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path(project: str, ) -> str: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path(project: str, location: str, ) -> str: + def common_location_path( + project: str, + location: str, + ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -382,14 +469,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = AssetServiceClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Figure out the client cert source to use. client_cert_source = None @@ -402,7 +493,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): api_endpoint = cls.DEFAULT_MTLS_ENDPOINT else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -427,7 +520,9 @@ def _read_environment_variables(): use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod @@ -450,7 +545,9 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: """Return the API endpoint used by the client. Args: @@ -466,17 +563,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): _default_universe = AssetServiceClient._DEFAULT_UNIVERSE if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) api_endpoint = AssetServiceClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = AssetServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = AssetServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) return api_endpoint @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: """Return the universe domain used by the client. Args: @@ -512,15 +617,18 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError + self, error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: return cred = self._transport._credentials @@ -553,12 +661,16 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AssetServiceTransport, Callable[..., AssetServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, AssetServiceTransport, Callable[..., AssetServiceTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the asset service client. Args: @@ -616,13 +728,23 @@ def __init__(self, *, self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = AssetServiceClient._read_environment_variables() - self._client_cert_source = AssetServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = AssetServiceClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = AssetServiceClient._read_environment_variables() + self._client_cert_source = AssetServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = AssetServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -634,7 +756,9 @@ def __init__(self, *, api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -643,8 +767,10 @@ def __init__(self, *, if transport_provided: # transport is a AssetServiceTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if self._client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes " @@ -653,20 +779,26 @@ def __init__(self, *, self._transport = cast(AssetServiceTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - AssetServiceClient._get_api_endpoint( - self._client_options.api_endpoint, - self._client_cert_source, - self._universe_domain, - self._use_mtls_endpoint)) + self._api_endpoint = self._api_endpoint or AssetServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) - transport_init: Union[Type[AssetServiceTransport], Callable[..., AssetServiceTransport]] = ( + transport_init: Union[ + Type[AssetServiceTransport], Callable[..., AssetServiceTransport] + ] = ( AssetServiceClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., AssetServiceTransport], transport) @@ -685,27 +817,36 @@ def __init__(self, *, ) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.asset_v1.AssetServiceClient`.", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { "serviceName": "google.cloud.asset.v1.AssetService", "credentialsType": None, - } + }, ) - def export_assets(self, - request: Optional[Union[asset_service.ExportAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def export_assets( + self, + request: Optional[Union[asset_service.ExportAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Exports assets with time and resource types to a given Cloud Storage location/BigQuery table. For Cloud Storage location destinations, the output format is newline-delimited JSON. Each @@ -789,9 +930,7 @@ def sample_export_assets(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -816,14 +955,15 @@ def sample_export_assets(): # Done; return the response. return response - def list_assets(self, - request: Optional[Union[asset_service.ListAssetsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAssetsPager: + def list_assets( + self, + request: Optional[Union[asset_service.ListAssetsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAssetsPager: r"""Lists assets with time and resource types and returns paged results in response. @@ -890,10 +1030,14 @@ def sample_list_assets(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -911,9 +1055,7 @@ def sample_list_assets(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -941,13 +1083,16 @@ def sample_list_assets(): # Done; return the response. return response - def batch_get_assets_history(self, - request: Optional[Union[asset_service.BatchGetAssetsHistoryRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.BatchGetAssetsHistoryResponse: + def batch_get_assets_history( + self, + request: Optional[ + Union[asset_service.BatchGetAssetsHistoryRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.BatchGetAssetsHistoryResponse: r"""Batch gets the update history of assets that overlap a time window. For IAM_POLICY content, this API outputs history when the asset and its attached IAM POLICY both exist. This can @@ -1010,9 +1155,7 @@ def sample_batch_get_assets_history(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1029,14 +1172,15 @@ def sample_batch_get_assets_history(): # Done; return the response. return response - def create_feed(self, - request: Optional[Union[asset_service.CreateFeedRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.Feed: + def create_feed( + self, + request: Optional[Union[asset_service.CreateFeedRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.Feed: r"""Creates a feed in a parent project/folder/organization to listen to its asset updates. @@ -1113,10 +1257,14 @@ def sample_create_feed(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1134,9 +1282,7 @@ def sample_create_feed(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1153,14 +1299,15 @@ def sample_create_feed(): # Done; return the response. return response - def get_feed(self, - request: Optional[Union[asset_service.GetFeedRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.Feed: + def get_feed( + self, + request: Optional[Union[asset_service.GetFeedRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.Feed: r"""Gets details about an asset feed. .. code-block:: python @@ -1225,10 +1372,14 @@ def sample_get_feed(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1246,9 +1397,7 @@ def sample_get_feed(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1265,14 +1414,15 @@ def sample_get_feed(): # Done; return the response. return response - def list_feeds(self, - request: Optional[Union[asset_service.ListFeedsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.ListFeedsResponse: + def list_feeds( + self, + request: Optional[Union[asset_service.ListFeedsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.ListFeedsResponse: r"""Lists all asset feeds in a parent project/folder/organization. @@ -1332,10 +1482,14 @@ def sample_list_feeds(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1353,9 +1507,7 @@ def sample_list_feeds(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1372,14 +1524,15 @@ def sample_list_feeds(): # Done; return the response. return response - def update_feed(self, - request: Optional[Union[asset_service.UpdateFeedRequest, dict]] = None, - *, - feed: Optional[asset_service.Feed] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.Feed: + def update_feed( + self, + request: Optional[Union[asset_service.UpdateFeedRequest, dict]] = None, + *, + feed: Optional[asset_service.Feed] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.Feed: r"""Updates an asset feed configuration. .. code-block:: python @@ -1448,10 +1601,14 @@ def sample_update_feed(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [feed] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1469,9 +1626,9 @@ def sample_update_feed(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("feed.name", request.feed.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("feed.name", request.feed.name),) + ), ) # Validate the universe domain. @@ -1488,14 +1645,15 @@ def sample_update_feed(): # Done; return the response. return response - def delete_feed(self, - request: Optional[Union[asset_service.DeleteFeedRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_feed( + self, + request: Optional[Union[asset_service.DeleteFeedRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes an asset feed. .. code-block:: python @@ -1545,10 +1703,14 @@ def sample_delete_feed(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1566,9 +1728,7 @@ def sample_delete_feed(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1582,16 +1742,17 @@ def sample_delete_feed(): metadata=metadata, ) - def search_all_resources(self, - request: Optional[Union[asset_service.SearchAllResourcesRequest, dict]] = None, - *, - scope: Optional[str] = None, - query: Optional[str] = None, - asset_types: Optional[MutableSequence[str]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.SearchAllResourcesPager: + def search_all_resources( + self, + request: Optional[Union[asset_service.SearchAllResourcesRequest, dict]] = None, + *, + scope: Optional[str] = None, + query: Optional[str] = None, + asset_types: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.SearchAllResourcesPager: r"""Searches all Google Cloud resources within the specified scope, such as a project, folder, or organization. The caller must be granted the ``cloudasset.assets.searchAllResources`` permission @@ -1794,10 +1955,14 @@ def sample_search_all_resources(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [scope, query, asset_types] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1819,9 +1984,7 @@ def sample_search_all_resources(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scope", request.scope), - )), + gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), ) # Validate the universe domain. @@ -1849,15 +2012,18 @@ def sample_search_all_resources(): # Done; return the response. return response - def search_all_iam_policies(self, - request: Optional[Union[asset_service.SearchAllIamPoliciesRequest, dict]] = None, - *, - scope: Optional[str] = None, - query: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.SearchAllIamPoliciesPager: + def search_all_iam_policies( + self, + request: Optional[ + Union[asset_service.SearchAllIamPoliciesRequest, dict] + ] = None, + *, + scope: Optional[str] = None, + query: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.SearchAllIamPoliciesPager: r"""Searches all IAM policies within the specified scope, such as a project, folder, or organization. The caller must be granted the ``cloudasset.assets.searchAllIamPolicies`` permission on the @@ -1987,10 +2153,14 @@ def sample_search_all_iam_policies(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [scope, query] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2010,9 +2180,7 @@ def sample_search_all_iam_policies(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scope", request.scope), - )), + gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), ) # Validate the universe domain. @@ -2040,13 +2208,14 @@ def sample_search_all_iam_policies(): # Done; return the response. return response - def analyze_iam_policy(self, - request: Optional[Union[asset_service.AnalyzeIamPolicyRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.AnalyzeIamPolicyResponse: + def analyze_iam_policy( + self, + request: Optional[Union[asset_service.AnalyzeIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.AnalyzeIamPolicyResponse: r"""Analyzes IAM policies to answer which identities have what accesses on which resources. @@ -2110,9 +2279,9 @@ def sample_analyze_iam_policy(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("analysis_query.scope", request.analysis_query.scope), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("analysis_query.scope", request.analysis_query.scope),) + ), ) # Validate the universe domain. @@ -2129,13 +2298,16 @@ def sample_analyze_iam_policy(): # Done; return the response. return response - def analyze_iam_policy_longrunning(self, - request: Optional[Union[asset_service.AnalyzeIamPolicyLongrunningRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def analyze_iam_policy_longrunning( + self, + request: Optional[ + Union[asset_service.AnalyzeIamPolicyLongrunningRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Analyzes IAM policies asynchronously to answer which identities have what accesses on which resources, and writes the analysis results to a Google Cloud Storage or a BigQuery destination. For @@ -2214,14 +2386,16 @@ def sample_analyze_iam_policy_longrunning(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.analyze_iam_policy_longrunning] + rpc = self._transport._wrapped_methods[ + self._transport.analyze_iam_policy_longrunning + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("analysis_query.scope", request.analysis_query.scope), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("analysis_query.scope", request.analysis_query.scope),) + ), ) # Validate the universe domain. @@ -2246,13 +2420,14 @@ def sample_analyze_iam_policy_longrunning(): # Done; return the response. return response - def analyze_move(self, - request: Optional[Union[asset_service.AnalyzeMoveRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.AnalyzeMoveResponse: + def analyze_move( + self, + request: Optional[Union[asset_service.AnalyzeMoveRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.AnalyzeMoveResponse: r"""Analyze moving a resource to a specified destination without kicking off the actual move. The analysis is best effort depending on the user's permissions of @@ -2319,9 +2494,7 @@ def sample_analyze_move(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), ) # Validate the universe domain. @@ -2338,13 +2511,14 @@ def sample_analyze_move(): # Done; return the response. return response - def query_assets(self, - request: Optional[Union[asset_service.QueryAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.QueryAssetsResponse: + def query_assets( + self, + request: Optional[Union[asset_service.QueryAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.QueryAssetsResponse: r"""Issue a job that queries assets using a SQL statement compatible with `BigQuery SQL `__. @@ -2417,9 +2591,7 @@ def sample_query_assets(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2436,16 +2608,17 @@ def sample_query_assets(): # Done; return the response. return response - def create_saved_query(self, - request: Optional[Union[asset_service.CreateSavedQueryRequest, dict]] = None, - *, - parent: Optional[str] = None, - saved_query: Optional[asset_service.SavedQuery] = None, - saved_query_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.SavedQuery: + def create_saved_query( + self, + request: Optional[Union[asset_service.CreateSavedQueryRequest, dict]] = None, + *, + parent: Optional[str] = None, + saved_query: Optional[asset_service.SavedQuery] = None, + saved_query_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.SavedQuery: r"""Creates a saved query in a parent project/folder/organization. @@ -2531,10 +2704,14 @@ def sample_create_saved_query(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, saved_query, saved_query_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2556,9 +2733,7 @@ def sample_create_saved_query(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2575,14 +2750,15 @@ def sample_create_saved_query(): # Done; return the response. return response - def get_saved_query(self, - request: Optional[Union[asset_service.GetSavedQueryRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.SavedQuery: + def get_saved_query( + self, + request: Optional[Union[asset_service.GetSavedQueryRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.SavedQuery: r"""Gets details about a saved query. .. code-block:: python @@ -2643,10 +2819,14 @@ def sample_get_saved_query(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2664,9 +2844,7 @@ def sample_get_saved_query(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2683,14 +2861,15 @@ def sample_get_saved_query(): # Done; return the response. return response - def list_saved_queries(self, - request: Optional[Union[asset_service.ListSavedQueriesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListSavedQueriesPager: + def list_saved_queries( + self, + request: Optional[Union[asset_service.ListSavedQueriesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSavedQueriesPager: r"""Lists all saved queries in a parent project/folder/organization. @@ -2757,10 +2936,14 @@ def sample_list_saved_queries(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2778,9 +2961,7 @@ def sample_list_saved_queries(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2808,15 +2989,16 @@ def sample_list_saved_queries(): # Done; return the response. return response - def update_saved_query(self, - request: Optional[Union[asset_service.UpdateSavedQueryRequest, dict]] = None, - *, - saved_query: Optional[asset_service.SavedQuery] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.SavedQuery: + def update_saved_query( + self, + request: Optional[Union[asset_service.UpdateSavedQueryRequest, dict]] = None, + *, + saved_query: Optional[asset_service.SavedQuery] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.SavedQuery: r"""Updates a saved query. .. code-block:: python @@ -2885,10 +3067,14 @@ def sample_update_saved_query(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [saved_query, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2908,9 +3094,9 @@ def sample_update_saved_query(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("saved_query.name", request.saved_query.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("saved_query.name", request.saved_query.name),) + ), ) # Validate the universe domain. @@ -2927,14 +3113,15 @@ def sample_update_saved_query(): # Done; return the response. return response - def delete_saved_query(self, - request: Optional[Union[asset_service.DeleteSavedQueryRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_saved_query( + self, + request: Optional[Union[asset_service.DeleteSavedQueryRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a saved query. .. code-block:: python @@ -2986,10 +3173,14 @@ def sample_delete_saved_query(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3007,9 +3198,7 @@ def sample_delete_saved_query(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3023,13 +3212,16 @@ def sample_delete_saved_query(): metadata=metadata, ) - def batch_get_effective_iam_policies(self, - request: Optional[Union[asset_service.BatchGetEffectiveIamPoliciesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> asset_service.BatchGetEffectiveIamPoliciesResponse: + def batch_get_effective_iam_policies( + self, + request: Optional[ + Union[asset_service.BatchGetEffectiveIamPoliciesRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.BatchGetEffectiveIamPoliciesResponse: r"""Gets effective IAM policies for a batch of resources. .. code-block:: python @@ -3085,14 +3277,14 @@ def sample_batch_get_effective_iam_policies(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_get_effective_iam_policies] + rpc = self._transport._wrapped_methods[ + self._transport.batch_get_effective_iam_policies + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scope", request.scope), - )), + gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), ) # Validate the universe domain. @@ -3109,16 +3301,17 @@ def sample_batch_get_effective_iam_policies(): # Done; return the response. return response - def analyze_org_policies(self, - request: Optional[Union[asset_service.AnalyzeOrgPoliciesRequest, dict]] = None, - *, - scope: Optional[str] = None, - constraint: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.AnalyzeOrgPoliciesPager: + def analyze_org_policies( + self, + request: Optional[Union[asset_service.AnalyzeOrgPoliciesRequest, dict]] = None, + *, + scope: Optional[str] = None, + constraint: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.AnalyzeOrgPoliciesPager: r"""Analyzes organization policies under a scope. .. code-block:: python @@ -3212,10 +3405,14 @@ def sample_analyze_org_policies(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [scope, constraint, filter] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3237,9 +3434,7 @@ def sample_analyze_org_policies(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scope", request.scope), - )), + gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), ) # Validate the universe domain. @@ -3267,16 +3462,19 @@ def sample_analyze_org_policies(): # Done; return the response. return response - def analyze_org_policy_governed_containers(self, - request: Optional[Union[asset_service.AnalyzeOrgPolicyGovernedContainersRequest, dict]] = None, - *, - scope: Optional[str] = None, - constraint: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.AnalyzeOrgPolicyGovernedContainersPager: + def analyze_org_policy_governed_containers( + self, + request: Optional[ + Union[asset_service.AnalyzeOrgPolicyGovernedContainersRequest, dict] + ] = None, + *, + scope: Optional[str] = None, + constraint: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.AnalyzeOrgPolicyGovernedContainersPager: r"""Analyzes organization policies governed containers (projects, folders or organization) under a scope. @@ -3371,14 +3569,20 @@ def sample_analyze_org_policy_governed_containers(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [scope, constraint, filter] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, asset_service.AnalyzeOrgPolicyGovernedContainersRequest): + if not isinstance( + request, asset_service.AnalyzeOrgPolicyGovernedContainersRequest + ): request = asset_service.AnalyzeOrgPolicyGovernedContainersRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -3391,14 +3595,14 @@ def sample_analyze_org_policy_governed_containers(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.analyze_org_policy_governed_containers] + rpc = self._transport._wrapped_methods[ + self._transport.analyze_org_policy_governed_containers + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scope", request.scope), - )), + gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), ) # Validate the universe domain. @@ -3426,16 +3630,19 @@ def sample_analyze_org_policy_governed_containers(): # Done; return the response. return response - def analyze_org_policy_governed_assets(self, - request: Optional[Union[asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, dict]] = None, - *, - scope: Optional[str] = None, - constraint: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.AnalyzeOrgPolicyGovernedAssetsPager: + def analyze_org_policy_governed_assets( + self, + request: Optional[ + Union[asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, dict] + ] = None, + *, + scope: Optional[str] = None, + constraint: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.AnalyzeOrgPolicyGovernedAssetsPager: r"""Analyzes organization policies governed assets (Google Cloud resources or policies) under a scope. This RPC supports custom constraints and the following canned constraints: @@ -3601,10 +3808,14 @@ def sample_analyze_org_policy_governed_assets(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [scope, constraint, filter] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3621,14 +3832,14 @@ def sample_analyze_org_policy_governed_assets(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.analyze_org_policy_governed_assets] + rpc = self._transport._wrapped_methods[ + self._transport.analyze_org_policy_governed_assets + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scope", request.scope), - )), + gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), ) # Validate the universe domain. @@ -3711,8 +3922,7 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -3721,7 +3931,11 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -3730,18 +3944,11 @@ def get_operation( raise e - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "AssetServiceClient", -) +__all__ = ("AssetServiceClient",) diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/base.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/base.py index 0cb26a225624..331a83c43b8e 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/base.py @@ -25,14 +25,16 @@ from google.api_core import retry as retries from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf from google.cloud.asset_v1.types import asset_service -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ @@ -41,24 +43,23 @@ class AssetServiceTransport(abc.ABC): """Abstract transport class for AssetService.""" - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - DEFAULT_HOST: str = 'cloudasset.googleapis.com' + DEFAULT_HOST: str = "cloudasset.googleapis.com" def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -97,31 +98,43 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host self._wrapped_methods: Dict[Callable, Callable] = {} @@ -322,14 +335,14 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -339,210 +352,248 @@ def operations_client(self): raise NotImplementedError() @property - def export_assets(self) -> Callable[ - [asset_service.ExportAssetsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def export_assets( + self, + ) -> Callable[ + [asset_service.ExportAssetsRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def list_assets(self) -> Callable[ - [asset_service.ListAssetsRequest], - Union[ - asset_service.ListAssetsResponse, - Awaitable[asset_service.ListAssetsResponse] - ]]: + def list_assets( + self, + ) -> Callable[ + [asset_service.ListAssetsRequest], + Union[ + asset_service.ListAssetsResponse, + Awaitable[asset_service.ListAssetsResponse], + ], + ]: raise NotImplementedError() @property - def batch_get_assets_history(self) -> Callable[ - [asset_service.BatchGetAssetsHistoryRequest], - Union[ - asset_service.BatchGetAssetsHistoryResponse, - Awaitable[asset_service.BatchGetAssetsHistoryResponse] - ]]: + def batch_get_assets_history( + self, + ) -> Callable[ + [asset_service.BatchGetAssetsHistoryRequest], + Union[ + asset_service.BatchGetAssetsHistoryResponse, + Awaitable[asset_service.BatchGetAssetsHistoryResponse], + ], + ]: raise NotImplementedError() @property - def create_feed(self) -> Callable[ - [asset_service.CreateFeedRequest], - Union[ - asset_service.Feed, - Awaitable[asset_service.Feed] - ]]: + def create_feed( + self, + ) -> Callable[ + [asset_service.CreateFeedRequest], + Union[asset_service.Feed, Awaitable[asset_service.Feed]], + ]: raise NotImplementedError() @property - def get_feed(self) -> Callable[ - [asset_service.GetFeedRequest], - Union[ - asset_service.Feed, - Awaitable[asset_service.Feed] - ]]: + def get_feed( + self, + ) -> Callable[ + [asset_service.GetFeedRequest], + Union[asset_service.Feed, Awaitable[asset_service.Feed]], + ]: raise NotImplementedError() @property - def list_feeds(self) -> Callable[ - [asset_service.ListFeedsRequest], - Union[ - asset_service.ListFeedsResponse, - Awaitable[asset_service.ListFeedsResponse] - ]]: + def list_feeds( + self, + ) -> Callable[ + [asset_service.ListFeedsRequest], + Union[ + asset_service.ListFeedsResponse, Awaitable[asset_service.ListFeedsResponse] + ], + ]: raise NotImplementedError() @property - def update_feed(self) -> Callable[ - [asset_service.UpdateFeedRequest], - Union[ - asset_service.Feed, - Awaitable[asset_service.Feed] - ]]: + def update_feed( + self, + ) -> Callable[ + [asset_service.UpdateFeedRequest], + Union[asset_service.Feed, Awaitable[asset_service.Feed]], + ]: raise NotImplementedError() @property - def delete_feed(self) -> Callable[ - [asset_service.DeleteFeedRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_feed( + self, + ) -> Callable[ + [asset_service.DeleteFeedRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property - def search_all_resources(self) -> Callable[ - [asset_service.SearchAllResourcesRequest], - Union[ - asset_service.SearchAllResourcesResponse, - Awaitable[asset_service.SearchAllResourcesResponse] - ]]: + def search_all_resources( + self, + ) -> Callable[ + [asset_service.SearchAllResourcesRequest], + Union[ + asset_service.SearchAllResourcesResponse, + Awaitable[asset_service.SearchAllResourcesResponse], + ], + ]: raise NotImplementedError() @property - def search_all_iam_policies(self) -> Callable[ - [asset_service.SearchAllIamPoliciesRequest], - Union[ - asset_service.SearchAllIamPoliciesResponse, - Awaitable[asset_service.SearchAllIamPoliciesResponse] - ]]: + def search_all_iam_policies( + self, + ) -> Callable[ + [asset_service.SearchAllIamPoliciesRequest], + Union[ + asset_service.SearchAllIamPoliciesResponse, + Awaitable[asset_service.SearchAllIamPoliciesResponse], + ], + ]: raise NotImplementedError() @property - def analyze_iam_policy(self) -> Callable[ - [asset_service.AnalyzeIamPolicyRequest], - Union[ - asset_service.AnalyzeIamPolicyResponse, - Awaitable[asset_service.AnalyzeIamPolicyResponse] - ]]: + def analyze_iam_policy( + self, + ) -> Callable[ + [asset_service.AnalyzeIamPolicyRequest], + Union[ + asset_service.AnalyzeIamPolicyResponse, + Awaitable[asset_service.AnalyzeIamPolicyResponse], + ], + ]: raise NotImplementedError() @property - def analyze_iam_policy_longrunning(self) -> Callable[ - [asset_service.AnalyzeIamPolicyLongrunningRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def analyze_iam_policy_longrunning( + self, + ) -> Callable[ + [asset_service.AnalyzeIamPolicyLongrunningRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def analyze_move(self) -> Callable[ - [asset_service.AnalyzeMoveRequest], - Union[ - asset_service.AnalyzeMoveResponse, - Awaitable[asset_service.AnalyzeMoveResponse] - ]]: + def analyze_move( + self, + ) -> Callable[ + [asset_service.AnalyzeMoveRequest], + Union[ + asset_service.AnalyzeMoveResponse, + Awaitable[asset_service.AnalyzeMoveResponse], + ], + ]: raise NotImplementedError() @property - def query_assets(self) -> Callable[ - [asset_service.QueryAssetsRequest], - Union[ - asset_service.QueryAssetsResponse, - Awaitable[asset_service.QueryAssetsResponse] - ]]: + def query_assets( + self, + ) -> Callable[ + [asset_service.QueryAssetsRequest], + Union[ + asset_service.QueryAssetsResponse, + Awaitable[asset_service.QueryAssetsResponse], + ], + ]: raise NotImplementedError() @property - def create_saved_query(self) -> Callable[ - [asset_service.CreateSavedQueryRequest], - Union[ - asset_service.SavedQuery, - Awaitable[asset_service.SavedQuery] - ]]: + def create_saved_query( + self, + ) -> Callable[ + [asset_service.CreateSavedQueryRequest], + Union[asset_service.SavedQuery, Awaitable[asset_service.SavedQuery]], + ]: raise NotImplementedError() @property - def get_saved_query(self) -> Callable[ - [asset_service.GetSavedQueryRequest], - Union[ - asset_service.SavedQuery, - Awaitable[asset_service.SavedQuery] - ]]: + def get_saved_query( + self, + ) -> Callable[ + [asset_service.GetSavedQueryRequest], + Union[asset_service.SavedQuery, Awaitable[asset_service.SavedQuery]], + ]: raise NotImplementedError() @property - def list_saved_queries(self) -> Callable[ - [asset_service.ListSavedQueriesRequest], - Union[ - asset_service.ListSavedQueriesResponse, - Awaitable[asset_service.ListSavedQueriesResponse] - ]]: + def list_saved_queries( + self, + ) -> Callable[ + [asset_service.ListSavedQueriesRequest], + Union[ + asset_service.ListSavedQueriesResponse, + Awaitable[asset_service.ListSavedQueriesResponse], + ], + ]: raise NotImplementedError() @property - def update_saved_query(self) -> Callable[ - [asset_service.UpdateSavedQueryRequest], - Union[ - asset_service.SavedQuery, - Awaitable[asset_service.SavedQuery] - ]]: + def update_saved_query( + self, + ) -> Callable[ + [asset_service.UpdateSavedQueryRequest], + Union[asset_service.SavedQuery, Awaitable[asset_service.SavedQuery]], + ]: raise NotImplementedError() @property - def delete_saved_query(self) -> Callable[ - [asset_service.DeleteSavedQueryRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_saved_query( + self, + ) -> Callable[ + [asset_service.DeleteSavedQueryRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property - def batch_get_effective_iam_policies(self) -> Callable[ - [asset_service.BatchGetEffectiveIamPoliciesRequest], - Union[ - asset_service.BatchGetEffectiveIamPoliciesResponse, - Awaitable[asset_service.BatchGetEffectiveIamPoliciesResponse] - ]]: + def batch_get_effective_iam_policies( + self, + ) -> Callable[ + [asset_service.BatchGetEffectiveIamPoliciesRequest], + Union[ + asset_service.BatchGetEffectiveIamPoliciesResponse, + Awaitable[asset_service.BatchGetEffectiveIamPoliciesResponse], + ], + ]: raise NotImplementedError() @property - def analyze_org_policies(self) -> Callable[ - [asset_service.AnalyzeOrgPoliciesRequest], - Union[ - asset_service.AnalyzeOrgPoliciesResponse, - Awaitable[asset_service.AnalyzeOrgPoliciesResponse] - ]]: + def analyze_org_policies( + self, + ) -> Callable[ + [asset_service.AnalyzeOrgPoliciesRequest], + Union[ + asset_service.AnalyzeOrgPoliciesResponse, + Awaitable[asset_service.AnalyzeOrgPoliciesResponse], + ], + ]: raise NotImplementedError() @property - def analyze_org_policy_governed_containers(self) -> Callable[ - [asset_service.AnalyzeOrgPolicyGovernedContainersRequest], - Union[ - asset_service.AnalyzeOrgPolicyGovernedContainersResponse, - Awaitable[asset_service.AnalyzeOrgPolicyGovernedContainersResponse] - ]]: + def analyze_org_policy_governed_containers( + self, + ) -> Callable[ + [asset_service.AnalyzeOrgPolicyGovernedContainersRequest], + Union[ + asset_service.AnalyzeOrgPolicyGovernedContainersResponse, + Awaitable[asset_service.AnalyzeOrgPolicyGovernedContainersResponse], + ], + ]: raise NotImplementedError() @property - def analyze_org_policy_governed_assets(self) -> Callable[ - [asset_service.AnalyzeOrgPolicyGovernedAssetsRequest], - Union[ - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse, - Awaitable[asset_service.AnalyzeOrgPolicyGovernedAssetsResponse] - ]]: + def analyze_org_policy_governed_assets( + self, + ) -> Callable[ + [asset_service.AnalyzeOrgPolicyGovernedAssetsRequest], + Union[ + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse, + Awaitable[asset_service.AnalyzeOrgPolicyGovernedAssetsResponse], + ], + ]: raise NotImplementedError() @property @@ -559,6 +610,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'AssetServiceTransport', -) +__all__ = ("AssetServiceTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/rest.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/rest.py index 84a68bc291aa..efaabcec898f 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/rest.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/rest.py @@ -49,6 +49,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -261,7 +262,14 @@ def post_update_saved_query(self, response): """ - def pre_analyze_iam_policy(self, request: asset_service.AnalyzeIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.AnalyzeIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_analyze_iam_policy( + self, + request: asset_service.AnalyzeIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.AnalyzeIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for analyze_iam_policy Override in a subclass to manipulate the request or metadata @@ -269,7 +277,9 @@ def pre_analyze_iam_policy(self, request: asset_service.AnalyzeIamPolicyRequest, """ return request, metadata - def post_analyze_iam_policy(self, response: asset_service.AnalyzeIamPolicyResponse) -> asset_service.AnalyzeIamPolicyResponse: + def post_analyze_iam_policy( + self, response: asset_service.AnalyzeIamPolicyResponse + ) -> asset_service.AnalyzeIamPolicyResponse: """Post-rpc interceptor for analyze_iam_policy DEPRECATED. Please use the `post_analyze_iam_policy_with_metadata` @@ -282,7 +292,13 @@ def post_analyze_iam_policy(self, response: asset_service.AnalyzeIamPolicyRespon """ return response - def post_analyze_iam_policy_with_metadata(self, response: asset_service.AnalyzeIamPolicyResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.AnalyzeIamPolicyResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_analyze_iam_policy_with_metadata( + self, + response: asset_service.AnalyzeIamPolicyResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.AnalyzeIamPolicyResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for analyze_iam_policy Override in a subclass to read or manipulate the response or metadata after it @@ -297,7 +313,14 @@ def post_analyze_iam_policy_with_metadata(self, response: asset_service.AnalyzeI """ return response, metadata - def pre_analyze_iam_policy_longrunning(self, request: asset_service.AnalyzeIamPolicyLongrunningRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.AnalyzeIamPolicyLongrunningRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_analyze_iam_policy_longrunning( + self, + request: asset_service.AnalyzeIamPolicyLongrunningRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.AnalyzeIamPolicyLongrunningRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for analyze_iam_policy_longrunning Override in a subclass to manipulate the request or metadata @@ -305,7 +328,9 @@ def pre_analyze_iam_policy_longrunning(self, request: asset_service.AnalyzeIamPo """ return request, metadata - def post_analyze_iam_policy_longrunning(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_analyze_iam_policy_longrunning( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for analyze_iam_policy_longrunning DEPRECATED. Please use the `post_analyze_iam_policy_longrunning_with_metadata` @@ -318,7 +343,11 @@ def post_analyze_iam_policy_longrunning(self, response: operations_pb2.Operation """ return response - def post_analyze_iam_policy_longrunning_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_analyze_iam_policy_longrunning_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for analyze_iam_policy_longrunning Override in a subclass to read or manipulate the response or metadata after it @@ -333,7 +362,13 @@ def post_analyze_iam_policy_longrunning_with_metadata(self, response: operations """ return response, metadata - def pre_analyze_move(self, request: asset_service.AnalyzeMoveRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.AnalyzeMoveRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_analyze_move( + self, + request: asset_service.AnalyzeMoveRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.AnalyzeMoveRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for analyze_move Override in a subclass to manipulate the request or metadata @@ -341,7 +376,9 @@ def pre_analyze_move(self, request: asset_service.AnalyzeMoveRequest, metadata: """ return request, metadata - def post_analyze_move(self, response: asset_service.AnalyzeMoveResponse) -> asset_service.AnalyzeMoveResponse: + def post_analyze_move( + self, response: asset_service.AnalyzeMoveResponse + ) -> asset_service.AnalyzeMoveResponse: """Post-rpc interceptor for analyze_move DEPRECATED. Please use the `post_analyze_move_with_metadata` @@ -354,7 +391,13 @@ def post_analyze_move(self, response: asset_service.AnalyzeMoveResponse) -> asse """ return response - def post_analyze_move_with_metadata(self, response: asset_service.AnalyzeMoveResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.AnalyzeMoveResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_analyze_move_with_metadata( + self, + response: asset_service.AnalyzeMoveResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.AnalyzeMoveResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for analyze_move Override in a subclass to read or manipulate the response or metadata after it @@ -369,7 +412,13 @@ def post_analyze_move_with_metadata(self, response: asset_service.AnalyzeMoveRes """ return response, metadata - def pre_analyze_org_policies(self, request: asset_service.AnalyzeOrgPoliciesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.AnalyzeOrgPoliciesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_analyze_org_policies( + self, + request: asset_service.AnalyzeOrgPoliciesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.AnalyzeOrgPoliciesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for analyze_org_policies Override in a subclass to manipulate the request or metadata @@ -377,7 +426,9 @@ def pre_analyze_org_policies(self, request: asset_service.AnalyzeOrgPoliciesRequ """ return request, metadata - def post_analyze_org_policies(self, response: asset_service.AnalyzeOrgPoliciesResponse) -> asset_service.AnalyzeOrgPoliciesResponse: + def post_analyze_org_policies( + self, response: asset_service.AnalyzeOrgPoliciesResponse + ) -> asset_service.AnalyzeOrgPoliciesResponse: """Post-rpc interceptor for analyze_org_policies DEPRECATED. Please use the `post_analyze_org_policies_with_metadata` @@ -390,7 +441,14 @@ def post_analyze_org_policies(self, response: asset_service.AnalyzeOrgPoliciesRe """ return response - def post_analyze_org_policies_with_metadata(self, response: asset_service.AnalyzeOrgPoliciesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.AnalyzeOrgPoliciesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_analyze_org_policies_with_metadata( + self, + response: asset_service.AnalyzeOrgPoliciesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.AnalyzeOrgPoliciesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for analyze_org_policies Override in a subclass to read or manipulate the response or metadata after it @@ -405,7 +463,14 @@ def post_analyze_org_policies_with_metadata(self, response: asset_service.Analyz """ return response, metadata - def pre_analyze_org_policy_governed_assets(self, request: asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_analyze_org_policy_governed_assets( + self, + request: asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for analyze_org_policy_governed_assets Override in a subclass to manipulate the request or metadata @@ -413,7 +478,9 @@ def pre_analyze_org_policy_governed_assets(self, request: asset_service.AnalyzeO """ return request, metadata - def post_analyze_org_policy_governed_assets(self, response: asset_service.AnalyzeOrgPolicyGovernedAssetsResponse) -> asset_service.AnalyzeOrgPolicyGovernedAssetsResponse: + def post_analyze_org_policy_governed_assets( + self, response: asset_service.AnalyzeOrgPolicyGovernedAssetsResponse + ) -> asset_service.AnalyzeOrgPolicyGovernedAssetsResponse: """Post-rpc interceptor for analyze_org_policy_governed_assets DEPRECATED. Please use the `post_analyze_org_policy_governed_assets_with_metadata` @@ -426,7 +493,14 @@ def post_analyze_org_policy_governed_assets(self, response: asset_service.Analyz """ return response - def post_analyze_org_policy_governed_assets_with_metadata(self, response: asset_service.AnalyzeOrgPolicyGovernedAssetsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.AnalyzeOrgPolicyGovernedAssetsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_analyze_org_policy_governed_assets_with_metadata( + self, + response: asset_service.AnalyzeOrgPolicyGovernedAssetsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for analyze_org_policy_governed_assets Override in a subclass to read or manipulate the response or metadata after it @@ -441,7 +515,14 @@ def post_analyze_org_policy_governed_assets_with_metadata(self, response: asset_ """ return response, metadata - def pre_analyze_org_policy_governed_containers(self, request: asset_service.AnalyzeOrgPolicyGovernedContainersRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.AnalyzeOrgPolicyGovernedContainersRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_analyze_org_policy_governed_containers( + self, + request: asset_service.AnalyzeOrgPolicyGovernedContainersRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.AnalyzeOrgPolicyGovernedContainersRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for analyze_org_policy_governed_containers Override in a subclass to manipulate the request or metadata @@ -449,7 +530,9 @@ def pre_analyze_org_policy_governed_containers(self, request: asset_service.Anal """ return request, metadata - def post_analyze_org_policy_governed_containers(self, response: asset_service.AnalyzeOrgPolicyGovernedContainersResponse) -> asset_service.AnalyzeOrgPolicyGovernedContainersResponse: + def post_analyze_org_policy_governed_containers( + self, response: asset_service.AnalyzeOrgPolicyGovernedContainersResponse + ) -> asset_service.AnalyzeOrgPolicyGovernedContainersResponse: """Post-rpc interceptor for analyze_org_policy_governed_containers DEPRECATED. Please use the `post_analyze_org_policy_governed_containers_with_metadata` @@ -462,7 +545,14 @@ def post_analyze_org_policy_governed_containers(self, response: asset_service.An """ return response - def post_analyze_org_policy_governed_containers_with_metadata(self, response: asset_service.AnalyzeOrgPolicyGovernedContainersResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.AnalyzeOrgPolicyGovernedContainersResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_analyze_org_policy_governed_containers_with_metadata( + self, + response: asset_service.AnalyzeOrgPolicyGovernedContainersResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.AnalyzeOrgPolicyGovernedContainersResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for analyze_org_policy_governed_containers Override in a subclass to read or manipulate the response or metadata after it @@ -477,7 +567,14 @@ def post_analyze_org_policy_governed_containers_with_metadata(self, response: as """ return response, metadata - def pre_batch_get_assets_history(self, request: asset_service.BatchGetAssetsHistoryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.BatchGetAssetsHistoryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_batch_get_assets_history( + self, + request: asset_service.BatchGetAssetsHistoryRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.BatchGetAssetsHistoryRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for batch_get_assets_history Override in a subclass to manipulate the request or metadata @@ -485,7 +582,9 @@ def pre_batch_get_assets_history(self, request: asset_service.BatchGetAssetsHist """ return request, metadata - def post_batch_get_assets_history(self, response: asset_service.BatchGetAssetsHistoryResponse) -> asset_service.BatchGetAssetsHistoryResponse: + def post_batch_get_assets_history( + self, response: asset_service.BatchGetAssetsHistoryResponse + ) -> asset_service.BatchGetAssetsHistoryResponse: """Post-rpc interceptor for batch_get_assets_history DEPRECATED. Please use the `post_batch_get_assets_history_with_metadata` @@ -498,7 +597,14 @@ def post_batch_get_assets_history(self, response: asset_service.BatchGetAssetsHi """ return response - def post_batch_get_assets_history_with_metadata(self, response: asset_service.BatchGetAssetsHistoryResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.BatchGetAssetsHistoryResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_batch_get_assets_history_with_metadata( + self, + response: asset_service.BatchGetAssetsHistoryResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.BatchGetAssetsHistoryResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for batch_get_assets_history Override in a subclass to read or manipulate the response or metadata after it @@ -513,7 +619,14 @@ def post_batch_get_assets_history_with_metadata(self, response: asset_service.Ba """ return response, metadata - def pre_batch_get_effective_iam_policies(self, request: asset_service.BatchGetEffectiveIamPoliciesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.BatchGetEffectiveIamPoliciesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_batch_get_effective_iam_policies( + self, + request: asset_service.BatchGetEffectiveIamPoliciesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.BatchGetEffectiveIamPoliciesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for batch_get_effective_iam_policies Override in a subclass to manipulate the request or metadata @@ -521,7 +634,9 @@ def pre_batch_get_effective_iam_policies(self, request: asset_service.BatchGetEf """ return request, metadata - def post_batch_get_effective_iam_policies(self, response: asset_service.BatchGetEffectiveIamPoliciesResponse) -> asset_service.BatchGetEffectiveIamPoliciesResponse: + def post_batch_get_effective_iam_policies( + self, response: asset_service.BatchGetEffectiveIamPoliciesResponse + ) -> asset_service.BatchGetEffectiveIamPoliciesResponse: """Post-rpc interceptor for batch_get_effective_iam_policies DEPRECATED. Please use the `post_batch_get_effective_iam_policies_with_metadata` @@ -534,7 +649,14 @@ def post_batch_get_effective_iam_policies(self, response: asset_service.BatchGet """ return response - def post_batch_get_effective_iam_policies_with_metadata(self, response: asset_service.BatchGetEffectiveIamPoliciesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.BatchGetEffectiveIamPoliciesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_batch_get_effective_iam_policies_with_metadata( + self, + response: asset_service.BatchGetEffectiveIamPoliciesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.BatchGetEffectiveIamPoliciesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for batch_get_effective_iam_policies Override in a subclass to read or manipulate the response or metadata after it @@ -549,7 +671,13 @@ def post_batch_get_effective_iam_policies_with_metadata(self, response: asset_se """ return response, metadata - def pre_create_feed(self, request: asset_service.CreateFeedRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.CreateFeedRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_create_feed( + self, + request: asset_service.CreateFeedRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.CreateFeedRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for create_feed Override in a subclass to manipulate the request or metadata @@ -570,7 +698,11 @@ def post_create_feed(self, response: asset_service.Feed) -> asset_service.Feed: """ return response - def post_create_feed_with_metadata(self, response: asset_service.Feed, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.Feed, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_create_feed_with_metadata( + self, + response: asset_service.Feed, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[asset_service.Feed, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for create_feed Override in a subclass to read or manipulate the response or metadata after it @@ -585,7 +717,13 @@ def post_create_feed_with_metadata(self, response: asset_service.Feed, metadata: """ return response, metadata - def pre_create_saved_query(self, request: asset_service.CreateSavedQueryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.CreateSavedQueryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_create_saved_query( + self, + request: asset_service.CreateSavedQueryRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.CreateSavedQueryRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for create_saved_query Override in a subclass to manipulate the request or metadata @@ -593,7 +731,9 @@ def pre_create_saved_query(self, request: asset_service.CreateSavedQueryRequest, """ return request, metadata - def post_create_saved_query(self, response: asset_service.SavedQuery) -> asset_service.SavedQuery: + def post_create_saved_query( + self, response: asset_service.SavedQuery + ) -> asset_service.SavedQuery: """Post-rpc interceptor for create_saved_query DEPRECATED. Please use the `post_create_saved_query_with_metadata` @@ -606,7 +746,11 @@ def post_create_saved_query(self, response: asset_service.SavedQuery) -> asset_s """ return response - def post_create_saved_query_with_metadata(self, response: asset_service.SavedQuery, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.SavedQuery, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_create_saved_query_with_metadata( + self, + response: asset_service.SavedQuery, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[asset_service.SavedQuery, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for create_saved_query Override in a subclass to read or manipulate the response or metadata after it @@ -621,7 +765,13 @@ def post_create_saved_query_with_metadata(self, response: asset_service.SavedQue """ return response, metadata - def pre_delete_feed(self, request: asset_service.DeleteFeedRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.DeleteFeedRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_delete_feed( + self, + request: asset_service.DeleteFeedRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.DeleteFeedRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for delete_feed Override in a subclass to manipulate the request or metadata @@ -629,7 +779,13 @@ def pre_delete_feed(self, request: asset_service.DeleteFeedRequest, metadata: Se """ return request, metadata - def pre_delete_saved_query(self, request: asset_service.DeleteSavedQueryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.DeleteSavedQueryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_delete_saved_query( + self, + request: asset_service.DeleteSavedQueryRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.DeleteSavedQueryRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for delete_saved_query Override in a subclass to manipulate the request or metadata @@ -637,7 +793,13 @@ def pre_delete_saved_query(self, request: asset_service.DeleteSavedQueryRequest, """ return request, metadata - def pre_export_assets(self, request: asset_service.ExportAssetsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.ExportAssetsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_export_assets( + self, + request: asset_service.ExportAssetsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.ExportAssetsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for export_assets Override in a subclass to manipulate the request or metadata @@ -645,7 +807,9 @@ def pre_export_assets(self, request: asset_service.ExportAssetsRequest, metadata """ return request, metadata - def post_export_assets(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_export_assets( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for export_assets DEPRECATED. Please use the `post_export_assets_with_metadata` @@ -658,7 +822,11 @@ def post_export_assets(self, response: operations_pb2.Operation) -> operations_p """ return response - def post_export_assets_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_export_assets_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for export_assets Override in a subclass to read or manipulate the response or metadata after it @@ -673,7 +841,11 @@ def post_export_assets_with_metadata(self, response: operations_pb2.Operation, m """ return response, metadata - def pre_get_feed(self, request: asset_service.GetFeedRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.GetFeedRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_get_feed( + self, + request: asset_service.GetFeedRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[asset_service.GetFeedRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_feed Override in a subclass to manipulate the request or metadata @@ -694,7 +866,11 @@ def post_get_feed(self, response: asset_service.Feed) -> asset_service.Feed: """ return response - def post_get_feed_with_metadata(self, response: asset_service.Feed, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.Feed, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_feed_with_metadata( + self, + response: asset_service.Feed, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[asset_service.Feed, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_feed Override in a subclass to read or manipulate the response or metadata after it @@ -709,7 +885,13 @@ def post_get_feed_with_metadata(self, response: asset_service.Feed, metadata: Se """ return response, metadata - def pre_get_saved_query(self, request: asset_service.GetSavedQueryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.GetSavedQueryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_get_saved_query( + self, + request: asset_service.GetSavedQueryRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.GetSavedQueryRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_saved_query Override in a subclass to manipulate the request or metadata @@ -717,7 +899,9 @@ def pre_get_saved_query(self, request: asset_service.GetSavedQueryRequest, metad """ return request, metadata - def post_get_saved_query(self, response: asset_service.SavedQuery) -> asset_service.SavedQuery: + def post_get_saved_query( + self, response: asset_service.SavedQuery + ) -> asset_service.SavedQuery: """Post-rpc interceptor for get_saved_query DEPRECATED. Please use the `post_get_saved_query_with_metadata` @@ -730,7 +914,11 @@ def post_get_saved_query(self, response: asset_service.SavedQuery) -> asset_serv """ return response - def post_get_saved_query_with_metadata(self, response: asset_service.SavedQuery, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.SavedQuery, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_saved_query_with_metadata( + self, + response: asset_service.SavedQuery, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[asset_service.SavedQuery, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_saved_query Override in a subclass to read or manipulate the response or metadata after it @@ -745,7 +933,13 @@ def post_get_saved_query_with_metadata(self, response: asset_service.SavedQuery, """ return response, metadata - def pre_list_assets(self, request: asset_service.ListAssetsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.ListAssetsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_assets( + self, + request: asset_service.ListAssetsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.ListAssetsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_assets Override in a subclass to manipulate the request or metadata @@ -753,7 +947,9 @@ def pre_list_assets(self, request: asset_service.ListAssetsRequest, metadata: Se """ return request, metadata - def post_list_assets(self, response: asset_service.ListAssetsResponse) -> asset_service.ListAssetsResponse: + def post_list_assets( + self, response: asset_service.ListAssetsResponse + ) -> asset_service.ListAssetsResponse: """Post-rpc interceptor for list_assets DEPRECATED. Please use the `post_list_assets_with_metadata` @@ -766,7 +962,13 @@ def post_list_assets(self, response: asset_service.ListAssetsResponse) -> asset_ """ return response - def post_list_assets_with_metadata(self, response: asset_service.ListAssetsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.ListAssetsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_assets_with_metadata( + self, + response: asset_service.ListAssetsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.ListAssetsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for list_assets Override in a subclass to read or manipulate the response or metadata after it @@ -781,7 +983,11 @@ def post_list_assets_with_metadata(self, response: asset_service.ListAssetsRespo """ return response, metadata - def pre_list_feeds(self, request: asset_service.ListFeedsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.ListFeedsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_feeds( + self, + request: asset_service.ListFeedsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[asset_service.ListFeedsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for list_feeds Override in a subclass to manipulate the request or metadata @@ -789,7 +995,9 @@ def pre_list_feeds(self, request: asset_service.ListFeedsRequest, metadata: Sequ """ return request, metadata - def post_list_feeds(self, response: asset_service.ListFeedsResponse) -> asset_service.ListFeedsResponse: + def post_list_feeds( + self, response: asset_service.ListFeedsResponse + ) -> asset_service.ListFeedsResponse: """Post-rpc interceptor for list_feeds DEPRECATED. Please use the `post_list_feeds_with_metadata` @@ -802,7 +1010,13 @@ def post_list_feeds(self, response: asset_service.ListFeedsResponse) -> asset_se """ return response - def post_list_feeds_with_metadata(self, response: asset_service.ListFeedsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.ListFeedsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_feeds_with_metadata( + self, + response: asset_service.ListFeedsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.ListFeedsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for list_feeds Override in a subclass to read or manipulate the response or metadata after it @@ -817,7 +1031,13 @@ def post_list_feeds_with_metadata(self, response: asset_service.ListFeedsRespons """ return response, metadata - def pre_list_saved_queries(self, request: asset_service.ListSavedQueriesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.ListSavedQueriesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_saved_queries( + self, + request: asset_service.ListSavedQueriesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.ListSavedQueriesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_saved_queries Override in a subclass to manipulate the request or metadata @@ -825,7 +1045,9 @@ def pre_list_saved_queries(self, request: asset_service.ListSavedQueriesRequest, """ return request, metadata - def post_list_saved_queries(self, response: asset_service.ListSavedQueriesResponse) -> asset_service.ListSavedQueriesResponse: + def post_list_saved_queries( + self, response: asset_service.ListSavedQueriesResponse + ) -> asset_service.ListSavedQueriesResponse: """Post-rpc interceptor for list_saved_queries DEPRECATED. Please use the `post_list_saved_queries_with_metadata` @@ -838,7 +1060,13 @@ def post_list_saved_queries(self, response: asset_service.ListSavedQueriesRespon """ return response - def post_list_saved_queries_with_metadata(self, response: asset_service.ListSavedQueriesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.ListSavedQueriesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_saved_queries_with_metadata( + self, + response: asset_service.ListSavedQueriesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.ListSavedQueriesResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for list_saved_queries Override in a subclass to read or manipulate the response or metadata after it @@ -853,7 +1081,13 @@ def post_list_saved_queries_with_metadata(self, response: asset_service.ListSave """ return response, metadata - def pre_query_assets(self, request: asset_service.QueryAssetsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.QueryAssetsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_query_assets( + self, + request: asset_service.QueryAssetsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.QueryAssetsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for query_assets Override in a subclass to manipulate the request or metadata @@ -861,7 +1095,9 @@ def pre_query_assets(self, request: asset_service.QueryAssetsRequest, metadata: """ return request, metadata - def post_query_assets(self, response: asset_service.QueryAssetsResponse) -> asset_service.QueryAssetsResponse: + def post_query_assets( + self, response: asset_service.QueryAssetsResponse + ) -> asset_service.QueryAssetsResponse: """Post-rpc interceptor for query_assets DEPRECATED. Please use the `post_query_assets_with_metadata` @@ -874,7 +1110,13 @@ def post_query_assets(self, response: asset_service.QueryAssetsResponse) -> asse """ return response - def post_query_assets_with_metadata(self, response: asset_service.QueryAssetsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.QueryAssetsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_query_assets_with_metadata( + self, + response: asset_service.QueryAssetsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.QueryAssetsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for query_assets Override in a subclass to read or manipulate the response or metadata after it @@ -889,7 +1131,14 @@ def post_query_assets_with_metadata(self, response: asset_service.QueryAssetsRes """ return response, metadata - def pre_search_all_iam_policies(self, request: asset_service.SearchAllIamPoliciesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.SearchAllIamPoliciesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_search_all_iam_policies( + self, + request: asset_service.SearchAllIamPoliciesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.SearchAllIamPoliciesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for search_all_iam_policies Override in a subclass to manipulate the request or metadata @@ -897,7 +1146,9 @@ def pre_search_all_iam_policies(self, request: asset_service.SearchAllIamPolicie """ return request, metadata - def post_search_all_iam_policies(self, response: asset_service.SearchAllIamPoliciesResponse) -> asset_service.SearchAllIamPoliciesResponse: + def post_search_all_iam_policies( + self, response: asset_service.SearchAllIamPoliciesResponse + ) -> asset_service.SearchAllIamPoliciesResponse: """Post-rpc interceptor for search_all_iam_policies DEPRECATED. Please use the `post_search_all_iam_policies_with_metadata` @@ -910,7 +1161,14 @@ def post_search_all_iam_policies(self, response: asset_service.SearchAllIamPolic """ return response - def post_search_all_iam_policies_with_metadata(self, response: asset_service.SearchAllIamPoliciesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.SearchAllIamPoliciesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_search_all_iam_policies_with_metadata( + self, + response: asset_service.SearchAllIamPoliciesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.SearchAllIamPoliciesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for search_all_iam_policies Override in a subclass to read or manipulate the response or metadata after it @@ -925,7 +1183,13 @@ def post_search_all_iam_policies_with_metadata(self, response: asset_service.Sea """ return response, metadata - def pre_search_all_resources(self, request: asset_service.SearchAllResourcesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.SearchAllResourcesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_search_all_resources( + self, + request: asset_service.SearchAllResourcesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.SearchAllResourcesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for search_all_resources Override in a subclass to manipulate the request or metadata @@ -933,7 +1197,9 @@ def pre_search_all_resources(self, request: asset_service.SearchAllResourcesRequ """ return request, metadata - def post_search_all_resources(self, response: asset_service.SearchAllResourcesResponse) -> asset_service.SearchAllResourcesResponse: + def post_search_all_resources( + self, response: asset_service.SearchAllResourcesResponse + ) -> asset_service.SearchAllResourcesResponse: """Post-rpc interceptor for search_all_resources DEPRECATED. Please use the `post_search_all_resources_with_metadata` @@ -946,7 +1212,14 @@ def post_search_all_resources(self, response: asset_service.SearchAllResourcesRe """ return response - def post_search_all_resources_with_metadata(self, response: asset_service.SearchAllResourcesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.SearchAllResourcesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_search_all_resources_with_metadata( + self, + response: asset_service.SearchAllResourcesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.SearchAllResourcesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for search_all_resources Override in a subclass to read or manipulate the response or metadata after it @@ -961,7 +1234,13 @@ def post_search_all_resources_with_metadata(self, response: asset_service.Search """ return response, metadata - def pre_update_feed(self, request: asset_service.UpdateFeedRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.UpdateFeedRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_update_feed( + self, + request: asset_service.UpdateFeedRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.UpdateFeedRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for update_feed Override in a subclass to manipulate the request or metadata @@ -982,7 +1261,11 @@ def post_update_feed(self, response: asset_service.Feed) -> asset_service.Feed: """ return response - def post_update_feed_with_metadata(self, response: asset_service.Feed, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.Feed, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_update_feed_with_metadata( + self, + response: asset_service.Feed, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[asset_service.Feed, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for update_feed Override in a subclass to read or manipulate the response or metadata after it @@ -997,7 +1280,13 @@ def post_update_feed_with_metadata(self, response: asset_service.Feed, metadata: """ return response, metadata - def pre_update_saved_query(self, request: asset_service.UpdateSavedQueryRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.UpdateSavedQueryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_update_saved_query( + self, + request: asset_service.UpdateSavedQueryRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + asset_service.UpdateSavedQueryRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for update_saved_query Override in a subclass to manipulate the request or metadata @@ -1005,7 +1294,9 @@ def pre_update_saved_query(self, request: asset_service.UpdateSavedQueryRequest, """ return request, metadata - def post_update_saved_query(self, response: asset_service.SavedQuery) -> asset_service.SavedQuery: + def post_update_saved_query( + self, response: asset_service.SavedQuery + ) -> asset_service.SavedQuery: """Post-rpc interceptor for update_saved_query DEPRECATED. Please use the `post_update_saved_query_with_metadata` @@ -1018,7 +1309,11 @@ def post_update_saved_query(self, response: asset_service.SavedQuery) -> asset_s """ return response - def post_update_saved_query_with_metadata(self, response: asset_service.SavedQuery, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[asset_service.SavedQuery, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_update_saved_query_with_metadata( + self, + response: asset_service.SavedQuery, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[asset_service.SavedQuery, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for update_saved_query Override in a subclass to read or manipulate the response or metadata after it @@ -1034,8 +1329,12 @@ def post_update_saved_query_with_metadata(self, response: asset_service.SavedQue return response, metadata def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_operation Override in a subclass to manipulate the request or metadata @@ -1074,62 +1373,63 @@ class AssetServiceRestTransport(_BaseAssetServiceRestTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__(self, *, - host: str = 'cloudasset.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[AssetServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: + def __init__( + self, + *, + host: str = "cloudasset.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[AssetServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. - NOTE: This REST transport functionality is currently in a beta - state (preview). We welcome your feedback via a GitHub issue in - this library's repository. Thank you! - - Args: - host (Optional[str]): - The hostname to connect to (default: 'cloudasset.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. This argument will be - removed in the next major version of this library. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - interceptor (Optional[AssetServiceRestInterceptor]): Interceptor used - to manipulate requests, request metadata, and responses. - api_audience (Optional[str]): The intended audience for the API calls - to the service that will be set when using certain 3rd party - authentication flows. Audience is typically a resource identifier. - If not set, the host value will be used as a default. + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudasset.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[AssetServiceRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. """ # Run the base constructor # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. @@ -1141,10 +1441,11 @@ def __init__(self, *, client_info=client_info, always_use_jwt_access=always_use_jwt_access, url_scheme=url_scheme, - api_audience=api_audience + api_audience=api_audience, ) self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) + self._credentials, default_host=self.DEFAULT_HOST + ) self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None if client_cert_source_for_mtls: self._session.configure_mtls_channel(client_cert_source_for_mtls) @@ -1161,28 +1462,33 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Only create a new client if we do not already have one. if self._operations_client is None: http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.GetOperation': [ + "google.longrunning.Operations.GetOperation": [ { - 'method': 'get', - 'uri': '/v1/{name=*/*/operations/*/**}', + "method": "get", + "uri": "/v1/{name=*/*/operations/*/**}", }, ], } rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) # Return the client from cache. return self._operations_client - class _AnalyzeIamPolicy(_BaseAssetServiceRestTransport._BaseAnalyzeIamPolicy, AssetServiceRestStub): + class _AnalyzeIamPolicy( + _BaseAssetServiceRestTransport._BaseAnalyzeIamPolicy, AssetServiceRestStub + ): def __hash__(self): return hash("AssetServiceRestTransport.AnalyzeIamPolicy") @@ -1194,26 +1500,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: asset_service.AnalyzeIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> asset_service.AnalyzeIamPolicyResponse: + def __call__( + self, + request: asset_service.AnalyzeIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.AnalyzeIamPolicyResponse: r"""Call the analyze iam policy method over HTTP. Args: @@ -1235,30 +1543,42 @@ def __call__(self, """ - http_options = _BaseAssetServiceRestTransport._BaseAnalyzeIamPolicy._get_http_options() + http_options = ( + _BaseAssetServiceRestTransport._BaseAnalyzeIamPolicy._get_http_options() + ) - request, metadata = self._interceptor.pre_analyze_iam_policy(request, metadata) - transcoded_request = _BaseAssetServiceRestTransport._BaseAnalyzeIamPolicy._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_analyze_iam_policy( + request, metadata + ) + transcoded_request = _BaseAssetServiceRestTransport._BaseAnalyzeIamPolicy._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAssetServiceRestTransport._BaseAnalyzeIamPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAssetServiceRestTransport._BaseAnalyzeIamPolicy._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.asset_v1.AssetServiceClient.AnalyzeIamPolicy", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "AnalyzeIamPolicy", "httpRequest": http_request, @@ -1267,7 +1587,14 @@ def __call__(self, ) # Send the request - response = AssetServiceRestTransport._AnalyzeIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AssetServiceRestTransport._AnalyzeIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1282,20 +1609,26 @@ def __call__(self, resp = self._interceptor.post_analyze_iam_policy(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_analyze_iam_policy_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_analyze_iam_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = asset_service.AnalyzeIamPolicyResponse.to_json(response) + response_payload = asset_service.AnalyzeIamPolicyResponse.to_json( + response + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.asset_v1.AssetServiceClient.analyze_iam_policy", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "AnalyzeIamPolicy", "metadata": http_response["headers"], @@ -1304,7 +1637,10 @@ def __call__(self, ) return resp - class _AnalyzeIamPolicyLongrunning(_BaseAssetServiceRestTransport._BaseAnalyzeIamPolicyLongrunning, AssetServiceRestStub): + class _AnalyzeIamPolicyLongrunning( + _BaseAssetServiceRestTransport._BaseAnalyzeIamPolicyLongrunning, + AssetServiceRestStub, + ): def __hash__(self): return hash("AssetServiceRestTransport.AnalyzeIamPolicyLongrunning") @@ -1316,76 +1652,92 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: asset_service.AnalyzeIamPolicyLongrunningRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: asset_service.AnalyzeIamPolicyLongrunningRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the analyze iam policy - longrunning method over HTTP. - - Args: - request (~.asset_service.AnalyzeIamPolicyLongrunningRequest): - The request object. A request message for - [AssetService.AnalyzeIamPolicyLongrunning][google.cloud.asset.v1.AssetService.AnalyzeIamPolicyLongrunning]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. + longrunning method over HTTP. + + Args: + request (~.asset_service.AnalyzeIamPolicyLongrunningRequest): + The request object. A request message for + [AssetService.AnalyzeIamPolicyLongrunning][google.cloud.asset.v1.AssetService.AnalyzeIamPolicyLongrunning]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = _BaseAssetServiceRestTransport._BaseAnalyzeIamPolicyLongrunning._get_http_options() + http_options = ( + _BaseAssetServiceRestTransport._BaseAnalyzeIamPolicyLongrunning._get_http_options() + ) - request, metadata = self._interceptor.pre_analyze_iam_policy_longrunning(request, metadata) - transcoded_request = _BaseAssetServiceRestTransport._BaseAnalyzeIamPolicyLongrunning._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_analyze_iam_policy_longrunning( + request, metadata + ) + transcoded_request = _BaseAssetServiceRestTransport._BaseAnalyzeIamPolicyLongrunning._get_transcoded_request( + http_options, request + ) - body = _BaseAssetServiceRestTransport._BaseAnalyzeIamPolicyLongrunning._get_request_body_json(transcoded_request) + body = _BaseAssetServiceRestTransport._BaseAnalyzeIamPolicyLongrunning._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseAssetServiceRestTransport._BaseAnalyzeIamPolicyLongrunning._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAssetServiceRestTransport._BaseAnalyzeIamPolicyLongrunning._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.asset_v1.AssetServiceClient.AnalyzeIamPolicyLongrunning", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "AnalyzeIamPolicyLongrunning", "httpRequest": http_request, @@ -1394,7 +1746,17 @@ def __call__(self, ) # Send the request - response = AssetServiceRestTransport._AnalyzeIamPolicyLongrunning._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = ( + AssetServiceRestTransport._AnalyzeIamPolicyLongrunning._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1407,20 +1769,27 @@ def __call__(self, resp = self._interceptor.post_analyze_iam_policy_longrunning(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_analyze_iam_policy_longrunning_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + ( + resp, + _, + ) = self._interceptor.post_analyze_iam_policy_longrunning_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.asset_v1.AssetServiceClient.analyze_iam_policy_longrunning", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "AnalyzeIamPolicyLongrunning", "metadata": http_response["headers"], @@ -1429,7 +1798,9 @@ def __call__(self, ) return resp - class _AnalyzeMove(_BaseAssetServiceRestTransport._BaseAnalyzeMove, AssetServiceRestStub): + class _AnalyzeMove( + _BaseAssetServiceRestTransport._BaseAnalyzeMove, AssetServiceRestStub + ): def __hash__(self): return hash("AssetServiceRestTransport.AnalyzeMove") @@ -1441,26 +1812,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: asset_service.AnalyzeMoveRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> asset_service.AnalyzeMoveResponse: + def __call__( + self, + request: asset_service.AnalyzeMoveRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.AnalyzeMoveResponse: r"""Call the analyze move method over HTTP. Args: @@ -1482,30 +1855,44 @@ def __call__(self, """ - http_options = _BaseAssetServiceRestTransport._BaseAnalyzeMove._get_http_options() + http_options = ( + _BaseAssetServiceRestTransport._BaseAnalyzeMove._get_http_options() + ) request, metadata = self._interceptor.pre_analyze_move(request, metadata) - transcoded_request = _BaseAssetServiceRestTransport._BaseAnalyzeMove._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseAssetServiceRestTransport._BaseAnalyzeMove._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseAssetServiceRestTransport._BaseAnalyzeMove._get_query_params_json(transcoded_request) + query_params = ( + _BaseAssetServiceRestTransport._BaseAnalyzeMove._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.asset_v1.AssetServiceClient.AnalyzeMove", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "AnalyzeMove", "httpRequest": http_request, @@ -1514,7 +1901,14 @@ def __call__(self, ) # Send the request - response = AssetServiceRestTransport._AnalyzeMove._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AssetServiceRestTransport._AnalyzeMove._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1529,20 +1923,26 @@ def __call__(self, resp = self._interceptor.post_analyze_move(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_analyze_move_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_analyze_move_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = asset_service.AnalyzeMoveResponse.to_json(response) + response_payload = asset_service.AnalyzeMoveResponse.to_json( + response + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.asset_v1.AssetServiceClient.analyze_move", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "AnalyzeMove", "metadata": http_response["headers"], @@ -1551,7 +1951,9 @@ def __call__(self, ) return resp - class _AnalyzeOrgPolicies(_BaseAssetServiceRestTransport._BaseAnalyzeOrgPolicies, AssetServiceRestStub): + class _AnalyzeOrgPolicies( + _BaseAssetServiceRestTransport._BaseAnalyzeOrgPolicies, AssetServiceRestStub + ): def __hash__(self): return hash("AssetServiceRestTransport.AnalyzeOrgPolicies") @@ -1563,26 +1965,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: asset_service.AnalyzeOrgPoliciesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> asset_service.AnalyzeOrgPoliciesResponse: + def __call__( + self, + request: asset_service.AnalyzeOrgPoliciesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.AnalyzeOrgPoliciesResponse: r"""Call the analyze org policies method over HTTP. Args: @@ -1604,30 +2008,42 @@ def __call__(self, """ - http_options = _BaseAssetServiceRestTransport._BaseAnalyzeOrgPolicies._get_http_options() + http_options = ( + _BaseAssetServiceRestTransport._BaseAnalyzeOrgPolicies._get_http_options() + ) - request, metadata = self._interceptor.pre_analyze_org_policies(request, metadata) - transcoded_request = _BaseAssetServiceRestTransport._BaseAnalyzeOrgPolicies._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_analyze_org_policies( + request, metadata + ) + transcoded_request = _BaseAssetServiceRestTransport._BaseAnalyzeOrgPolicies._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAssetServiceRestTransport._BaseAnalyzeOrgPolicies._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAssetServiceRestTransport._BaseAnalyzeOrgPolicies._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.asset_v1.AssetServiceClient.AnalyzeOrgPolicies", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "AnalyzeOrgPolicies", "httpRequest": http_request, @@ -1636,7 +2052,14 @@ def __call__(self, ) # Send the request - response = AssetServiceRestTransport._AnalyzeOrgPolicies._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AssetServiceRestTransport._AnalyzeOrgPolicies._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1651,20 +2074,26 @@ def __call__(self, resp = self._interceptor.post_analyze_org_policies(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_analyze_org_policies_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_analyze_org_policies_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = asset_service.AnalyzeOrgPoliciesResponse.to_json(response) + response_payload = asset_service.AnalyzeOrgPoliciesResponse.to_json( + response + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.asset_v1.AssetServiceClient.analyze_org_policies", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "AnalyzeOrgPolicies", "metadata": http_response["headers"], @@ -1673,7 +2102,10 @@ def __call__(self, ) return resp - class _AnalyzeOrgPolicyGovernedAssets(_BaseAssetServiceRestTransport._BaseAnalyzeOrgPolicyGovernedAssets, AssetServiceRestStub): + class _AnalyzeOrgPolicyGovernedAssets( + _BaseAssetServiceRestTransport._BaseAnalyzeOrgPolicyGovernedAssets, + AssetServiceRestStub, + ): def __hash__(self): return hash("AssetServiceRestTransport.AnalyzeOrgPolicyGovernedAssets") @@ -1685,72 +2117,89 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> asset_service.AnalyzeOrgPolicyGovernedAssetsResponse: + def __call__( + self, + request: asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.AnalyzeOrgPolicyGovernedAssetsResponse: r"""Call the analyze org policy - governed assets method over HTTP. - - Args: - request (~.asset_service.AnalyzeOrgPolicyGovernedAssetsRequest): - The request object. A request message for - [AssetService.AnalyzeOrgPolicyGovernedAssets][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedAssets]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.asset_service.AnalyzeOrgPolicyGovernedAssetsResponse: - The response message for - [AssetService.AnalyzeOrgPolicyGovernedAssets][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedAssets]. + governed assets method over HTTP. + + Args: + request (~.asset_service.AnalyzeOrgPolicyGovernedAssetsRequest): + The request object. A request message for + [AssetService.AnalyzeOrgPolicyGovernedAssets][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedAssets]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.asset_service.AnalyzeOrgPolicyGovernedAssetsResponse: + The response message for + [AssetService.AnalyzeOrgPolicyGovernedAssets][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedAssets]. """ - http_options = _BaseAssetServiceRestTransport._BaseAnalyzeOrgPolicyGovernedAssets._get_http_options() + http_options = ( + _BaseAssetServiceRestTransport._BaseAnalyzeOrgPolicyGovernedAssets._get_http_options() + ) - request, metadata = self._interceptor.pre_analyze_org_policy_governed_assets(request, metadata) - transcoded_request = _BaseAssetServiceRestTransport._BaseAnalyzeOrgPolicyGovernedAssets._get_transcoded_request(http_options, request) + ( + request, + metadata, + ) = self._interceptor.pre_analyze_org_policy_governed_assets( + request, metadata + ) + transcoded_request = _BaseAssetServiceRestTransport._BaseAnalyzeOrgPolicyGovernedAssets._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAssetServiceRestTransport._BaseAnalyzeOrgPolicyGovernedAssets._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAssetServiceRestTransport._BaseAnalyzeOrgPolicyGovernedAssets._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.asset_v1.AssetServiceClient.AnalyzeOrgPolicyGovernedAssets", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "AnalyzeOrgPolicyGovernedAssets", "httpRequest": http_request, @@ -1759,7 +2208,16 @@ def __call__(self, ) # Send the request - response = AssetServiceRestTransport._AnalyzeOrgPolicyGovernedAssets._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = ( + AssetServiceRestTransport._AnalyzeOrgPolicyGovernedAssets._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1774,20 +2232,31 @@ def __call__(self, resp = self._interceptor.post_analyze_org_policy_governed_assets(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_analyze_org_policy_governed_assets_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + ( + resp, + _, + ) = self._interceptor.post_analyze_org_policy_governed_assets_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.to_json(response) + response_payload = ( + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.to_json( + response + ) + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.asset_v1.AssetServiceClient.analyze_org_policy_governed_assets", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "AnalyzeOrgPolicyGovernedAssets", "metadata": http_response["headers"], @@ -1796,7 +2265,10 @@ def __call__(self, ) return resp - class _AnalyzeOrgPolicyGovernedContainers(_BaseAssetServiceRestTransport._BaseAnalyzeOrgPolicyGovernedContainers, AssetServiceRestStub): + class _AnalyzeOrgPolicyGovernedContainers( + _BaseAssetServiceRestTransport._BaseAnalyzeOrgPolicyGovernedContainers, + AssetServiceRestStub, + ): def __hash__(self): return hash("AssetServiceRestTransport.AnalyzeOrgPolicyGovernedContainers") @@ -1808,72 +2280,89 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: asset_service.AnalyzeOrgPolicyGovernedContainersRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> asset_service.AnalyzeOrgPolicyGovernedContainersResponse: + def __call__( + self, + request: asset_service.AnalyzeOrgPolicyGovernedContainersRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.AnalyzeOrgPolicyGovernedContainersResponse: r"""Call the analyze org policy - governed containers method over HTTP. - - Args: - request (~.asset_service.AnalyzeOrgPolicyGovernedContainersRequest): - The request object. A request message for - [AssetService.AnalyzeOrgPolicyGovernedContainers][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedContainers]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.asset_service.AnalyzeOrgPolicyGovernedContainersResponse: - The response message for - [AssetService.AnalyzeOrgPolicyGovernedContainers][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedContainers]. + governed containers method over HTTP. + + Args: + request (~.asset_service.AnalyzeOrgPolicyGovernedContainersRequest): + The request object. A request message for + [AssetService.AnalyzeOrgPolicyGovernedContainers][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedContainers]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.asset_service.AnalyzeOrgPolicyGovernedContainersResponse: + The response message for + [AssetService.AnalyzeOrgPolicyGovernedContainers][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedContainers]. """ - http_options = _BaseAssetServiceRestTransport._BaseAnalyzeOrgPolicyGovernedContainers._get_http_options() + http_options = ( + _BaseAssetServiceRestTransport._BaseAnalyzeOrgPolicyGovernedContainers._get_http_options() + ) - request, metadata = self._interceptor.pre_analyze_org_policy_governed_containers(request, metadata) - transcoded_request = _BaseAssetServiceRestTransport._BaseAnalyzeOrgPolicyGovernedContainers._get_transcoded_request(http_options, request) + ( + request, + metadata, + ) = self._interceptor.pre_analyze_org_policy_governed_containers( + request, metadata + ) + transcoded_request = _BaseAssetServiceRestTransport._BaseAnalyzeOrgPolicyGovernedContainers._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAssetServiceRestTransport._BaseAnalyzeOrgPolicyGovernedContainers._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAssetServiceRestTransport._BaseAnalyzeOrgPolicyGovernedContainers._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.asset_v1.AssetServiceClient.AnalyzeOrgPolicyGovernedContainers", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "AnalyzeOrgPolicyGovernedContainers", "httpRequest": http_request, @@ -1882,7 +2371,14 @@ def __call__(self, ) # Send the request - response = AssetServiceRestTransport._AnalyzeOrgPolicyGovernedContainers._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AssetServiceRestTransport._AnalyzeOrgPolicyGovernedContainers._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1897,20 +2393,29 @@ def __call__(self, resp = self._interceptor.post_analyze_org_policy_governed_containers(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_analyze_org_policy_governed_containers_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + ( + resp, + _, + ) = self._interceptor.post_analyze_org_policy_governed_containers_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = asset_service.AnalyzeOrgPolicyGovernedContainersResponse.to_json(response) + response_payload = asset_service.AnalyzeOrgPolicyGovernedContainersResponse.to_json( + response + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.asset_v1.AssetServiceClient.analyze_org_policy_governed_containers", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "AnalyzeOrgPolicyGovernedContainers", "metadata": http_response["headers"], @@ -1919,7 +2424,9 @@ def __call__(self, ) return resp - class _BatchGetAssetsHistory(_BaseAssetServiceRestTransport._BaseBatchGetAssetsHistory, AssetServiceRestStub): + class _BatchGetAssetsHistory( + _BaseAssetServiceRestTransport._BaseBatchGetAssetsHistory, AssetServiceRestStub + ): def __hash__(self): return hash("AssetServiceRestTransport.BatchGetAssetsHistory") @@ -1931,26 +2438,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: asset_service.BatchGetAssetsHistoryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> asset_service.BatchGetAssetsHistoryResponse: + def __call__( + self, + request: asset_service.BatchGetAssetsHistoryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.BatchGetAssetsHistoryResponse: r"""Call the batch get assets history method over HTTP. Args: @@ -1969,30 +2478,42 @@ def __call__(self, Batch get assets history response. """ - http_options = _BaseAssetServiceRestTransport._BaseBatchGetAssetsHistory._get_http_options() + http_options = ( + _BaseAssetServiceRestTransport._BaseBatchGetAssetsHistory._get_http_options() + ) - request, metadata = self._interceptor.pre_batch_get_assets_history(request, metadata) - transcoded_request = _BaseAssetServiceRestTransport._BaseBatchGetAssetsHistory._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_batch_get_assets_history( + request, metadata + ) + transcoded_request = _BaseAssetServiceRestTransport._BaseBatchGetAssetsHistory._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAssetServiceRestTransport._BaseBatchGetAssetsHistory._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAssetServiceRestTransport._BaseBatchGetAssetsHistory._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.asset_v1.AssetServiceClient.BatchGetAssetsHistory", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "BatchGetAssetsHistory", "httpRequest": http_request, @@ -2001,7 +2522,14 @@ def __call__(self, ) # Send the request - response = AssetServiceRestTransport._BatchGetAssetsHistory._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AssetServiceRestTransport._BatchGetAssetsHistory._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2016,20 +2544,26 @@ def __call__(self, resp = self._interceptor.post_batch_get_assets_history(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_batch_get_assets_history_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_batch_get_assets_history_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = asset_service.BatchGetAssetsHistoryResponse.to_json(response) + response_payload = ( + asset_service.BatchGetAssetsHistoryResponse.to_json(response) + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.asset_v1.AssetServiceClient.batch_get_assets_history", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "BatchGetAssetsHistory", "metadata": http_response["headers"], @@ -2038,7 +2572,10 @@ def __call__(self, ) return resp - class _BatchGetEffectiveIamPolicies(_BaseAssetServiceRestTransport._BaseBatchGetEffectiveIamPolicies, AssetServiceRestStub): + class _BatchGetEffectiveIamPolicies( + _BaseAssetServiceRestTransport._BaseBatchGetEffectiveIamPolicies, + AssetServiceRestStub, + ): def __hash__(self): return hash("AssetServiceRestTransport.BatchGetEffectiveIamPolicies") @@ -2050,72 +2587,86 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: asset_service.BatchGetEffectiveIamPoliciesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> asset_service.BatchGetEffectiveIamPoliciesResponse: + def __call__( + self, + request: asset_service.BatchGetEffectiveIamPoliciesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.BatchGetEffectiveIamPoliciesResponse: r"""Call the batch get effective iam - policies method over HTTP. - - Args: - request (~.asset_service.BatchGetEffectiveIamPoliciesRequest): - The request object. A request message for - [AssetService.BatchGetEffectiveIamPolicies][google.cloud.asset.v1.AssetService.BatchGetEffectiveIamPolicies]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.asset_service.BatchGetEffectiveIamPoliciesResponse: - A response message for - [AssetService.BatchGetEffectiveIamPolicies][google.cloud.asset.v1.AssetService.BatchGetEffectiveIamPolicies]. + policies method over HTTP. + + Args: + request (~.asset_service.BatchGetEffectiveIamPoliciesRequest): + The request object. A request message for + [AssetService.BatchGetEffectiveIamPolicies][google.cloud.asset.v1.AssetService.BatchGetEffectiveIamPolicies]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.asset_service.BatchGetEffectiveIamPoliciesResponse: + A response message for + [AssetService.BatchGetEffectiveIamPolicies][google.cloud.asset.v1.AssetService.BatchGetEffectiveIamPolicies]. """ - http_options = _BaseAssetServiceRestTransport._BaseBatchGetEffectiveIamPolicies._get_http_options() + http_options = ( + _BaseAssetServiceRestTransport._BaseBatchGetEffectiveIamPolicies._get_http_options() + ) - request, metadata = self._interceptor.pre_batch_get_effective_iam_policies(request, metadata) - transcoded_request = _BaseAssetServiceRestTransport._BaseBatchGetEffectiveIamPolicies._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_batch_get_effective_iam_policies( + request, metadata + ) + transcoded_request = _BaseAssetServiceRestTransport._BaseBatchGetEffectiveIamPolicies._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAssetServiceRestTransport._BaseBatchGetEffectiveIamPolicies._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAssetServiceRestTransport._BaseBatchGetEffectiveIamPolicies._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.asset_v1.AssetServiceClient.BatchGetEffectiveIamPolicies", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "BatchGetEffectiveIamPolicies", "httpRequest": http_request, @@ -2124,7 +2675,16 @@ def __call__(self, ) # Send the request - response = AssetServiceRestTransport._BatchGetEffectiveIamPolicies._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = ( + AssetServiceRestTransport._BatchGetEffectiveIamPolicies._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2139,20 +2699,31 @@ def __call__(self, resp = self._interceptor.post_batch_get_effective_iam_policies(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_batch_get_effective_iam_policies_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + ( + resp, + _, + ) = self._interceptor.post_batch_get_effective_iam_policies_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = asset_service.BatchGetEffectiveIamPoliciesResponse.to_json(response) + response_payload = ( + asset_service.BatchGetEffectiveIamPoliciesResponse.to_json( + response + ) + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.asset_v1.AssetServiceClient.batch_get_effective_iam_policies", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "BatchGetEffectiveIamPolicies", "metadata": http_response["headers"], @@ -2161,7 +2732,9 @@ def __call__(self, ) return resp - class _CreateFeed(_BaseAssetServiceRestTransport._BaseCreateFeed, AssetServiceRestStub): + class _CreateFeed( + _BaseAssetServiceRestTransport._BaseCreateFeed, AssetServiceRestStub + ): def __hash__(self): return hash("AssetServiceRestTransport.CreateFeed") @@ -2173,27 +2746,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: asset_service.CreateFeedRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> asset_service.Feed: + def __call__( + self, + request: asset_service.CreateFeedRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.Feed: r"""Call the create feed method over HTTP. Args: @@ -2220,32 +2795,50 @@ def __call__(self, """ - http_options = _BaseAssetServiceRestTransport._BaseCreateFeed._get_http_options() + http_options = ( + _BaseAssetServiceRestTransport._BaseCreateFeed._get_http_options() + ) request, metadata = self._interceptor.pre_create_feed(request, metadata) - transcoded_request = _BaseAssetServiceRestTransport._BaseCreateFeed._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseAssetServiceRestTransport._BaseCreateFeed._get_transcoded_request( + http_options, request + ) + ) - body = _BaseAssetServiceRestTransport._BaseCreateFeed._get_request_body_json(transcoded_request) + body = ( + _BaseAssetServiceRestTransport._BaseCreateFeed._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = _BaseAssetServiceRestTransport._BaseCreateFeed._get_query_params_json(transcoded_request) + query_params = ( + _BaseAssetServiceRestTransport._BaseCreateFeed._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.asset_v1.AssetServiceClient.CreateFeed", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "CreateFeed", "httpRequest": http_request, @@ -2254,7 +2847,15 @@ def __call__(self, ) # Send the request - response = AssetServiceRestTransport._CreateFeed._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = AssetServiceRestTransport._CreateFeed._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2269,20 +2870,24 @@ def __call__(self, resp = self._interceptor.post_create_feed(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_feed_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_create_feed_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = asset_service.Feed.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.asset_v1.AssetServiceClient.create_feed", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "CreateFeed", "metadata": http_response["headers"], @@ -2291,7 +2896,9 @@ def __call__(self, ) return resp - class _CreateSavedQuery(_BaseAssetServiceRestTransport._BaseCreateSavedQuery, AssetServiceRestStub): + class _CreateSavedQuery( + _BaseAssetServiceRestTransport._BaseCreateSavedQuery, AssetServiceRestStub + ): def __hash__(self): return hash("AssetServiceRestTransport.CreateSavedQuery") @@ -2303,27 +2910,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: asset_service.CreateSavedQueryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> asset_service.SavedQuery: + def __call__( + self, + request: asset_service.CreateSavedQueryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.SavedQuery: r"""Call the create saved query method over HTTP. Args: @@ -2344,32 +2953,46 @@ def __call__(self, """ - http_options = _BaseAssetServiceRestTransport._BaseCreateSavedQuery._get_http_options() + http_options = ( + _BaseAssetServiceRestTransport._BaseCreateSavedQuery._get_http_options() + ) - request, metadata = self._interceptor.pre_create_saved_query(request, metadata) - transcoded_request = _BaseAssetServiceRestTransport._BaseCreateSavedQuery._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_create_saved_query( + request, metadata + ) + transcoded_request = _BaseAssetServiceRestTransport._BaseCreateSavedQuery._get_transcoded_request( + http_options, request + ) - body = _BaseAssetServiceRestTransport._BaseCreateSavedQuery._get_request_body_json(transcoded_request) + body = _BaseAssetServiceRestTransport._BaseCreateSavedQuery._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseAssetServiceRestTransport._BaseCreateSavedQuery._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAssetServiceRestTransport._BaseCreateSavedQuery._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.asset_v1.AssetServiceClient.CreateSavedQuery", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "CreateSavedQuery", "httpRequest": http_request, @@ -2378,7 +3001,15 @@ def __call__(self, ) # Send the request - response = AssetServiceRestTransport._CreateSavedQuery._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = AssetServiceRestTransport._CreateSavedQuery._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2393,20 +3024,24 @@ def __call__(self, resp = self._interceptor.post_create_saved_query(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_saved_query_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_create_saved_query_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = asset_service.SavedQuery.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.asset_v1.AssetServiceClient.create_saved_query", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "CreateSavedQuery", "metadata": http_response["headers"], @@ -2415,7 +3050,9 @@ def __call__(self, ) return resp - class _DeleteFeed(_BaseAssetServiceRestTransport._BaseDeleteFeed, AssetServiceRestStub): + class _DeleteFeed( + _BaseAssetServiceRestTransport._BaseDeleteFeed, AssetServiceRestStub + ): def __hash__(self): return hash("AssetServiceRestTransport.DeleteFeed") @@ -2427,26 +3064,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: asset_service.DeleteFeedRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): + def __call__( + self, + request: asset_service.DeleteFeedRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): r"""Call the delete feed method over HTTP. Args: @@ -2461,30 +3100,44 @@ def __call__(self, be of type `bytes`. """ - http_options = _BaseAssetServiceRestTransport._BaseDeleteFeed._get_http_options() + http_options = ( + _BaseAssetServiceRestTransport._BaseDeleteFeed._get_http_options() + ) request, metadata = self._interceptor.pre_delete_feed(request, metadata) - transcoded_request = _BaseAssetServiceRestTransport._BaseDeleteFeed._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseAssetServiceRestTransport._BaseDeleteFeed._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseAssetServiceRestTransport._BaseDeleteFeed._get_query_params_json(transcoded_request) + query_params = ( + _BaseAssetServiceRestTransport._BaseDeleteFeed._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.asset_v1.AssetServiceClient.DeleteFeed", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "DeleteFeed", "httpRequest": http_request, @@ -2493,14 +3146,23 @@ def __call__(self, ) # Send the request - response = AssetServiceRestTransport._DeleteFeed._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AssetServiceRestTransport._DeleteFeed._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _DeleteSavedQuery(_BaseAssetServiceRestTransport._BaseDeleteSavedQuery, AssetServiceRestStub): + class _DeleteSavedQuery( + _BaseAssetServiceRestTransport._BaseDeleteSavedQuery, AssetServiceRestStub + ): def __hash__(self): return hash("AssetServiceRestTransport.DeleteSavedQuery") @@ -2512,26 +3174,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: asset_service.DeleteSavedQueryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): + def __call__( + self, + request: asset_service.DeleteSavedQueryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): r"""Call the delete saved query method over HTTP. Args: @@ -2546,30 +3210,42 @@ def __call__(self, be of type `bytes`. """ - http_options = _BaseAssetServiceRestTransport._BaseDeleteSavedQuery._get_http_options() + http_options = ( + _BaseAssetServiceRestTransport._BaseDeleteSavedQuery._get_http_options() + ) - request, metadata = self._interceptor.pre_delete_saved_query(request, metadata) - transcoded_request = _BaseAssetServiceRestTransport._BaseDeleteSavedQuery._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_delete_saved_query( + request, metadata + ) + transcoded_request = _BaseAssetServiceRestTransport._BaseDeleteSavedQuery._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAssetServiceRestTransport._BaseDeleteSavedQuery._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAssetServiceRestTransport._BaseDeleteSavedQuery._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.asset_v1.AssetServiceClient.DeleteSavedQuery", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "DeleteSavedQuery", "httpRequest": http_request, @@ -2578,14 +3254,23 @@ def __call__(self, ) # Send the request - response = AssetServiceRestTransport._DeleteSavedQuery._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AssetServiceRestTransport._DeleteSavedQuery._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _ExportAssets(_BaseAssetServiceRestTransport._BaseExportAssets, AssetServiceRestStub): + class _ExportAssets( + _BaseAssetServiceRestTransport._BaseExportAssets, AssetServiceRestStub + ): def __hash__(self): return hash("AssetServiceRestTransport.ExportAssets") @@ -2597,27 +3282,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: asset_service.ExportAssetsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: asset_service.ExportAssetsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the export assets method over HTTP. Args: @@ -2639,32 +3326,48 @@ def __call__(self, """ - http_options = _BaseAssetServiceRestTransport._BaseExportAssets._get_http_options() + http_options = ( + _BaseAssetServiceRestTransport._BaseExportAssets._get_http_options() + ) request, metadata = self._interceptor.pre_export_assets(request, metadata) - transcoded_request = _BaseAssetServiceRestTransport._BaseExportAssets._get_transcoded_request(http_options, request) + transcoded_request = _BaseAssetServiceRestTransport._BaseExportAssets._get_transcoded_request( + http_options, request + ) - body = _BaseAssetServiceRestTransport._BaseExportAssets._get_request_body_json(transcoded_request) + body = ( + _BaseAssetServiceRestTransport._BaseExportAssets._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = _BaseAssetServiceRestTransport._BaseExportAssets._get_query_params_json(transcoded_request) + query_params = ( + _BaseAssetServiceRestTransport._BaseExportAssets._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.asset_v1.AssetServiceClient.ExportAssets", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "ExportAssets", "httpRequest": http_request, @@ -2673,7 +3376,15 @@ def __call__(self, ) # Send the request - response = AssetServiceRestTransport._ExportAssets._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = AssetServiceRestTransport._ExportAssets._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2686,20 +3397,24 @@ def __call__(self, resp = self._interceptor.post_export_assets(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_export_assets_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_export_assets_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.asset_v1.AssetServiceClient.export_assets", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "ExportAssets", "metadata": http_response["headers"], @@ -2720,26 +3435,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: asset_service.GetFeedRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> asset_service.Feed: + def __call__( + self, + request: asset_service.GetFeedRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.Feed: r"""Call the get feed method over HTTP. Args: @@ -2766,30 +3483,44 @@ def __call__(self, """ - http_options = _BaseAssetServiceRestTransport._BaseGetFeed._get_http_options() + http_options = ( + _BaseAssetServiceRestTransport._BaseGetFeed._get_http_options() + ) request, metadata = self._interceptor.pre_get_feed(request, metadata) - transcoded_request = _BaseAssetServiceRestTransport._BaseGetFeed._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseAssetServiceRestTransport._BaseGetFeed._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseAssetServiceRestTransport._BaseGetFeed._get_query_params_json(transcoded_request) + query_params = ( + _BaseAssetServiceRestTransport._BaseGetFeed._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.asset_v1.AssetServiceClient.GetFeed", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "GetFeed", "httpRequest": http_request, @@ -2798,7 +3529,14 @@ def __call__(self, ) # Send the request - response = AssetServiceRestTransport._GetFeed._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AssetServiceRestTransport._GetFeed._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2813,20 +3551,24 @@ def __call__(self, resp = self._interceptor.post_get_feed(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_feed_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_feed_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = asset_service.Feed.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.asset_v1.AssetServiceClient.get_feed", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "GetFeed", "metadata": http_response["headers"], @@ -2835,7 +3577,9 @@ def __call__(self, ) return resp - class _GetSavedQuery(_BaseAssetServiceRestTransport._BaseGetSavedQuery, AssetServiceRestStub): + class _GetSavedQuery( + _BaseAssetServiceRestTransport._BaseGetSavedQuery, AssetServiceRestStub + ): def __hash__(self): return hash("AssetServiceRestTransport.GetSavedQuery") @@ -2847,26 +3591,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: asset_service.GetSavedQueryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> asset_service.SavedQuery: + def __call__( + self, + request: asset_service.GetSavedQueryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.SavedQuery: r"""Call the get saved query method over HTTP. Args: @@ -2887,30 +3633,40 @@ def __call__(self, """ - http_options = _BaseAssetServiceRestTransport._BaseGetSavedQuery._get_http_options() + http_options = ( + _BaseAssetServiceRestTransport._BaseGetSavedQuery._get_http_options() + ) request, metadata = self._interceptor.pre_get_saved_query(request, metadata) - transcoded_request = _BaseAssetServiceRestTransport._BaseGetSavedQuery._get_transcoded_request(http_options, request) + transcoded_request = _BaseAssetServiceRestTransport._BaseGetSavedQuery._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAssetServiceRestTransport._BaseGetSavedQuery._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAssetServiceRestTransport._BaseGetSavedQuery._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.asset_v1.AssetServiceClient.GetSavedQuery", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "GetSavedQuery", "httpRequest": http_request, @@ -2919,7 +3675,14 @@ def __call__(self, ) # Send the request - response = AssetServiceRestTransport._GetSavedQuery._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AssetServiceRestTransport._GetSavedQuery._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2934,20 +3697,24 @@ def __call__(self, resp = self._interceptor.post_get_saved_query(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_saved_query_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_saved_query_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = asset_service.SavedQuery.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.asset_v1.AssetServiceClient.get_saved_query", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "GetSavedQuery", "metadata": http_response["headers"], @@ -2956,7 +3723,9 @@ def __call__(self, ) return resp - class _ListAssets(_BaseAssetServiceRestTransport._BaseListAssets, AssetServiceRestStub): + class _ListAssets( + _BaseAssetServiceRestTransport._BaseListAssets, AssetServiceRestStub + ): def __hash__(self): return hash("AssetServiceRestTransport.ListAssets") @@ -2968,26 +3737,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: asset_service.ListAssetsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> asset_service.ListAssetsResponse: + def __call__( + self, + request: asset_service.ListAssetsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.ListAssetsResponse: r"""Call the list assets method over HTTP. Args: @@ -3006,30 +3777,44 @@ def __call__(self, ListAssets response. """ - http_options = _BaseAssetServiceRestTransport._BaseListAssets._get_http_options() + http_options = ( + _BaseAssetServiceRestTransport._BaseListAssets._get_http_options() + ) request, metadata = self._interceptor.pre_list_assets(request, metadata) - transcoded_request = _BaseAssetServiceRestTransport._BaseListAssets._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseAssetServiceRestTransport._BaseListAssets._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseAssetServiceRestTransport._BaseListAssets._get_query_params_json(transcoded_request) + query_params = ( + _BaseAssetServiceRestTransport._BaseListAssets._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.asset_v1.AssetServiceClient.ListAssets", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "ListAssets", "httpRequest": http_request, @@ -3038,7 +3823,14 @@ def __call__(self, ) # Send the request - response = AssetServiceRestTransport._ListAssets._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AssetServiceRestTransport._ListAssets._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3053,20 +3845,26 @@ def __call__(self, resp = self._interceptor.post_list_assets(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_assets_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_assets_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = asset_service.ListAssetsResponse.to_json(response) + response_payload = asset_service.ListAssetsResponse.to_json( + response + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.asset_v1.AssetServiceClient.list_assets", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "ListAssets", "metadata": http_response["headers"], @@ -3075,7 +3873,9 @@ def __call__(self, ) return resp - class _ListFeeds(_BaseAssetServiceRestTransport._BaseListFeeds, AssetServiceRestStub): + class _ListFeeds( + _BaseAssetServiceRestTransport._BaseListFeeds, AssetServiceRestStub + ): def __hash__(self): return hash("AssetServiceRestTransport.ListFeeds") @@ -3087,26 +3887,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: asset_service.ListFeedsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> asset_service.ListFeedsResponse: + def __call__( + self, + request: asset_service.ListFeedsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.ListFeedsResponse: r"""Call the list feeds method over HTTP. Args: @@ -3125,30 +3927,44 @@ def __call__(self, """ - http_options = _BaseAssetServiceRestTransport._BaseListFeeds._get_http_options() + http_options = ( + _BaseAssetServiceRestTransport._BaseListFeeds._get_http_options() + ) request, metadata = self._interceptor.pre_list_feeds(request, metadata) - transcoded_request = _BaseAssetServiceRestTransport._BaseListFeeds._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseAssetServiceRestTransport._BaseListFeeds._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseAssetServiceRestTransport._BaseListFeeds._get_query_params_json(transcoded_request) + query_params = ( + _BaseAssetServiceRestTransport._BaseListFeeds._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.asset_v1.AssetServiceClient.ListFeeds", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "ListFeeds", "httpRequest": http_request, @@ -3157,7 +3973,14 @@ def __call__(self, ) # Send the request - response = AssetServiceRestTransport._ListFeeds._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AssetServiceRestTransport._ListFeeds._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3172,20 +3995,24 @@ def __call__(self, resp = self._interceptor.post_list_feeds(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_feeds_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_feeds_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = asset_service.ListFeedsResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.asset_v1.AssetServiceClient.list_feeds", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "ListFeeds", "metadata": http_response["headers"], @@ -3194,7 +4021,9 @@ def __call__(self, ) return resp - class _ListSavedQueries(_BaseAssetServiceRestTransport._BaseListSavedQueries, AssetServiceRestStub): + class _ListSavedQueries( + _BaseAssetServiceRestTransport._BaseListSavedQueries, AssetServiceRestStub + ): def __hash__(self): return hash("AssetServiceRestTransport.ListSavedQueries") @@ -3206,26 +4035,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: asset_service.ListSavedQueriesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> asset_service.ListSavedQueriesResponse: + def __call__( + self, + request: asset_service.ListSavedQueriesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.ListSavedQueriesResponse: r"""Call the list saved queries method over HTTP. Args: @@ -3244,30 +4075,42 @@ def __call__(self, Response of listing saved queries. """ - http_options = _BaseAssetServiceRestTransport._BaseListSavedQueries._get_http_options() + http_options = ( + _BaseAssetServiceRestTransport._BaseListSavedQueries._get_http_options() + ) - request, metadata = self._interceptor.pre_list_saved_queries(request, metadata) - transcoded_request = _BaseAssetServiceRestTransport._BaseListSavedQueries._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_list_saved_queries( + request, metadata + ) + transcoded_request = _BaseAssetServiceRestTransport._BaseListSavedQueries._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAssetServiceRestTransport._BaseListSavedQueries._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAssetServiceRestTransport._BaseListSavedQueries._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.asset_v1.AssetServiceClient.ListSavedQueries", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "ListSavedQueries", "httpRequest": http_request, @@ -3276,7 +4119,14 @@ def __call__(self, ) # Send the request - response = AssetServiceRestTransport._ListSavedQueries._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AssetServiceRestTransport._ListSavedQueries._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3291,20 +4141,26 @@ def __call__(self, resp = self._interceptor.post_list_saved_queries(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_saved_queries_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_saved_queries_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = asset_service.ListSavedQueriesResponse.to_json(response) + response_payload = asset_service.ListSavedQueriesResponse.to_json( + response + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.asset_v1.AssetServiceClient.list_saved_queries", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "ListSavedQueries", "metadata": http_response["headers"], @@ -3313,7 +4169,9 @@ def __call__(self, ) return resp - class _QueryAssets(_BaseAssetServiceRestTransport._BaseQueryAssets, AssetServiceRestStub): + class _QueryAssets( + _BaseAssetServiceRestTransport._BaseQueryAssets, AssetServiceRestStub + ): def __hash__(self): return hash("AssetServiceRestTransport.QueryAssets") @@ -3325,27 +4183,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: asset_service.QueryAssetsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> asset_service.QueryAssetsResponse: + def __call__( + self, + request: asset_service.QueryAssetsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.QueryAssetsResponse: r"""Call the query assets method over HTTP. Args: @@ -3364,32 +4224,50 @@ def __call__(self, QueryAssets response. """ - http_options = _BaseAssetServiceRestTransport._BaseQueryAssets._get_http_options() + http_options = ( + _BaseAssetServiceRestTransport._BaseQueryAssets._get_http_options() + ) request, metadata = self._interceptor.pre_query_assets(request, metadata) - transcoded_request = _BaseAssetServiceRestTransport._BaseQueryAssets._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseAssetServiceRestTransport._BaseQueryAssets._get_transcoded_request( + http_options, request + ) + ) - body = _BaseAssetServiceRestTransport._BaseQueryAssets._get_request_body_json(transcoded_request) + body = ( + _BaseAssetServiceRestTransport._BaseQueryAssets._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = _BaseAssetServiceRestTransport._BaseQueryAssets._get_query_params_json(transcoded_request) + query_params = ( + _BaseAssetServiceRestTransport._BaseQueryAssets._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.asset_v1.AssetServiceClient.QueryAssets", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "QueryAssets", "httpRequest": http_request, @@ -3398,7 +4276,15 @@ def __call__(self, ) # Send the request - response = AssetServiceRestTransport._QueryAssets._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = AssetServiceRestTransport._QueryAssets._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3413,20 +4299,26 @@ def __call__(self, resp = self._interceptor.post_query_assets(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_query_assets_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_query_assets_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = asset_service.QueryAssetsResponse.to_json(response) + response_payload = asset_service.QueryAssetsResponse.to_json( + response + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.asset_v1.AssetServiceClient.query_assets", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "QueryAssets", "metadata": http_response["headers"], @@ -3435,7 +4327,9 @@ def __call__(self, ) return resp - class _SearchAllIamPolicies(_BaseAssetServiceRestTransport._BaseSearchAllIamPolicies, AssetServiceRestStub): + class _SearchAllIamPolicies( + _BaseAssetServiceRestTransport._BaseSearchAllIamPolicies, AssetServiceRestStub + ): def __hash__(self): return hash("AssetServiceRestTransport.SearchAllIamPolicies") @@ -3447,26 +4341,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: asset_service.SearchAllIamPoliciesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> asset_service.SearchAllIamPoliciesResponse: + def __call__( + self, + request: asset_service.SearchAllIamPoliciesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.SearchAllIamPoliciesResponse: r"""Call the search all iam policies method over HTTP. Args: @@ -3485,30 +4381,42 @@ def __call__(self, Search all IAM policies response. """ - http_options = _BaseAssetServiceRestTransport._BaseSearchAllIamPolicies._get_http_options() + http_options = ( + _BaseAssetServiceRestTransport._BaseSearchAllIamPolicies._get_http_options() + ) - request, metadata = self._interceptor.pre_search_all_iam_policies(request, metadata) - transcoded_request = _BaseAssetServiceRestTransport._BaseSearchAllIamPolicies._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_search_all_iam_policies( + request, metadata + ) + transcoded_request = _BaseAssetServiceRestTransport._BaseSearchAllIamPolicies._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAssetServiceRestTransport._BaseSearchAllIamPolicies._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAssetServiceRestTransport._BaseSearchAllIamPolicies._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.asset_v1.AssetServiceClient.SearchAllIamPolicies", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "SearchAllIamPolicies", "httpRequest": http_request, @@ -3517,7 +4425,14 @@ def __call__(self, ) # Send the request - response = AssetServiceRestTransport._SearchAllIamPolicies._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AssetServiceRestTransport._SearchAllIamPolicies._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3532,20 +4447,26 @@ def __call__(self, resp = self._interceptor.post_search_all_iam_policies(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_search_all_iam_policies_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_search_all_iam_policies_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = asset_service.SearchAllIamPoliciesResponse.to_json(response) + response_payload = ( + asset_service.SearchAllIamPoliciesResponse.to_json(response) + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.asset_v1.AssetServiceClient.search_all_iam_policies", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "SearchAllIamPolicies", "metadata": http_response["headers"], @@ -3554,7 +4475,9 @@ def __call__(self, ) return resp - class _SearchAllResources(_BaseAssetServiceRestTransport._BaseSearchAllResources, AssetServiceRestStub): + class _SearchAllResources( + _BaseAssetServiceRestTransport._BaseSearchAllResources, AssetServiceRestStub + ): def __hash__(self): return hash("AssetServiceRestTransport.SearchAllResources") @@ -3566,26 +4489,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: asset_service.SearchAllResourcesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> asset_service.SearchAllResourcesResponse: + def __call__( + self, + request: asset_service.SearchAllResourcesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.SearchAllResourcesResponse: r"""Call the search all resources method over HTTP. Args: @@ -3604,30 +4529,42 @@ def __call__(self, Search all resources response. """ - http_options = _BaseAssetServiceRestTransport._BaseSearchAllResources._get_http_options() + http_options = ( + _BaseAssetServiceRestTransport._BaseSearchAllResources._get_http_options() + ) - request, metadata = self._interceptor.pre_search_all_resources(request, metadata) - transcoded_request = _BaseAssetServiceRestTransport._BaseSearchAllResources._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_search_all_resources( + request, metadata + ) + transcoded_request = _BaseAssetServiceRestTransport._BaseSearchAllResources._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAssetServiceRestTransport._BaseSearchAllResources._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAssetServiceRestTransport._BaseSearchAllResources._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.asset_v1.AssetServiceClient.SearchAllResources", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "SearchAllResources", "httpRequest": http_request, @@ -3636,7 +4573,14 @@ def __call__(self, ) # Send the request - response = AssetServiceRestTransport._SearchAllResources._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AssetServiceRestTransport._SearchAllResources._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3651,20 +4595,26 @@ def __call__(self, resp = self._interceptor.post_search_all_resources(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_search_all_resources_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_search_all_resources_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = asset_service.SearchAllResourcesResponse.to_json(response) + response_payload = asset_service.SearchAllResourcesResponse.to_json( + response + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.asset_v1.AssetServiceClient.search_all_resources", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "SearchAllResources", "metadata": http_response["headers"], @@ -3673,7 +4623,9 @@ def __call__(self, ) return resp - class _UpdateFeed(_BaseAssetServiceRestTransport._BaseUpdateFeed, AssetServiceRestStub): + class _UpdateFeed( + _BaseAssetServiceRestTransport._BaseUpdateFeed, AssetServiceRestStub + ): def __hash__(self): return hash("AssetServiceRestTransport.UpdateFeed") @@ -3685,27 +4637,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: asset_service.UpdateFeedRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> asset_service.Feed: + def __call__( + self, + request: asset_service.UpdateFeedRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.Feed: r"""Call the update feed method over HTTP. Args: @@ -3732,32 +4686,50 @@ def __call__(self, """ - http_options = _BaseAssetServiceRestTransport._BaseUpdateFeed._get_http_options() + http_options = ( + _BaseAssetServiceRestTransport._BaseUpdateFeed._get_http_options() + ) request, metadata = self._interceptor.pre_update_feed(request, metadata) - transcoded_request = _BaseAssetServiceRestTransport._BaseUpdateFeed._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseAssetServiceRestTransport._BaseUpdateFeed._get_transcoded_request( + http_options, request + ) + ) - body = _BaseAssetServiceRestTransport._BaseUpdateFeed._get_request_body_json(transcoded_request) + body = ( + _BaseAssetServiceRestTransport._BaseUpdateFeed._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = _BaseAssetServiceRestTransport._BaseUpdateFeed._get_query_params_json(transcoded_request) + query_params = ( + _BaseAssetServiceRestTransport._BaseUpdateFeed._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.asset_v1.AssetServiceClient.UpdateFeed", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "UpdateFeed", "httpRequest": http_request, @@ -3766,7 +4738,15 @@ def __call__(self, ) # Send the request - response = AssetServiceRestTransport._UpdateFeed._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = AssetServiceRestTransport._UpdateFeed._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3781,20 +4761,24 @@ def __call__(self, resp = self._interceptor.post_update_feed(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_feed_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_update_feed_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = asset_service.Feed.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.asset_v1.AssetServiceClient.update_feed", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "UpdateFeed", "metadata": http_response["headers"], @@ -3803,7 +4787,9 @@ def __call__(self, ) return resp - class _UpdateSavedQuery(_BaseAssetServiceRestTransport._BaseUpdateSavedQuery, AssetServiceRestStub): + class _UpdateSavedQuery( + _BaseAssetServiceRestTransport._BaseUpdateSavedQuery, AssetServiceRestStub + ): def __hash__(self): return hash("AssetServiceRestTransport.UpdateSavedQuery") @@ -3815,27 +4801,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: asset_service.UpdateSavedQueryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> asset_service.SavedQuery: + def __call__( + self, + request: asset_service.UpdateSavedQueryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> asset_service.SavedQuery: r"""Call the update saved query method over HTTP. Args: @@ -3856,32 +4844,46 @@ def __call__(self, """ - http_options = _BaseAssetServiceRestTransport._BaseUpdateSavedQuery._get_http_options() + http_options = ( + _BaseAssetServiceRestTransport._BaseUpdateSavedQuery._get_http_options() + ) - request, metadata = self._interceptor.pre_update_saved_query(request, metadata) - transcoded_request = _BaseAssetServiceRestTransport._BaseUpdateSavedQuery._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_update_saved_query( + request, metadata + ) + transcoded_request = _BaseAssetServiceRestTransport._BaseUpdateSavedQuery._get_transcoded_request( + http_options, request + ) - body = _BaseAssetServiceRestTransport._BaseUpdateSavedQuery._get_request_body_json(transcoded_request) + body = _BaseAssetServiceRestTransport._BaseUpdateSavedQuery._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseAssetServiceRestTransport._BaseUpdateSavedQuery._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAssetServiceRestTransport._BaseUpdateSavedQuery._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.asset_v1.AssetServiceClient.UpdateSavedQuery", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "UpdateSavedQuery", "httpRequest": http_request, @@ -3890,7 +4892,15 @@ def __call__(self, ) # Send the request - response = AssetServiceRestTransport._UpdateSavedQuery._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = AssetServiceRestTransport._UpdateSavedQuery._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3905,20 +4915,24 @@ def __call__(self, resp = self._interceptor.post_update_saved_query(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_saved_query_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_update_saved_query_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = asset_service.SavedQuery.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.asset_v1.AssetServiceClient.update_saved_query", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "UpdateSavedQuery", "metadata": http_response["headers"], @@ -3928,194 +4942,225 @@ def __call__(self, return resp @property - def analyze_iam_policy(self) -> Callable[ - [asset_service.AnalyzeIamPolicyRequest], - asset_service.AnalyzeIamPolicyResponse]: + def analyze_iam_policy( + self, + ) -> Callable[ + [asset_service.AnalyzeIamPolicyRequest], asset_service.AnalyzeIamPolicyResponse + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._AnalyzeIamPolicy(self._session, self._host, self._interceptor) # type: ignore + return self._AnalyzeIamPolicy(self._session, self._host, self._interceptor) # type: ignore @property - def analyze_iam_policy_longrunning(self) -> Callable[ - [asset_service.AnalyzeIamPolicyLongrunningRequest], - operations_pb2.Operation]: + def analyze_iam_policy_longrunning( + self, + ) -> Callable[ + [asset_service.AnalyzeIamPolicyLongrunningRequest], operations_pb2.Operation + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._AnalyzeIamPolicyLongrunning(self._session, self._host, self._interceptor) # type: ignore + return self._AnalyzeIamPolicyLongrunning(self._session, self._host, self._interceptor) # type: ignore @property - def analyze_move(self) -> Callable[ - [asset_service.AnalyzeMoveRequest], - asset_service.AnalyzeMoveResponse]: + def analyze_move( + self, + ) -> Callable[ + [asset_service.AnalyzeMoveRequest], asset_service.AnalyzeMoveResponse + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._AnalyzeMove(self._session, self._host, self._interceptor) # type: ignore + return self._AnalyzeMove(self._session, self._host, self._interceptor) # type: ignore @property - def analyze_org_policies(self) -> Callable[ - [asset_service.AnalyzeOrgPoliciesRequest], - asset_service.AnalyzeOrgPoliciesResponse]: + def analyze_org_policies( + self, + ) -> Callable[ + [asset_service.AnalyzeOrgPoliciesRequest], + asset_service.AnalyzeOrgPoliciesResponse, + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._AnalyzeOrgPolicies(self._session, self._host, self._interceptor) # type: ignore + return self._AnalyzeOrgPolicies(self._session, self._host, self._interceptor) # type: ignore @property - def analyze_org_policy_governed_assets(self) -> Callable[ - [asset_service.AnalyzeOrgPolicyGovernedAssetsRequest], - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse]: + def analyze_org_policy_governed_assets( + self, + ) -> Callable[ + [asset_service.AnalyzeOrgPolicyGovernedAssetsRequest], + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse, + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._AnalyzeOrgPolicyGovernedAssets(self._session, self._host, self._interceptor) # type: ignore + return self._AnalyzeOrgPolicyGovernedAssets(self._session, self._host, self._interceptor) # type: ignore @property - def analyze_org_policy_governed_containers(self) -> Callable[ - [asset_service.AnalyzeOrgPolicyGovernedContainersRequest], - asset_service.AnalyzeOrgPolicyGovernedContainersResponse]: + def analyze_org_policy_governed_containers( + self, + ) -> Callable[ + [asset_service.AnalyzeOrgPolicyGovernedContainersRequest], + asset_service.AnalyzeOrgPolicyGovernedContainersResponse, + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._AnalyzeOrgPolicyGovernedContainers(self._session, self._host, self._interceptor) # type: ignore + return self._AnalyzeOrgPolicyGovernedContainers(self._session, self._host, self._interceptor) # type: ignore @property - def batch_get_assets_history(self) -> Callable[ - [asset_service.BatchGetAssetsHistoryRequest], - asset_service.BatchGetAssetsHistoryResponse]: + def batch_get_assets_history( + self, + ) -> Callable[ + [asset_service.BatchGetAssetsHistoryRequest], + asset_service.BatchGetAssetsHistoryResponse, + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._BatchGetAssetsHistory(self._session, self._host, self._interceptor) # type: ignore + return self._BatchGetAssetsHistory(self._session, self._host, self._interceptor) # type: ignore @property - def batch_get_effective_iam_policies(self) -> Callable[ - [asset_service.BatchGetEffectiveIamPoliciesRequest], - asset_service.BatchGetEffectiveIamPoliciesResponse]: + def batch_get_effective_iam_policies( + self, + ) -> Callable[ + [asset_service.BatchGetEffectiveIamPoliciesRequest], + asset_service.BatchGetEffectiveIamPoliciesResponse, + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._BatchGetEffectiveIamPolicies(self._session, self._host, self._interceptor) # type: ignore + return self._BatchGetEffectiveIamPolicies(self._session, self._host, self._interceptor) # type: ignore @property - def create_feed(self) -> Callable[ - [asset_service.CreateFeedRequest], - asset_service.Feed]: + def create_feed( + self, + ) -> Callable[[asset_service.CreateFeedRequest], asset_service.Feed]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._CreateFeed(self._session, self._host, self._interceptor) # type: ignore + return self._CreateFeed(self._session, self._host, self._interceptor) # type: ignore @property - def create_saved_query(self) -> Callable[ - [asset_service.CreateSavedQueryRequest], - asset_service.SavedQuery]: + def create_saved_query( + self, + ) -> Callable[[asset_service.CreateSavedQueryRequest], asset_service.SavedQuery]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._CreateSavedQuery(self._session, self._host, self._interceptor) # type: ignore + return self._CreateSavedQuery(self._session, self._host, self._interceptor) # type: ignore @property - def delete_feed(self) -> Callable[ - [asset_service.DeleteFeedRequest], - empty_pb2.Empty]: + def delete_feed( + self, + ) -> Callable[[asset_service.DeleteFeedRequest], empty_pb2.Empty]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._DeleteFeed(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteFeed(self._session, self._host, self._interceptor) # type: ignore @property - def delete_saved_query(self) -> Callable[ - [asset_service.DeleteSavedQueryRequest], - empty_pb2.Empty]: + def delete_saved_query( + self, + ) -> Callable[[asset_service.DeleteSavedQueryRequest], empty_pb2.Empty]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._DeleteSavedQuery(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteSavedQuery(self._session, self._host, self._interceptor) # type: ignore @property - def export_assets(self) -> Callable[ - [asset_service.ExportAssetsRequest], - operations_pb2.Operation]: + def export_assets( + self, + ) -> Callable[[asset_service.ExportAssetsRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._ExportAssets(self._session, self._host, self._interceptor) # type: ignore + return self._ExportAssets(self._session, self._host, self._interceptor) # type: ignore @property - def get_feed(self) -> Callable[ - [asset_service.GetFeedRequest], - asset_service.Feed]: + def get_feed(self) -> Callable[[asset_service.GetFeedRequest], asset_service.Feed]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._GetFeed(self._session, self._host, self._interceptor) # type: ignore + return self._GetFeed(self._session, self._host, self._interceptor) # type: ignore @property - def get_saved_query(self) -> Callable[ - [asset_service.GetSavedQueryRequest], - asset_service.SavedQuery]: + def get_saved_query( + self, + ) -> Callable[[asset_service.GetSavedQueryRequest], asset_service.SavedQuery]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._GetSavedQuery(self._session, self._host, self._interceptor) # type: ignore + return self._GetSavedQuery(self._session, self._host, self._interceptor) # type: ignore @property - def list_assets(self) -> Callable[ - [asset_service.ListAssetsRequest], - asset_service.ListAssetsResponse]: + def list_assets( + self, + ) -> Callable[[asset_service.ListAssetsRequest], asset_service.ListAssetsResponse]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._ListAssets(self._session, self._host, self._interceptor) # type: ignore + return self._ListAssets(self._session, self._host, self._interceptor) # type: ignore @property - def list_feeds(self) -> Callable[ - [asset_service.ListFeedsRequest], - asset_service.ListFeedsResponse]: + def list_feeds( + self, + ) -> Callable[[asset_service.ListFeedsRequest], asset_service.ListFeedsResponse]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._ListFeeds(self._session, self._host, self._interceptor) # type: ignore + return self._ListFeeds(self._session, self._host, self._interceptor) # type: ignore @property - def list_saved_queries(self) -> Callable[ - [asset_service.ListSavedQueriesRequest], - asset_service.ListSavedQueriesResponse]: + def list_saved_queries( + self, + ) -> Callable[ + [asset_service.ListSavedQueriesRequest], asset_service.ListSavedQueriesResponse + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._ListSavedQueries(self._session, self._host, self._interceptor) # type: ignore + return self._ListSavedQueries(self._session, self._host, self._interceptor) # type: ignore @property - def query_assets(self) -> Callable[ - [asset_service.QueryAssetsRequest], - asset_service.QueryAssetsResponse]: + def query_assets( + self, + ) -> Callable[ + [asset_service.QueryAssetsRequest], asset_service.QueryAssetsResponse + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._QueryAssets(self._session, self._host, self._interceptor) # type: ignore + return self._QueryAssets(self._session, self._host, self._interceptor) # type: ignore @property - def search_all_iam_policies(self) -> Callable[ - [asset_service.SearchAllIamPoliciesRequest], - asset_service.SearchAllIamPoliciesResponse]: + def search_all_iam_policies( + self, + ) -> Callable[ + [asset_service.SearchAllIamPoliciesRequest], + asset_service.SearchAllIamPoliciesResponse, + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._SearchAllIamPolicies(self._session, self._host, self._interceptor) # type: ignore + return self._SearchAllIamPolicies(self._session, self._host, self._interceptor) # type: ignore @property - def search_all_resources(self) -> Callable[ - [asset_service.SearchAllResourcesRequest], - asset_service.SearchAllResourcesResponse]: + def search_all_resources( + self, + ) -> Callable[ + [asset_service.SearchAllResourcesRequest], + asset_service.SearchAllResourcesResponse, + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._SearchAllResources(self._session, self._host, self._interceptor) # type: ignore + return self._SearchAllResources(self._session, self._host, self._interceptor) # type: ignore @property - def update_feed(self) -> Callable[ - [asset_service.UpdateFeedRequest], - asset_service.Feed]: + def update_feed( + self, + ) -> Callable[[asset_service.UpdateFeedRequest], asset_service.Feed]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._UpdateFeed(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateFeed(self._session, self._host, self._interceptor) # type: ignore @property - def update_saved_query(self) -> Callable[ - [asset_service.UpdateSavedQueryRequest], - asset_service.SavedQuery]: + def update_saved_query( + self, + ) -> Callable[[asset_service.UpdateSavedQueryRequest], asset_service.SavedQuery]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._UpdateSavedQuery(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateSavedQuery(self._session, self._host, self._interceptor) # type: ignore @property def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(_BaseAssetServiceRestTransport._BaseGetOperation, AssetServiceRestStub): + class _GetOperation( + _BaseAssetServiceRestTransport._BaseGetOperation, AssetServiceRestStub + ): def __hash__(self): return hash("AssetServiceRestTransport.GetOperation") @@ -4127,27 +5172,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the get operation method over HTTP. Args: @@ -4165,30 +5211,42 @@ def __call__(self, operations_pb2.Operation: Response from GetOperation method. """ - http_options = _BaseAssetServiceRestTransport._BaseGetOperation._get_http_options() + http_options = ( + _BaseAssetServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseAssetServiceRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + transcoded_request = _BaseAssetServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAssetServiceRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) + query_params = ( + _BaseAssetServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.asset_v1.AssetServiceClient.GetOperation", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "GetOperation", "httpRequest": http_request, @@ -4197,7 +5255,14 @@ def __call__(self, ) # Send the request - response = AssetServiceRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AssetServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -4208,19 +5273,21 @@ def __call__(self, resp = operations_pb2.Operation() resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.asset_v1.AssetServiceAsyncClient.GetOperation", - extra = { + extra={ "serviceName": "google.cloud.asset.v1.AssetService", "rpcName": "GetOperation", "httpResponse": http_response, @@ -4237,6 +5304,4 @@ def close(self): self._session.close() -__all__=( - 'AssetServiceRestTransport', -) +__all__ = ("AssetServiceRestTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/asset/setup.py b/packages/gapic-generator/tests/integration/goldens/asset/setup.py index d5e4623ee04b..c5727134d203 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/setup.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/setup.py @@ -17,23 +17,23 @@ import os import re -import setuptools # type: ignore +import setuptools # type: ignore package_root = os.path.abspath(os.path.dirname(__file__)) -name = 'google-cloud-asset' +name = "google-cloud-asset" description = "Google Cloud Asset API client library" version = None -with open(os.path.join(package_root, 'google/cloud/asset/gapic_version.py')) as fp: +with open(os.path.join(package_root, "google/cloud/asset/gapic_version.py")) as fp: version_candidates = re.findall( r"(?<=\")\d+\.\d+\.\d+[^\"\s]*(?=\")", fp.read(), ) - assert (len(version_candidates) == 1) + assert len(version_candidates) == 1 version = version_candidates[0] if version[0] == "0": @@ -54,8 +54,7 @@ "google-cloud-os-config >= 1.20.1, <2.0.0", "grpc-google-iam-v1 >= 0.14.2, <1.0.0", ] -extras = { -} +extras = {} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-asset" package_root = os.path.abspath(os.path.dirname(__file__)) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/__init__.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/__init__.py index 943687313e36..3cc7ce960425 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/__init__.py @@ -35,10 +35,12 @@ from .types.common import SignJwtRequest from .types.common import SignJwtResponse -if hasattr(api_core, "check_python_version") and hasattr(api_core, "check_dependency_versions"): # pragma: NO COVER - api_core.check_python_version("google.iam.credentials_v1") # type: ignore - api_core.check_dependency_versions("google.iam.credentials_v1") # type: ignore -else: # pragma: NO COVER +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.iam.credentials_v1") # type: ignore + api_core.check_dependency_versions("google.iam.credentials_v1") # type: ignore +else: # pragma: NO COVER # An older version of api_core is installed which does not define the # functions above. We do equivalent checks manually. try: @@ -47,12 +49,14 @@ _py_version_str = sys.version.split()[0] _package_label = "google.iam.credentials_v1" if sys.version_info < (3, 10): - warnings.warn("You are using a non-supported Python version " + - f"({_py_version_str}). Google will not post any further " + - f"updates to {_package_label} supporting this Python version. " + - "Please upgrade to the latest Python version, or at " + - f"least to Python 3.10, and then update {_package_label}.", - FutureWarning) + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.10, and then update {_package_label}.", + FutureWarning, + ) def parse_version_to_tuple(version_string: str): """Safely converts a semantic version string to a comparable tuple of integers. @@ -90,35 +94,39 @@ def _get_version(dependency_name): _recommendation = " (we recommend 7.x)" (_version_used, _version_used_string) = _get_version(_dependency_package) if _version_used and _version_used < _next_supported_version_tuple: - warnings.warn(f"Package {_package_label} depends on " + - f"{_dependency_package}, currently installed at version " + - f"{_version_used_string}. Future updates to " + - f"{_package_label} will require {_dependency_package} at " + - f"version {_next_supported_version} or higher{_recommendation}." + - " Please ensure " + - "that either (a) your Python environment doesn't pin the " + - f"version of {_dependency_package}, so that updates to " + - f"{_package_label} can require the higher version, or " + - "(b) you manually update your Python environment to use at " + - f"least version {_next_supported_version} of " + - f"{_dependency_package}.", - FutureWarning) + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) except Exception: - warnings.warn("Could not determine the version of Python " + - "currently being used. To continue receiving " + - "updates for {_package_label}, ensure you are " + - "using a supported version of Python; see " + - "https://devguide.python.org/versions/") + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) __all__ = ( - 'IAMCredentialsAsyncClient', -'GenerateAccessTokenRequest', -'GenerateAccessTokenResponse', -'GenerateIdTokenRequest', -'GenerateIdTokenResponse', -'IAMCredentialsClient', -'SignBlobRequest', -'SignBlobResponse', -'SignJwtRequest', -'SignJwtResponse', + "IAMCredentialsAsyncClient", + "GenerateAccessTokenRequest", + "GenerateAccessTokenResponse", + "GenerateIdTokenRequest", + "GenerateIdTokenResponse", + "IAMCredentialsClient", + "SignBlobRequest", + "SignBlobResponse", + "SignJwtRequest", + "SignJwtResponse", ) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/async_client.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/async_client.py index a0f4996ffd20..316ab578023c 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/async_client.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/async_client.py @@ -16,7 +16,18 @@ import logging as std_logging from collections import OrderedDict import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union +from typing import ( + Dict, + Callable, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) from google.iam.credentials_v1 import gapic_version as package_version @@ -24,8 +35,8 @@ from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf @@ -43,12 +54,14 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) + class IAMCredentialsAsyncClient: """A service account is a special type of Google account that belongs to your application or a virtual machine (VM), instead @@ -72,17 +85,33 @@ class IAMCredentialsAsyncClient: _DEFAULT_UNIVERSE = IAMCredentialsClient._DEFAULT_UNIVERSE service_account_path = staticmethod(IAMCredentialsClient.service_account_path) - parse_service_account_path = staticmethod(IAMCredentialsClient.parse_service_account_path) - common_billing_account_path = staticmethod(IAMCredentialsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(IAMCredentialsClient.parse_common_billing_account_path) + parse_service_account_path = staticmethod( + IAMCredentialsClient.parse_service_account_path + ) + common_billing_account_path = staticmethod( + IAMCredentialsClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + IAMCredentialsClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(IAMCredentialsClient.common_folder_path) - parse_common_folder_path = staticmethod(IAMCredentialsClient.parse_common_folder_path) - common_organization_path = staticmethod(IAMCredentialsClient.common_organization_path) - parse_common_organization_path = staticmethod(IAMCredentialsClient.parse_common_organization_path) + parse_common_folder_path = staticmethod( + IAMCredentialsClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + IAMCredentialsClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + IAMCredentialsClient.parse_common_organization_path + ) common_project_path = staticmethod(IAMCredentialsClient.common_project_path) - parse_common_project_path = staticmethod(IAMCredentialsClient.parse_common_project_path) + parse_common_project_path = staticmethod( + IAMCredentialsClient.parse_common_project_path + ) common_location_path = staticmethod(IAMCredentialsClient.common_location_path) - parse_common_location_path = staticmethod(IAMCredentialsClient.parse_common_location_path) + parse_common_location_path = staticmethod( + IAMCredentialsClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -124,7 +153,9 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): """Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -187,12 +218,16 @@ def universe_domain(self) -> str: get_transport_class = IAMCredentialsClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, IAMCredentialsTransport, Callable[..., IAMCredentialsTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, IAMCredentialsTransport, Callable[..., IAMCredentialsTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the iam credentials async client. Args: @@ -250,34 +285,42 @@ def __init__(self, *, transport=transport, client_options=client_options, client_info=client_info, - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.iam.credentials_v1.IAMCredentialsAsyncClient`.", - extra = { + extra={ "serviceName": "google.iam.credentials.v1.IAMCredentials", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { "serviceName": "google.iam.credentials.v1.IAMCredentials", "credentialsType": None, - } + }, ) - async def generate_access_token(self, - request: Optional[Union[common.GenerateAccessTokenRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - scope: Optional[MutableSequence[str]] = None, - lifetime: Optional[duration_pb2.Duration] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.GenerateAccessTokenResponse: + async def generate_access_token( + self, + request: Optional[Union[common.GenerateAccessTokenRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + scope: Optional[MutableSequence[str]] = None, + lifetime: Optional[duration_pb2.Duration] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.GenerateAccessTokenResponse: r"""Generates an OAuth 2.0 access token for a service account. @@ -378,10 +421,14 @@ async def sample_generate_access_token(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, scope, lifetime] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -401,14 +448,14 @@ async def sample_generate_access_token(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.generate_access_token] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.generate_access_token + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -425,17 +472,18 @@ async def sample_generate_access_token(): # Done; return the response. return response - async def generate_id_token(self, - request: Optional[Union[common.GenerateIdTokenRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - audience: Optional[str] = None, - include_email: Optional[bool] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.GenerateIdTokenResponse: + async def generate_id_token( + self, + request: Optional[Union[common.GenerateIdTokenRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + audience: Optional[str] = None, + include_email: Optional[bool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.GenerateIdTokenResponse: r"""Generates an OpenID Connect ID token for a service account. @@ -530,10 +578,14 @@ async def sample_generate_id_token(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, audience, include_email] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -553,14 +605,14 @@ async def sample_generate_id_token(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.generate_id_token] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.generate_id_token + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -577,16 +629,17 @@ async def sample_generate_id_token(): # Done; return the response. return response - async def sign_blob(self, - request: Optional[Union[common.SignBlobRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - payload: Optional[bytes] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.SignBlobResponse: + async def sign_blob( + self, + request: Optional[Union[common.SignBlobRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + payload: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.SignBlobResponse: r"""Signs a blob using a service account's system-managed private key. @@ -670,10 +723,14 @@ async def sample_sign_blob(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, payload] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -691,14 +748,14 @@ async def sample_sign_blob(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.sign_blob] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.sign_blob + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -715,16 +772,17 @@ async def sample_sign_blob(): # Done; return the response. return response - async def sign_jwt(self, - request: Optional[Union[common.SignJwtRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - payload: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.SignJwtResponse: + async def sign_jwt( + self, + request: Optional[Union[common.SignJwtRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + payload: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.SignJwtResponse: r"""Signs a JWT using a service account's system-managed private key. @@ -811,10 +869,14 @@ async def sample_sign_jwt(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, payload] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -837,9 +899,7 @@ async def sample_sign_jwt(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -862,12 +922,13 @@ async def __aenter__(self) -> "IAMCredentialsAsyncClient": async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "IAMCredentialsAsyncClient", -) +__all__ = ("IAMCredentialsAsyncClient",) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py index c466eeb53f4e..701136a496c2 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py @@ -19,7 +19,19 @@ import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +from typing import ( + Dict, + Callable, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) import warnings from google.iam.credentials_v1 import gapic_version as package_version @@ -28,11 +40,11 @@ from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.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.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 import google.protobuf try: @@ -42,6 +54,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -64,14 +77,18 @@ class IAMCredentialsClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[IAMCredentialsTransport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[IAMCredentialsTransport]] _transport_registry["grpc"] = IAMCredentialsGrpcTransport _transport_registry["grpc_asyncio"] = IAMCredentialsGrpcAsyncIOTransport _transport_registry["rest"] = IAMCredentialsRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[IAMCredentialsTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[IAMCredentialsTransport]: """Returns an appropriate transport class. Args: @@ -157,14 +174,16 @@ def _use_client_cert_effective(): bool: whether client certificate should be used for mTLS Raises: ValueError: (If using a version of google-auth without should_use_client_cert and - GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) """ # check if google-auth version supports should_use_client_cert for automatic mTLS enablement if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER return mtls.should_use_client_cert() - else: # pragma: NO COVER + else: # pragma: NO COVER # if unsupported, fallback to reading from env var - use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() if use_client_cert_str not in ("true", "false"): raise ValueError( "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" @@ -203,8 +222,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: IAMCredentialsClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -221,73 +239,106 @@ def transport(self) -> IAMCredentialsTransport: return self._transport @staticmethod - def service_account_path(project: str,service_account: str,) -> str: + def service_account_path( + project: str, + service_account: str, + ) -> str: """Returns a fully-qualified service_account string.""" - return "projects/{project}/serviceAccounts/{service_account}".format(project=project, service_account=service_account, ) + return "projects/{project}/serviceAccounts/{service_account}".format( + project=project, + service_account=service_account, + ) @staticmethod - def parse_service_account_path(path: str) -> Dict[str,str]: + def parse_service_account_path(path: str) -> Dict[str, str]: """Parses a service_account path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/serviceAccounts/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/serviceAccounts/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + def common_billing_account_path( + billing_account: str, + ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path(folder: str, ) -> str: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path(organization: str, ) -> str: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path(project: str, ) -> str: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path(project: str, location: str, ) -> str: + def common_location_path( + project: str, + location: str, + ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -319,14 +370,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = IAMCredentialsClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Figure out the client cert source to use. client_cert_source = None @@ -339,7 +394,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): api_endpoint = cls.DEFAULT_MTLS_ENDPOINT else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -364,7 +421,9 @@ def _read_environment_variables(): use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod @@ -387,7 +446,9 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: """Return the API endpoint used by the client. Args: @@ -403,17 +464,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): _default_universe = IAMCredentialsClient._DEFAULT_UNIVERSE if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) api_endpoint = IAMCredentialsClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) return api_endpoint @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: """Return the universe domain used by the client. Args: @@ -449,15 +518,18 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError + self, error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: return cred = self._transport._credentials @@ -490,12 +562,16 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, IAMCredentialsTransport, Callable[..., IAMCredentialsTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, IAMCredentialsTransport, Callable[..., IAMCredentialsTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the iam credentials client. Args: @@ -553,13 +629,23 @@ def __init__(self, *, self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = IAMCredentialsClient._read_environment_variables() - self._client_cert_source = IAMCredentialsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = IAMCredentialsClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = IAMCredentialsClient._read_environment_variables() + self._client_cert_source = IAMCredentialsClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = IAMCredentialsClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -571,7 +657,9 @@ def __init__(self, *, api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -580,8 +668,10 @@ def __init__(self, *, if transport_provided: # transport is a IAMCredentialsTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if self._client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes " @@ -590,20 +680,29 @@ def __init__(self, *, self._transport = cast(IAMCredentialsTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - IAMCredentialsClient._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or IAMCredentialsClient._get_api_endpoint( self._client_options.api_endpoint, self._client_cert_source, self._universe_domain, - self._use_mtls_endpoint)) + self._use_mtls_endpoint, + ) + ) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) - transport_init: Union[Type[IAMCredentialsTransport], Callable[..., IAMCredentialsTransport]] = ( + transport_init: Union[ + Type[IAMCredentialsTransport], Callable[..., IAMCredentialsTransport] + ] = ( IAMCredentialsClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., IAMCredentialsTransport], transport) @@ -622,31 +721,40 @@ def __init__(self, *, ) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.iam.credentials_v1.IAMCredentialsClient`.", - extra = { + extra={ "serviceName": "google.iam.credentials.v1.IAMCredentials", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { "serviceName": "google.iam.credentials.v1.IAMCredentials", "credentialsType": None, - } + }, ) - def generate_access_token(self, - request: Optional[Union[common.GenerateAccessTokenRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - scope: Optional[MutableSequence[str]] = None, - lifetime: Optional[duration_pb2.Duration] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.GenerateAccessTokenResponse: + def generate_access_token( + self, + request: Optional[Union[common.GenerateAccessTokenRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + scope: Optional[MutableSequence[str]] = None, + lifetime: Optional[duration_pb2.Duration] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.GenerateAccessTokenResponse: r"""Generates an OAuth 2.0 access token for a service account. @@ -747,10 +855,14 @@ def sample_generate_access_token(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, scope, lifetime] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -774,9 +886,7 @@ def sample_generate_access_token(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -793,17 +903,18 @@ def sample_generate_access_token(): # Done; return the response. return response - def generate_id_token(self, - request: Optional[Union[common.GenerateIdTokenRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - audience: Optional[str] = None, - include_email: Optional[bool] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.GenerateIdTokenResponse: + def generate_id_token( + self, + request: Optional[Union[common.GenerateIdTokenRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + audience: Optional[str] = None, + include_email: Optional[bool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.GenerateIdTokenResponse: r"""Generates an OpenID Connect ID token for a service account. @@ -898,10 +1009,14 @@ def sample_generate_id_token(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, audience, include_email] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -925,9 +1040,7 @@ def sample_generate_id_token(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -944,16 +1057,17 @@ def sample_generate_id_token(): # Done; return the response. return response - def sign_blob(self, - request: Optional[Union[common.SignBlobRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - payload: Optional[bytes] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.SignBlobResponse: + def sign_blob( + self, + request: Optional[Union[common.SignBlobRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + payload: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.SignBlobResponse: r"""Signs a blob using a service account's system-managed private key. @@ -1037,10 +1151,14 @@ def sample_sign_blob(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, payload] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1062,9 +1180,7 @@ def sample_sign_blob(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1081,16 +1197,17 @@ def sample_sign_blob(): # Done; return the response. return response - def sign_jwt(self, - request: Optional[Union[common.SignJwtRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - payload: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.SignJwtResponse: + def sign_jwt( + self, + request: Optional[Union[common.SignJwtRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + payload: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.SignJwtResponse: r"""Signs a JWT using a service account's system-managed private key. @@ -1177,10 +1294,14 @@ def sample_sign_jwt(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, payload] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1202,9 +1323,7 @@ def sample_sign_jwt(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1235,16 +1354,11 @@ def __exit__(self, type, value, traceback): self.transport.close() - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "IAMCredentialsClient", -) +__all__ = ("IAMCredentialsClient",) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py index d59eeedc25f9..f24bcb272d5e 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py @@ -24,12 +24,14 @@ from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf from google.iam.credentials_v1.types import common -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ @@ -38,24 +40,23 @@ class IAMCredentialsTransport(abc.ABC): """Abstract transport class for IAMCredentials.""" - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - DEFAULT_HOST: str = 'iamcredentials.googleapis.com' + DEFAULT_HOST: str = "iamcredentials.googleapis.com" def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -94,31 +95,43 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host self._wrapped_methods: Dict[Callable, Callable] = {} @@ -190,51 +203,56 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @property - def generate_access_token(self) -> Callable[ - [common.GenerateAccessTokenRequest], - Union[ - common.GenerateAccessTokenResponse, - Awaitable[common.GenerateAccessTokenResponse] - ]]: + def generate_access_token( + self, + ) -> Callable[ + [common.GenerateAccessTokenRequest], + Union[ + common.GenerateAccessTokenResponse, + Awaitable[common.GenerateAccessTokenResponse], + ], + ]: raise NotImplementedError() @property - def generate_id_token(self) -> Callable[ - [common.GenerateIdTokenRequest], - Union[ - common.GenerateIdTokenResponse, - Awaitable[common.GenerateIdTokenResponse] - ]]: + def generate_id_token( + self, + ) -> Callable[ + [common.GenerateIdTokenRequest], + Union[ + common.GenerateIdTokenResponse, Awaitable[common.GenerateIdTokenResponse] + ], + ]: raise NotImplementedError() @property - def sign_blob(self) -> Callable[ - [common.SignBlobRequest], - Union[ - common.SignBlobResponse, - Awaitable[common.SignBlobResponse] - ]]: + def sign_blob( + self, + ) -> Callable[ + [common.SignBlobRequest], + Union[common.SignBlobResponse, Awaitable[common.SignBlobResponse]], + ]: raise NotImplementedError() @property - def sign_jwt(self) -> Callable[ - [common.SignJwtRequest], - Union[ - common.SignJwtResponse, - Awaitable[common.SignJwtResponse] - ]]: + def sign_jwt( + self, + ) -> Callable[ + [common.SignJwtRequest], + Union[common.SignJwtResponse, Awaitable[common.SignJwtResponse]], + ]: raise NotImplementedError() @property @@ -242,6 +260,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'IAMCredentialsTransport', -) +__all__ = ("IAMCredentialsTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/rest.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/rest.py index fbb576e2c5f7..662f8d1d5f1f 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/rest.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/rest.py @@ -46,6 +46,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -114,7 +115,14 @@ def post_sign_jwt(self, response): """ - def pre_generate_access_token(self, request: common.GenerateAccessTokenRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[common.GenerateAccessTokenRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_generate_access_token( + self, + request: common.GenerateAccessTokenRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + common.GenerateAccessTokenRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for generate_access_token Override in a subclass to manipulate the request or metadata @@ -122,7 +130,9 @@ def pre_generate_access_token(self, request: common.GenerateAccessTokenRequest, """ return request, metadata - def post_generate_access_token(self, response: common.GenerateAccessTokenResponse) -> common.GenerateAccessTokenResponse: + def post_generate_access_token( + self, response: common.GenerateAccessTokenResponse + ) -> common.GenerateAccessTokenResponse: """Post-rpc interceptor for generate_access_token DEPRECATED. Please use the `post_generate_access_token_with_metadata` @@ -135,7 +145,13 @@ def post_generate_access_token(self, response: common.GenerateAccessTokenRespons """ return response - def post_generate_access_token_with_metadata(self, response: common.GenerateAccessTokenResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[common.GenerateAccessTokenResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_generate_access_token_with_metadata( + self, + response: common.GenerateAccessTokenResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + common.GenerateAccessTokenResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for generate_access_token Override in a subclass to read or manipulate the response or metadata after it @@ -150,7 +166,11 @@ def post_generate_access_token_with_metadata(self, response: common.GenerateAcce """ return response, metadata - def pre_generate_id_token(self, request: common.GenerateIdTokenRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[common.GenerateIdTokenRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_generate_id_token( + self, + request: common.GenerateIdTokenRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[common.GenerateIdTokenRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for generate_id_token Override in a subclass to manipulate the request or metadata @@ -158,7 +178,9 @@ def pre_generate_id_token(self, request: common.GenerateIdTokenRequest, metadata """ return request, metadata - def post_generate_id_token(self, response: common.GenerateIdTokenResponse) -> common.GenerateIdTokenResponse: + def post_generate_id_token( + self, response: common.GenerateIdTokenResponse + ) -> common.GenerateIdTokenResponse: """Post-rpc interceptor for generate_id_token DEPRECATED. Please use the `post_generate_id_token_with_metadata` @@ -171,7 +193,11 @@ def post_generate_id_token(self, response: common.GenerateIdTokenResponse) -> co """ return response - def post_generate_id_token_with_metadata(self, response: common.GenerateIdTokenResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[common.GenerateIdTokenResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_generate_id_token_with_metadata( + self, + response: common.GenerateIdTokenResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[common.GenerateIdTokenResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for generate_id_token Override in a subclass to read or manipulate the response or metadata after it @@ -186,7 +212,11 @@ def post_generate_id_token_with_metadata(self, response: common.GenerateIdTokenR """ return response, metadata - def pre_sign_blob(self, request: common.SignBlobRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[common.SignBlobRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_sign_blob( + self, + request: common.SignBlobRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[common.SignBlobRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for sign_blob Override in a subclass to manipulate the request or metadata @@ -194,7 +224,9 @@ def pre_sign_blob(self, request: common.SignBlobRequest, metadata: Sequence[Tupl """ return request, metadata - def post_sign_blob(self, response: common.SignBlobResponse) -> common.SignBlobResponse: + def post_sign_blob( + self, response: common.SignBlobResponse + ) -> common.SignBlobResponse: """Post-rpc interceptor for sign_blob DEPRECATED. Please use the `post_sign_blob_with_metadata` @@ -207,7 +239,11 @@ def post_sign_blob(self, response: common.SignBlobResponse) -> common.SignBlobRe """ return response - def post_sign_blob_with_metadata(self, response: common.SignBlobResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[common.SignBlobResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_sign_blob_with_metadata( + self, + response: common.SignBlobResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[common.SignBlobResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for sign_blob Override in a subclass to read or manipulate the response or metadata after it @@ -222,7 +258,11 @@ def post_sign_blob_with_metadata(self, response: common.SignBlobResponse, metada """ return response, metadata - def pre_sign_jwt(self, request: common.SignJwtRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[common.SignJwtRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_sign_jwt( + self, + request: common.SignJwtRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[common.SignJwtRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for sign_jwt Override in a subclass to manipulate the request or metadata @@ -243,7 +283,11 @@ def post_sign_jwt(self, response: common.SignJwtResponse) -> common.SignJwtRespo """ return response - def post_sign_jwt_with_metadata(self, response: common.SignJwtResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[common.SignJwtResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_sign_jwt_with_metadata( + self, + response: common.SignJwtResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[common.SignJwtResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for sign_jwt Override in a subclass to read or manipulate the response or metadata after it @@ -287,62 +331,63 @@ class IAMCredentialsRestTransport(_BaseIAMCredentialsRestTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__(self, *, - host: str = 'iamcredentials.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[IAMCredentialsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: + def __init__( + self, + *, + host: str = "iamcredentials.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[IAMCredentialsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. - NOTE: This REST transport functionality is currently in a beta - state (preview). We welcome your feedback via a GitHub issue in - this library's repository. Thank you! - - Args: - host (Optional[str]): - The hostname to connect to (default: 'iamcredentials.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. This argument will be - removed in the next major version of this library. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - interceptor (Optional[IAMCredentialsRestInterceptor]): Interceptor used - to manipulate requests, request metadata, and responses. - api_audience (Optional[str]): The intended audience for the API calls - to the service that will be set when using certain 3rd party - authentication flows. Audience is typically a resource identifier. - If not set, the host value will be used as a default. + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iamcredentials.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[IAMCredentialsRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. """ # Run the base constructor # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. @@ -354,16 +399,20 @@ def __init__(self, *, client_info=client_info, always_use_jwt_access=always_use_jwt_access, url_scheme=url_scheme, - api_audience=api_audience + api_audience=api_audience, ) self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) + self._credentials, default_host=self.DEFAULT_HOST + ) if client_cert_source_for_mtls: self._session.configure_mtls_channel(client_cert_source_for_mtls) self._interceptor = interceptor or IAMCredentialsRestInterceptor() self._prep_wrapped_messages(client_info) - class _GenerateAccessToken(_BaseIAMCredentialsRestTransport._BaseGenerateAccessToken, IAMCredentialsRestStub): + class _GenerateAccessToken( + _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken, + IAMCredentialsRestStub, + ): def __hash__(self): return hash("IAMCredentialsRestTransport.GenerateAccessToken") @@ -375,27 +424,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: common.GenerateAccessTokenRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> common.GenerateAccessTokenResponse: + def __call__( + self, + request: common.GenerateAccessTokenRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.GenerateAccessTokenResponse: r"""Call the generate access token method over HTTP. Args: @@ -414,32 +465,46 @@ def __call__(self, """ - http_options = _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_http_options() + http_options = ( + _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_http_options() + ) - request, metadata = self._interceptor.pre_generate_access_token(request, metadata) - transcoded_request = _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_generate_access_token( + request, metadata + ) + transcoded_request = _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_transcoded_request( + http_options, request + ) - body = _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_request_body_json(transcoded_request) + body = _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.iam.credentials_v1.IAMCredentialsClient.GenerateAccessToken", - extra = { + extra={ "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": "GenerateAccessToken", "httpRequest": http_request, @@ -448,7 +513,15 @@ def __call__(self, ) # Send the request - response = IAMCredentialsRestTransport._GenerateAccessToken._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = IAMCredentialsRestTransport._GenerateAccessToken._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -463,20 +536,26 @@ def __call__(self, resp = self._interceptor.post_generate_access_token(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_generate_access_token_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_generate_access_token_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = common.GenerateAccessTokenResponse.to_json(response) + response_payload = common.GenerateAccessTokenResponse.to_json( + response + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.iam.credentials_v1.IAMCredentialsClient.generate_access_token", - extra = { + extra={ "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": "GenerateAccessToken", "metadata": http_response["headers"], @@ -485,7 +564,9 @@ def __call__(self, ) return resp - class _GenerateIdToken(_BaseIAMCredentialsRestTransport._BaseGenerateIdToken, IAMCredentialsRestStub): + class _GenerateIdToken( + _BaseIAMCredentialsRestTransport._BaseGenerateIdToken, IAMCredentialsRestStub + ): def __hash__(self): return hash("IAMCredentialsRestTransport.GenerateIdToken") @@ -497,27 +578,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: common.GenerateIdTokenRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> common.GenerateIdTokenResponse: + def __call__( + self, + request: common.GenerateIdTokenRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.GenerateIdTokenResponse: r"""Call the generate id token method over HTTP. Args: @@ -536,32 +619,46 @@ def __call__(self, """ - http_options = _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_http_options() + http_options = ( + _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_http_options() + ) - request, metadata = self._interceptor.pre_generate_id_token(request, metadata) - transcoded_request = _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_generate_id_token( + request, metadata + ) + transcoded_request = _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_transcoded_request( + http_options, request + ) - body = _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_request_body_json(transcoded_request) + body = _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.iam.credentials_v1.IAMCredentialsClient.GenerateIdToken", - extra = { + extra={ "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": "GenerateIdToken", "httpRequest": http_request, @@ -570,7 +667,15 @@ def __call__(self, ) # Send the request - response = IAMCredentialsRestTransport._GenerateIdToken._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = IAMCredentialsRestTransport._GenerateIdToken._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -585,20 +690,24 @@ def __call__(self, resp = self._interceptor.post_generate_id_token(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_generate_id_token_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_generate_id_token_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = common.GenerateIdTokenResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.iam.credentials_v1.IAMCredentialsClient.generate_id_token", - extra = { + extra={ "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": "GenerateIdToken", "metadata": http_response["headers"], @@ -607,7 +716,9 @@ def __call__(self, ) return resp - class _SignBlob(_BaseIAMCredentialsRestTransport._BaseSignBlob, IAMCredentialsRestStub): + class _SignBlob( + _BaseIAMCredentialsRestTransport._BaseSignBlob, IAMCredentialsRestStub + ): def __hash__(self): return hash("IAMCredentialsRestTransport.SignBlob") @@ -619,27 +730,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: common.SignBlobRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> common.SignBlobResponse: + def __call__( + self, + request: common.SignBlobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.SignBlobResponse: r"""Call the sign blob method over HTTP. Args: @@ -658,32 +771,50 @@ def __call__(self, """ - http_options = _BaseIAMCredentialsRestTransport._BaseSignBlob._get_http_options() + http_options = ( + _BaseIAMCredentialsRestTransport._BaseSignBlob._get_http_options() + ) request, metadata = self._interceptor.pre_sign_blob(request, metadata) - transcoded_request = _BaseIAMCredentialsRestTransport._BaseSignBlob._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseIAMCredentialsRestTransport._BaseSignBlob._get_transcoded_request( + http_options, request + ) + ) - body = _BaseIAMCredentialsRestTransport._BaseSignBlob._get_request_body_json(transcoded_request) + body = ( + _BaseIAMCredentialsRestTransport._BaseSignBlob._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = _BaseIAMCredentialsRestTransport._BaseSignBlob._get_query_params_json(transcoded_request) + query_params = ( + _BaseIAMCredentialsRestTransport._BaseSignBlob._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.iam.credentials_v1.IAMCredentialsClient.SignBlob", - extra = { + extra={ "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": "SignBlob", "httpRequest": http_request, @@ -692,7 +823,15 @@ def __call__(self, ) # Send the request - response = IAMCredentialsRestTransport._SignBlob._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = IAMCredentialsRestTransport._SignBlob._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -707,20 +846,24 @@ def __call__(self, resp = self._interceptor.post_sign_blob(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_sign_blob_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_sign_blob_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = common.SignBlobResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.iam.credentials_v1.IAMCredentialsClient.sign_blob", - extra = { + extra={ "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": "SignBlob", "metadata": http_response["headers"], @@ -729,7 +872,9 @@ def __call__(self, ) return resp - class _SignJwt(_BaseIAMCredentialsRestTransport._BaseSignJwt, IAMCredentialsRestStub): + class _SignJwt( + _BaseIAMCredentialsRestTransport._BaseSignJwt, IAMCredentialsRestStub + ): def __hash__(self): return hash("IAMCredentialsRestTransport.SignJwt") @@ -741,27 +886,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: common.SignJwtRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> common.SignJwtResponse: + def __call__( + self, + request: common.SignJwtRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.SignJwtResponse: r"""Call the sign jwt method over HTTP. Args: @@ -780,32 +927,48 @@ def __call__(self, """ - http_options = _BaseIAMCredentialsRestTransport._BaseSignJwt._get_http_options() + http_options = ( + _BaseIAMCredentialsRestTransport._BaseSignJwt._get_http_options() + ) request, metadata = self._interceptor.pre_sign_jwt(request, metadata) - transcoded_request = _BaseIAMCredentialsRestTransport._BaseSignJwt._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseIAMCredentialsRestTransport._BaseSignJwt._get_transcoded_request( + http_options, request + ) + ) - body = _BaseIAMCredentialsRestTransport._BaseSignJwt._get_request_body_json(transcoded_request) + body = _BaseIAMCredentialsRestTransport._BaseSignJwt._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseIAMCredentialsRestTransport._BaseSignJwt._get_query_params_json(transcoded_request) + query_params = ( + _BaseIAMCredentialsRestTransport._BaseSignJwt._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.iam.credentials_v1.IAMCredentialsClient.SignJwt", - extra = { + extra={ "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": "SignJwt", "httpRequest": http_request, @@ -814,7 +977,15 @@ def __call__(self, ) # Send the request - response = IAMCredentialsRestTransport._SignJwt._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = IAMCredentialsRestTransport._SignJwt._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -829,20 +1000,24 @@ def __call__(self, resp = self._interceptor.post_sign_jwt(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_sign_jwt_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_sign_jwt_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = common.SignJwtResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.iam.credentials_v1.IAMCredentialsClient.sign_jwt", - extra = { + extra={ "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": "SignJwt", "metadata": http_response["headers"], @@ -852,36 +1027,34 @@ def __call__(self, return resp @property - def generate_access_token(self) -> Callable[ - [common.GenerateAccessTokenRequest], - common.GenerateAccessTokenResponse]: + def generate_access_token( + self, + ) -> Callable[ + [common.GenerateAccessTokenRequest], common.GenerateAccessTokenResponse + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._GenerateAccessToken(self._session, self._host, self._interceptor) # type: ignore + return self._GenerateAccessToken(self._session, self._host, self._interceptor) # type: ignore @property - def generate_id_token(self) -> Callable[ - [common.GenerateIdTokenRequest], - common.GenerateIdTokenResponse]: + def generate_id_token( + self, + ) -> Callable[[common.GenerateIdTokenRequest], common.GenerateIdTokenResponse]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._GenerateIdToken(self._session, self._host, self._interceptor) # type: ignore + return self._GenerateIdToken(self._session, self._host, self._interceptor) # type: ignore @property - def sign_blob(self) -> Callable[ - [common.SignBlobRequest], - common.SignBlobResponse]: + def sign_blob(self) -> Callable[[common.SignBlobRequest], common.SignBlobResponse]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._SignBlob(self._session, self._host, self._interceptor) # type: ignore + return self._SignBlob(self._session, self._host, self._interceptor) # type: ignore @property - def sign_jwt(self) -> Callable[ - [common.SignJwtRequest], - common.SignJwtResponse]: + def sign_jwt(self) -> Callable[[common.SignJwtRequest], common.SignJwtResponse]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._SignJwt(self._session, self._host, self._interceptor) # type: ignore + return self._SignJwt(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -891,6 +1064,4 @@ def close(self): self._session.close() -__all__=( - 'IAMCredentialsRestTransport', -) +__all__ = ("IAMCredentialsRestTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/setup.py b/packages/gapic-generator/tests/integration/goldens/credentials/setup.py index 57e35ca4e0c0..5a37acf4b291 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/setup.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/setup.py @@ -17,23 +17,23 @@ import os import re -import setuptools # type: ignore +import setuptools # type: ignore package_root = os.path.abspath(os.path.dirname(__file__)) -name = 'google-iam-credentials' +name = "google-iam-credentials" description = "Google Iam Credentials API client library" version = None -with open(os.path.join(package_root, 'google/iam/credentials/gapic_version.py')) as fp: +with open(os.path.join(package_root, "google/iam/credentials/gapic_version.py")) as fp: version_candidates = re.findall( r"(?<=\")\d+\.\d+\.\d+[^\"\s]*(?=\")", fp.read(), ) - assert (len(version_candidates) == 1) + assert len(version_candidates) == 1 version = version_candidates[0] if version[0] == "0": @@ -51,8 +51,7 @@ "proto-plus >= 1.26.1, <2.0.0", "protobuf >= 6.33.5, < 8.0.0", ] -extras = { -} +extras = {} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-iam-credentials" package_root = os.path.abspath(os.path.dirname(__file__)) diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/__init__.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/__init__.py index c2c65d30a333..054846a4c5d7 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/__init__.py @@ -97,10 +97,12 @@ from .types.trigger import Transport from .types.trigger import Trigger -if hasattr(api_core, "check_python_version") and hasattr(api_core, "check_dependency_versions"): # pragma: NO COVER - api_core.check_python_version("google.cloud.eventarc_v1") # type: ignore - api_core.check_dependency_versions("google.cloud.eventarc_v1") # type: ignore -else: # pragma: NO COVER +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.cloud.eventarc_v1") # type: ignore + api_core.check_dependency_versions("google.cloud.eventarc_v1") # type: ignore +else: # pragma: NO COVER # An older version of api_core is installed which does not define the # functions above. We do equivalent checks manually. try: @@ -109,12 +111,14 @@ _py_version_str = sys.version.split()[0] _package_label = "google.cloud.eventarc_v1" if sys.version_info < (3, 10): - warnings.warn("You are using a non-supported Python version " + - f"({_py_version_str}). Google will not post any further " + - f"updates to {_package_label} supporting this Python version. " + - "Please upgrade to the latest Python version, or at " + - f"least to Python 3.10, and then update {_package_label}.", - FutureWarning) + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.10, and then update {_package_label}.", + FutureWarning, + ) def parse_version_to_tuple(version_string: str): """Safely converts a semantic version string to a comparable tuple of integers. @@ -152,97 +156,101 @@ def _get_version(dependency_name): _recommendation = " (we recommend 7.x)" (_version_used, _version_used_string) = _get_version(_dependency_package) if _version_used and _version_used < _next_supported_version_tuple: - warnings.warn(f"Package {_package_label} depends on " + - f"{_dependency_package}, currently installed at version " + - f"{_version_used_string}. Future updates to " + - f"{_package_label} will require {_dependency_package} at " + - f"version {_next_supported_version} or higher{_recommendation}." + - " Please ensure " + - "that either (a) your Python environment doesn't pin the " + - f"version of {_dependency_package}, so that updates to " + - f"{_package_label} can require the higher version, or " + - "(b) you manually update your Python environment to use at " + - f"least version {_next_supported_version} of " + - f"{_dependency_package}.", - FutureWarning) + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) except Exception: - warnings.warn("Could not determine the version of Python " + - "currently being used. To continue receiving " + - "updates for {_package_label}, ensure you are " + - "using a supported version of Python; see " + - "https://devguide.python.org/versions/") + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) __all__ = ( - 'EventarcAsyncClient', -'Channel', -'ChannelConnection', -'CloudRun', -'CreateChannelConnectionRequest', -'CreateChannelRequest', -'CreateEnrollmentRequest', -'CreateGoogleApiSourceRequest', -'CreateMessageBusRequest', -'CreatePipelineRequest', -'CreateTriggerRequest', -'DeleteChannelConnectionRequest', -'DeleteChannelRequest', -'DeleteEnrollmentRequest', -'DeleteGoogleApiSourceRequest', -'DeleteMessageBusRequest', -'DeletePipelineRequest', -'DeleteTriggerRequest', -'Destination', -'Enrollment', -'EventFilter', -'EventType', -'EventarcClient', -'FilteringAttribute', -'GKE', -'GetChannelConnectionRequest', -'GetChannelRequest', -'GetEnrollmentRequest', -'GetGoogleApiSourceRequest', -'GetGoogleChannelConfigRequest', -'GetMessageBusRequest', -'GetPipelineRequest', -'GetProviderRequest', -'GetTriggerRequest', -'GoogleApiSource', -'GoogleChannelConfig', -'HttpEndpoint', -'ListChannelConnectionsRequest', -'ListChannelConnectionsResponse', -'ListChannelsRequest', -'ListChannelsResponse', -'ListEnrollmentsRequest', -'ListEnrollmentsResponse', -'ListGoogleApiSourcesRequest', -'ListGoogleApiSourcesResponse', -'ListMessageBusEnrollmentsRequest', -'ListMessageBusEnrollmentsResponse', -'ListMessageBusesRequest', -'ListMessageBusesResponse', -'ListPipelinesRequest', -'ListPipelinesResponse', -'ListProvidersRequest', -'ListProvidersResponse', -'ListTriggersRequest', -'ListTriggersResponse', -'LoggingConfig', -'MessageBus', -'NetworkConfig', -'OperationMetadata', -'Pipeline', -'Provider', -'Pubsub', -'StateCondition', -'Transport', -'Trigger', -'UpdateChannelRequest', -'UpdateEnrollmentRequest', -'UpdateGoogleApiSourceRequest', -'UpdateGoogleChannelConfigRequest', -'UpdateMessageBusRequest', -'UpdatePipelineRequest', -'UpdateTriggerRequest', + "EventarcAsyncClient", + "Channel", + "ChannelConnection", + "CloudRun", + "CreateChannelConnectionRequest", + "CreateChannelRequest", + "CreateEnrollmentRequest", + "CreateGoogleApiSourceRequest", + "CreateMessageBusRequest", + "CreatePipelineRequest", + "CreateTriggerRequest", + "DeleteChannelConnectionRequest", + "DeleteChannelRequest", + "DeleteEnrollmentRequest", + "DeleteGoogleApiSourceRequest", + "DeleteMessageBusRequest", + "DeletePipelineRequest", + "DeleteTriggerRequest", + "Destination", + "Enrollment", + "EventFilter", + "EventType", + "EventarcClient", + "FilteringAttribute", + "GKE", + "GetChannelConnectionRequest", + "GetChannelRequest", + "GetEnrollmentRequest", + "GetGoogleApiSourceRequest", + "GetGoogleChannelConfigRequest", + "GetMessageBusRequest", + "GetPipelineRequest", + "GetProviderRequest", + "GetTriggerRequest", + "GoogleApiSource", + "GoogleChannelConfig", + "HttpEndpoint", + "ListChannelConnectionsRequest", + "ListChannelConnectionsResponse", + "ListChannelsRequest", + "ListChannelsResponse", + "ListEnrollmentsRequest", + "ListEnrollmentsResponse", + "ListGoogleApiSourcesRequest", + "ListGoogleApiSourcesResponse", + "ListMessageBusEnrollmentsRequest", + "ListMessageBusEnrollmentsResponse", + "ListMessageBusesRequest", + "ListMessageBusesResponse", + "ListPipelinesRequest", + "ListPipelinesResponse", + "ListProvidersRequest", + "ListProvidersResponse", + "ListTriggersRequest", + "ListTriggersResponse", + "LoggingConfig", + "MessageBus", + "NetworkConfig", + "OperationMetadata", + "Pipeline", + "Provider", + "Pubsub", + "StateCondition", + "Transport", + "Trigger", + "UpdateChannelRequest", + "UpdateEnrollmentRequest", + "UpdateGoogleApiSourceRequest", + "UpdateGoogleChannelConfigRequest", + "UpdateMessageBusRequest", + "UpdatePipelineRequest", + "UpdateTriggerRequest", ) diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/async_client.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/async_client.py index 442e33c0ee71..0756803aff06 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/async_client.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/async_client.py @@ -16,7 +16,18 @@ import logging as std_logging from collections import OrderedDict import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union +from typing import ( + Dict, + Callable, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) from google.cloud.eventarc_v1 import gapic_version as package_version @@ -24,8 +35,8 @@ from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf @@ -46,7 +57,9 @@ from google.cloud.eventarc_v1.types import google_api_source from google.cloud.eventarc_v1.types import google_api_source as gce_google_api_source from google.cloud.eventarc_v1.types import google_channel_config -from google.cloud.eventarc_v1.types import google_channel_config as gce_google_channel_config +from google.cloud.eventarc_v1.types import ( + google_channel_config as gce_google_channel_config, +) from google.cloud.eventarc_v1.types import logging_config from google.cloud.eventarc_v1.types import message_bus from google.cloud.eventarc_v1.types import message_bus as gce_message_bus @@ -54,10 +67,10 @@ from google.cloud.eventarc_v1.types import pipeline as gce_pipeline from google.cloud.eventarc_v1.types import trigger from google.cloud.eventarc_v1.types import trigger as gce_trigger -from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.api_core.operation as operation # type: ignore import google.api_core.operation_async as operation_async # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore @@ -68,12 +81,14 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) + class EventarcAsyncClient: """Eventarc allows users to subscribe to various events that are provided by Google Cloud services and forward them to supported @@ -92,7 +107,9 @@ class EventarcAsyncClient: channel_path = staticmethod(EventarcClient.channel_path) parse_channel_path = staticmethod(EventarcClient.parse_channel_path) channel_connection_path = staticmethod(EventarcClient.channel_connection_path) - parse_channel_connection_path = staticmethod(EventarcClient.parse_channel_connection_path) + parse_channel_connection_path = staticmethod( + EventarcClient.parse_channel_connection_path + ) cloud_function_path = staticmethod(EventarcClient.cloud_function_path) parse_cloud_function_path = staticmethod(EventarcClient.parse_cloud_function_path) crypto_key_path = staticmethod(EventarcClient.crypto_key_path) @@ -100,13 +117,19 @@ class EventarcAsyncClient: enrollment_path = staticmethod(EventarcClient.enrollment_path) parse_enrollment_path = staticmethod(EventarcClient.parse_enrollment_path) google_api_source_path = staticmethod(EventarcClient.google_api_source_path) - parse_google_api_source_path = staticmethod(EventarcClient.parse_google_api_source_path) + parse_google_api_source_path = staticmethod( + EventarcClient.parse_google_api_source_path + ) google_channel_config_path = staticmethod(EventarcClient.google_channel_config_path) - parse_google_channel_config_path = staticmethod(EventarcClient.parse_google_channel_config_path) + parse_google_channel_config_path = staticmethod( + EventarcClient.parse_google_channel_config_path + ) message_bus_path = staticmethod(EventarcClient.message_bus_path) parse_message_bus_path = staticmethod(EventarcClient.parse_message_bus_path) network_attachment_path = staticmethod(EventarcClient.network_attachment_path) - parse_network_attachment_path = staticmethod(EventarcClient.parse_network_attachment_path) + parse_network_attachment_path = staticmethod( + EventarcClient.parse_network_attachment_path + ) pipeline_path = staticmethod(EventarcClient.pipeline_path) parse_pipeline_path = staticmethod(EventarcClient.parse_pipeline_path) provider_path = staticmethod(EventarcClient.provider_path) @@ -121,12 +144,18 @@ class EventarcAsyncClient: parse_trigger_path = staticmethod(EventarcClient.parse_trigger_path) workflow_path = staticmethod(EventarcClient.workflow_path) parse_workflow_path = staticmethod(EventarcClient.parse_workflow_path) - common_billing_account_path = staticmethod(EventarcClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(EventarcClient.parse_common_billing_account_path) + common_billing_account_path = staticmethod( + EventarcClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + EventarcClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(EventarcClient.common_folder_path) parse_common_folder_path = staticmethod(EventarcClient.parse_common_folder_path) common_organization_path = staticmethod(EventarcClient.common_organization_path) - parse_common_organization_path = staticmethod(EventarcClient.parse_common_organization_path) + parse_common_organization_path = staticmethod( + EventarcClient.parse_common_organization_path + ) common_project_path = staticmethod(EventarcClient.common_project_path) parse_common_project_path = staticmethod(EventarcClient.parse_common_project_path) common_location_path = staticmethod(EventarcClient.common_location_path) @@ -145,9 +174,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: EventarcAsyncClient: The constructed client. """ - sa_info_func = ( - EventarcClient.from_service_account_info.__func__ # type: ignore - ) + sa_info_func = EventarcClient.from_service_account_info.__func__ # type: ignore return sa_info_func(EventarcAsyncClient, info, *args, **kwargs) @classmethod @@ -164,15 +191,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: EventarcAsyncClient: The constructed client. """ - sa_file_func = ( - EventarcClient.from_service_account_file.__func__ # type: ignore - ) + sa_file_func = EventarcClient.from_service_account_file.__func__ # type: ignore return sa_file_func(EventarcAsyncClient, filename, *args, **kwargs) from_service_account_json = from_service_account_file @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): """Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -235,12 +262,16 @@ def universe_domain(self) -> str: get_transport_class = EventarcClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, EventarcTransport, Callable[..., EventarcTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, EventarcTransport, Callable[..., EventarcTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the eventarc async client. Args: @@ -298,31 +329,39 @@ def __init__(self, *, transport=transport, client_options=client_options, client_info=client_info, - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.eventarc_v1.EventarcAsyncClient`.", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { "serviceName": "google.cloud.eventarc.v1.Eventarc", "credentialsType": None, - } + }, ) - async def get_trigger(self, - request: Optional[Union[eventarc.GetTriggerRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> trigger.Trigger: + async def get_trigger( + self, + request: Optional[Union[eventarc.GetTriggerRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> trigger.Trigger: r"""Get a single trigger. .. code-block:: python @@ -380,10 +419,14 @@ async def sample_get_trigger(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -397,14 +440,14 @@ async def sample_get_trigger(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_trigger] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_trigger + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -421,14 +464,15 @@ async def sample_get_trigger(): # Done; return the response. return response - async def list_triggers(self, - request: Optional[Union[eventarc.ListTriggersRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListTriggersAsyncPager: + async def list_triggers( + self, + request: Optional[Union[eventarc.ListTriggersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListTriggersAsyncPager: r"""List triggers. .. code-block:: python @@ -489,10 +533,14 @@ async def sample_list_triggers(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -506,14 +554,14 @@ async def sample_list_triggers(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_triggers] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_triggers + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -541,16 +589,17 @@ async def sample_list_triggers(): # Done; return the response. return response - async def create_trigger(self, - request: Optional[Union[eventarc.CreateTriggerRequest, dict]] = None, - *, - parent: Optional[str] = None, - trigger: Optional[gce_trigger.Trigger] = None, - trigger_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def create_trigger( + self, + request: Optional[Union[eventarc.CreateTriggerRequest, dict]] = None, + *, + parent: Optional[str] = None, + trigger: Optional[gce_trigger.Trigger] = None, + trigger_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Create a new trigger in a particular project and location. @@ -637,10 +686,14 @@ async def sample_create_trigger(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, trigger, trigger_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -658,14 +711,14 @@ async def sample_create_trigger(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_trigger] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_trigger + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -690,16 +743,17 @@ async def sample_create_trigger(): # Done; return the response. return response - async def update_trigger(self, - request: Optional[Union[eventarc.UpdateTriggerRequest, dict]] = None, - *, - trigger: Optional[gce_trigger.Trigger] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - allow_missing: Optional[bool] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def update_trigger( + self, + request: Optional[Union[eventarc.UpdateTriggerRequest, dict]] = None, + *, + trigger: Optional[gce_trigger.Trigger] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + allow_missing: Optional[bool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Update a single trigger. .. code-block:: python @@ -778,10 +832,14 @@ async def sample_update_trigger(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [trigger, update_mask, allow_missing] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -799,14 +857,16 @@ async def sample_update_trigger(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_trigger] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_trigger + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("trigger.name", request.trigger.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("trigger.name", request.trigger.name),) + ), ) # Validate the universe domain. @@ -831,15 +891,16 @@ async def sample_update_trigger(): # Done; return the response. return response - async def delete_trigger(self, - request: Optional[Union[eventarc.DeleteTriggerRequest, dict]] = None, - *, - name: Optional[str] = None, - allow_missing: Optional[bool] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def delete_trigger( + self, + request: Optional[Union[eventarc.DeleteTriggerRequest, dict]] = None, + *, + name: Optional[str] = None, + allow_missing: Optional[bool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Delete a single trigger. .. code-block:: python @@ -912,10 +973,14 @@ async def sample_delete_trigger(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, allow_missing] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -931,14 +996,14 @@ async def sample_delete_trigger(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_trigger] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_trigger + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -963,14 +1028,15 @@ async def sample_delete_trigger(): # Done; return the response. return response - async def get_channel(self, - request: Optional[Union[eventarc.GetChannelRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> channel.Channel: + async def get_channel( + self, + request: Optional[Union[eventarc.GetChannelRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> channel.Channel: r"""Get a single Channel. .. code-block:: python @@ -1034,10 +1100,14 @@ async def sample_get_channel(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1051,14 +1121,14 @@ async def sample_get_channel(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_channel] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_channel + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1075,14 +1145,15 @@ async def sample_get_channel(): # Done; return the response. return response - async def list_channels(self, - request: Optional[Union[eventarc.ListChannelsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListChannelsAsyncPager: + async def list_channels( + self, + request: Optional[Union[eventarc.ListChannelsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListChannelsAsyncPager: r"""List channels. .. code-block:: python @@ -1143,10 +1214,14 @@ async def sample_list_channels(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1160,14 +1235,14 @@ async def sample_list_channels(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_channels] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_channels + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1195,16 +1270,17 @@ async def sample_list_channels(): # Done; return the response. return response - async def create_channel(self, - request: Optional[Union[eventarc.CreateChannelRequest, dict]] = None, - *, - parent: Optional[str] = None, - channel: Optional[gce_channel.Channel] = None, - channel_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def create_channel( + self, + request: Optional[Union[eventarc.CreateChannelRequest, dict]] = None, + *, + parent: Optional[str] = None, + channel: Optional[gce_channel.Channel] = None, + channel_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Create a new channel in a particular project and location. @@ -1291,10 +1367,14 @@ async def sample_create_channel(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, channel, channel_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1312,14 +1392,14 @@ async def sample_create_channel(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_channel_] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_channel_ + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1344,15 +1424,16 @@ async def sample_create_channel(): # Done; return the response. return response - async def update_channel(self, - request: Optional[Union[eventarc.UpdateChannelRequest, dict]] = None, - *, - channel: Optional[gce_channel.Channel] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def update_channel( + self, + request: Optional[Union[eventarc.UpdateChannelRequest, dict]] = None, + *, + channel: Optional[gce_channel.Channel] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Update a single channel. .. code-block:: python @@ -1426,10 +1507,14 @@ async def sample_update_channel(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [channel, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1445,14 +1530,16 @@ async def sample_update_channel(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_channel] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_channel + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("channel.name", request.channel.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("channel.name", request.channel.name),) + ), ) # Validate the universe domain. @@ -1477,14 +1564,15 @@ async def sample_update_channel(): # Done; return the response. return response - async def delete_channel(self, - request: Optional[Union[eventarc.DeleteChannelRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def delete_channel( + self, + request: Optional[Union[eventarc.DeleteChannelRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Delete a single channel. .. code-block:: python @@ -1552,10 +1640,14 @@ async def sample_delete_channel(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1569,14 +1661,14 @@ async def sample_delete_channel(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_channel] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_channel + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1601,14 +1693,15 @@ async def sample_delete_channel(): # Done; return the response. return response - async def get_provider(self, - request: Optional[Union[eventarc.GetProviderRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> discovery.Provider: + async def get_provider( + self, + request: Optional[Union[eventarc.GetProviderRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> discovery.Provider: r"""Get a single Provider. .. code-block:: python @@ -1666,10 +1759,14 @@ async def sample_get_provider(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1683,14 +1780,14 @@ async def sample_get_provider(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_provider] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_provider + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1707,14 +1804,15 @@ async def sample_get_provider(): # Done; return the response. return response - async def list_providers(self, - request: Optional[Union[eventarc.ListProvidersRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListProvidersAsyncPager: + async def list_providers( + self, + request: Optional[Union[eventarc.ListProvidersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListProvidersAsyncPager: r"""List providers. .. code-block:: python @@ -1775,10 +1873,14 @@ async def sample_list_providers(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1792,14 +1894,14 @@ async def sample_list_providers(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_providers] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_providers + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1827,14 +1929,15 @@ async def sample_list_providers(): # Done; return the response. return response - async def get_channel_connection(self, - request: Optional[Union[eventarc.GetChannelConnectionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> channel_connection.ChannelConnection: + async def get_channel_connection( + self, + request: Optional[Union[eventarc.GetChannelConnectionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> channel_connection.ChannelConnection: r"""Get a single ChannelConnection. .. code-block:: python @@ -1897,10 +2000,14 @@ async def sample_get_channel_connection(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1914,14 +2021,14 @@ async def sample_get_channel_connection(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_channel_connection] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_channel_connection + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1938,14 +2045,15 @@ async def sample_get_channel_connection(): # Done; return the response. return response - async def list_channel_connections(self, - request: Optional[Union[eventarc.ListChannelConnectionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListChannelConnectionsAsyncPager: + async def list_channel_connections( + self, + request: Optional[Union[eventarc.ListChannelConnectionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListChannelConnectionsAsyncPager: r"""List channel connections. .. code-block:: python @@ -2007,10 +2115,14 @@ async def sample_list_channel_connections(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2024,14 +2136,14 @@ async def sample_list_channel_connections(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_channel_connections] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_channel_connections + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2059,16 +2171,17 @@ async def sample_list_channel_connections(): # Done; return the response. return response - async def create_channel_connection(self, - request: Optional[Union[eventarc.CreateChannelConnectionRequest, dict]] = None, - *, - parent: Optional[str] = None, - channel_connection: Optional[gce_channel_connection.ChannelConnection] = None, - channel_connection_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def create_channel_connection( + self, + request: Optional[Union[eventarc.CreateChannelConnectionRequest, dict]] = None, + *, + parent: Optional[str] = None, + channel_connection: Optional[gce_channel_connection.ChannelConnection] = None, + channel_connection_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Create a new ChannelConnection in a particular project and location. @@ -2156,10 +2269,14 @@ async def sample_create_channel_connection(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, channel_connection, channel_connection_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2177,14 +2294,14 @@ async def sample_create_channel_connection(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_channel_connection] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_channel_connection + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2209,14 +2326,15 @@ async def sample_create_channel_connection(): # Done; return the response. return response - async def delete_channel_connection(self, - request: Optional[Union[eventarc.DeleteChannelConnectionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def delete_channel_connection( + self, + request: Optional[Union[eventarc.DeleteChannelConnectionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Delete a single ChannelConnection. .. code-block:: python @@ -2283,10 +2401,14 @@ async def sample_delete_channel_connection(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2300,14 +2422,14 @@ async def sample_delete_channel_connection(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_channel_connection] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_channel_connection + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2332,14 +2454,15 @@ async def sample_delete_channel_connection(): # Done; return the response. return response - async def get_google_channel_config(self, - request: Optional[Union[eventarc.GetGoogleChannelConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> google_channel_config.GoogleChannelConfig: + async def get_google_channel_config( + self, + request: Optional[Union[eventarc.GetGoogleChannelConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> google_channel_config.GoogleChannelConfig: r"""Get a GoogleChannelConfig. The name of the GoogleChannelConfig in the response is ALWAYS coded with projectID. @@ -2405,10 +2528,14 @@ async def sample_get_google_channel_config(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2422,14 +2549,14 @@ async def sample_get_google_channel_config(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_google_channel_config] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_google_channel_config + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2446,15 +2573,20 @@ async def sample_get_google_channel_config(): # Done; return the response. return response - async def update_google_channel_config(self, - request: Optional[Union[eventarc.UpdateGoogleChannelConfigRequest, dict]] = None, - *, - google_channel_config: Optional[gce_google_channel_config.GoogleChannelConfig] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gce_google_channel_config.GoogleChannelConfig: + async def update_google_channel_config( + self, + request: Optional[ + Union[eventarc.UpdateGoogleChannelConfigRequest, dict] + ] = None, + *, + google_channel_config: Optional[ + gce_google_channel_config.GoogleChannelConfig + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gce_google_channel_config.GoogleChannelConfig: r"""Update a single GoogleChannelConfig .. code-block:: python @@ -2528,10 +2660,14 @@ async def sample_update_google_channel_config(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [google_channel_config, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2547,14 +2683,16 @@ async def sample_update_google_channel_config(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_google_channel_config] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_google_channel_config + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("google_channel_config.name", request.google_channel_config.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("google_channel_config.name", request.google_channel_config.name),) + ), ) # Validate the universe domain. @@ -2571,14 +2709,15 @@ async def sample_update_google_channel_config(): # Done; return the response. return response - async def get_message_bus(self, - request: Optional[Union[eventarc.GetMessageBusRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> message_bus.MessageBus: + async def get_message_bus( + self, + request: Optional[Union[eventarc.GetMessageBusRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> message_bus.MessageBus: r"""Get a single MessageBus. .. code-block:: python @@ -2642,10 +2781,14 @@ async def sample_get_message_bus(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2659,14 +2802,14 @@ async def sample_get_message_bus(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_message_bus] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_message_bus + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2683,14 +2826,15 @@ async def sample_get_message_bus(): # Done; return the response. return response - async def list_message_buses(self, - request: Optional[Union[eventarc.ListMessageBusesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListMessageBusesAsyncPager: + async def list_message_buses( + self, + request: Optional[Union[eventarc.ListMessageBusesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMessageBusesAsyncPager: r"""List message buses. .. code-block:: python @@ -2751,10 +2895,14 @@ async def sample_list_message_buses(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2768,14 +2916,14 @@ async def sample_list_message_buses(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_message_buses] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_message_buses + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2803,14 +2951,17 @@ async def sample_list_message_buses(): # Done; return the response. return response - async def list_message_bus_enrollments(self, - request: Optional[Union[eventarc.ListMessageBusEnrollmentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListMessageBusEnrollmentsAsyncPager: + async def list_message_bus_enrollments( + self, + request: Optional[ + Union[eventarc.ListMessageBusEnrollmentsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMessageBusEnrollmentsAsyncPager: r"""List message bus enrollments. .. code-block:: python @@ -2872,10 +3023,14 @@ async def sample_list_message_bus_enrollments(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2889,14 +3044,14 @@ async def sample_list_message_bus_enrollments(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_message_bus_enrollments] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_message_bus_enrollments + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2924,16 +3079,17 @@ async def sample_list_message_bus_enrollments(): # Done; return the response. return response - async def create_message_bus(self, - request: Optional[Union[eventarc.CreateMessageBusRequest, dict]] = None, - *, - parent: Optional[str] = None, - message_bus: Optional[gce_message_bus.MessageBus] = None, - message_bus_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def create_message_bus( + self, + request: Optional[Union[eventarc.CreateMessageBusRequest, dict]] = None, + *, + parent: Optional[str] = None, + message_bus: Optional[gce_message_bus.MessageBus] = None, + message_bus_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Create a new MessageBus in a particular project and location. @@ -3015,10 +3171,14 @@ async def sample_create_message_bus(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, message_bus, message_bus_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3036,14 +3196,14 @@ async def sample_create_message_bus(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_message_bus] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_message_bus + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -3068,15 +3228,16 @@ async def sample_create_message_bus(): # Done; return the response. return response - async def update_message_bus(self, - request: Optional[Union[eventarc.UpdateMessageBusRequest, dict]] = None, - *, - message_bus: Optional[gce_message_bus.MessageBus] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def update_message_bus( + self, + request: Optional[Union[eventarc.UpdateMessageBusRequest, dict]] = None, + *, + message_bus: Optional[gce_message_bus.MessageBus] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Update a single message bus. .. code-block:: python @@ -3152,10 +3313,14 @@ async def sample_update_message_bus(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [message_bus, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3171,14 +3336,16 @@ async def sample_update_message_bus(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_message_bus] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_message_bus + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("message_bus.name", request.message_bus.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("message_bus.name", request.message_bus.name),) + ), ) # Validate the universe domain. @@ -3203,15 +3370,16 @@ async def sample_update_message_bus(): # Done; return the response. return response - async def delete_message_bus(self, - request: Optional[Union[eventarc.DeleteMessageBusRequest, dict]] = None, - *, - name: Optional[str] = None, - etag: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def delete_message_bus( + self, + request: Optional[Union[eventarc.DeleteMessageBusRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Delete a single message bus. .. code-block:: python @@ -3286,10 +3454,14 @@ async def sample_delete_message_bus(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, etag] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3305,14 +3477,14 @@ async def sample_delete_message_bus(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_message_bus] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_message_bus + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3337,14 +3509,15 @@ async def sample_delete_message_bus(): # Done; return the response. return response - async def get_enrollment(self, - request: Optional[Union[eventarc.GetEnrollmentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> enrollment.Enrollment: + async def get_enrollment( + self, + request: Optional[Union[eventarc.GetEnrollmentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> enrollment.Enrollment: r"""Get a single Enrollment. .. code-block:: python @@ -3406,10 +3579,14 @@ async def sample_get_enrollment(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3423,14 +3600,14 @@ async def sample_get_enrollment(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_enrollment] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_enrollment + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3447,14 +3624,15 @@ async def sample_get_enrollment(): # Done; return the response. return response - async def list_enrollments(self, - request: Optional[Union[eventarc.ListEnrollmentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListEnrollmentsAsyncPager: + async def list_enrollments( + self, + request: Optional[Union[eventarc.ListEnrollmentsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListEnrollmentsAsyncPager: r"""List Enrollments. .. code-block:: python @@ -3515,10 +3693,14 @@ async def sample_list_enrollments(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3532,14 +3714,14 @@ async def sample_list_enrollments(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_enrollments] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_enrollments + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -3567,16 +3749,17 @@ async def sample_list_enrollments(): # Done; return the response. return response - async def create_enrollment(self, - request: Optional[Union[eventarc.CreateEnrollmentRequest, dict]] = None, - *, - parent: Optional[str] = None, - enrollment: Optional[gce_enrollment.Enrollment] = None, - enrollment_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def create_enrollment( + self, + request: Optional[Union[eventarc.CreateEnrollmentRequest, dict]] = None, + *, + parent: Optional[str] = None, + enrollment: Optional[gce_enrollment.Enrollment] = None, + enrollment_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Create a new Enrollment in a particular project and location. @@ -3663,10 +3846,14 @@ async def sample_create_enrollment(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, enrollment, enrollment_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3684,14 +3871,14 @@ async def sample_create_enrollment(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_enrollment] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_enrollment + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -3716,15 +3903,16 @@ async def sample_create_enrollment(): # Done; return the response. return response - async def update_enrollment(self, - request: Optional[Union[eventarc.UpdateEnrollmentRequest, dict]] = None, - *, - enrollment: Optional[gce_enrollment.Enrollment] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def update_enrollment( + self, + request: Optional[Union[eventarc.UpdateEnrollmentRequest, dict]] = None, + *, + enrollment: Optional[gce_enrollment.Enrollment] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Update a single Enrollment. .. code-block:: python @@ -3805,10 +3993,14 @@ async def sample_update_enrollment(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [enrollment, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3824,14 +4016,16 @@ async def sample_update_enrollment(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_enrollment] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_enrollment + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("enrollment.name", request.enrollment.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("enrollment.name", request.enrollment.name),) + ), ) # Validate the universe domain. @@ -3856,15 +4050,16 @@ async def sample_update_enrollment(): # Done; return the response. return response - async def delete_enrollment(self, - request: Optional[Union[eventarc.DeleteEnrollmentRequest, dict]] = None, - *, - name: Optional[str] = None, - etag: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def delete_enrollment( + self, + request: Optional[Union[eventarc.DeleteEnrollmentRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Delete a single Enrollment. .. code-block:: python @@ -3938,10 +4133,14 @@ async def sample_delete_enrollment(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, etag] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3957,14 +4156,14 @@ async def sample_delete_enrollment(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_enrollment] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_enrollment + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3989,14 +4188,15 @@ async def sample_delete_enrollment(): # Done; return the response. return response - async def get_pipeline(self, - request: Optional[Union[eventarc.GetPipelineRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pipeline.Pipeline: + async def get_pipeline( + self, + request: Optional[Union[eventarc.GetPipelineRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pipeline.Pipeline: r"""Get a single Pipeline. .. code-block:: python @@ -4054,10 +4254,14 @@ async def sample_get_pipeline(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4071,14 +4275,14 @@ async def sample_get_pipeline(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_pipeline] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_pipeline + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -4095,14 +4299,15 @@ async def sample_get_pipeline(): # Done; return the response. return response - async def list_pipelines(self, - request: Optional[Union[eventarc.ListPipelinesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListPipelinesAsyncPager: + async def list_pipelines( + self, + request: Optional[Union[eventarc.ListPipelinesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPipelinesAsyncPager: r"""List pipelines. .. code-block:: python @@ -4164,10 +4369,14 @@ async def sample_list_pipelines(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4181,14 +4390,14 @@ async def sample_list_pipelines(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_pipelines] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_pipelines + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -4216,16 +4425,17 @@ async def sample_list_pipelines(): # Done; return the response. return response - async def create_pipeline(self, - request: Optional[Union[eventarc.CreatePipelineRequest, dict]] = None, - *, - parent: Optional[str] = None, - pipeline: Optional[gce_pipeline.Pipeline] = None, - pipeline_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def create_pipeline( + self, + request: Optional[Union[eventarc.CreatePipelineRequest, dict]] = None, + *, + parent: Optional[str] = None, + pipeline: Optional[gce_pipeline.Pipeline] = None, + pipeline_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Create a new Pipeline in a particular project and location. @@ -4309,10 +4519,14 @@ async def sample_create_pipeline(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, pipeline, pipeline_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4330,14 +4544,14 @@ async def sample_create_pipeline(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_pipeline] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_pipeline + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -4362,15 +4576,16 @@ async def sample_create_pipeline(): # Done; return the response. return response - async def update_pipeline(self, - request: Optional[Union[eventarc.UpdatePipelineRequest, dict]] = None, - *, - pipeline: Optional[gce_pipeline.Pipeline] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def update_pipeline( + self, + request: Optional[Union[eventarc.UpdatePipelineRequest, dict]] = None, + *, + pipeline: Optional[gce_pipeline.Pipeline] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Update a single pipeline. .. code-block:: python @@ -4446,10 +4661,14 @@ async def sample_update_pipeline(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [pipeline, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4465,14 +4684,16 @@ async def sample_update_pipeline(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_pipeline] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_pipeline + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("pipeline.name", request.pipeline.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("pipeline.name", request.pipeline.name),) + ), ) # Validate the universe domain. @@ -4497,15 +4718,16 @@ async def sample_update_pipeline(): # Done; return the response. return response - async def delete_pipeline(self, - request: Optional[Union[eventarc.DeletePipelineRequest, dict]] = None, - *, - name: Optional[str] = None, - etag: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def delete_pipeline( + self, + request: Optional[Union[eventarc.DeletePipelineRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Delete a single pipeline. .. code-block:: python @@ -4578,10 +4800,14 @@ async def sample_delete_pipeline(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, etag] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4597,14 +4823,14 @@ async def sample_delete_pipeline(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_pipeline] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_pipeline + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -4629,14 +4855,15 @@ async def sample_delete_pipeline(): # Done; return the response. return response - async def get_google_api_source(self, - request: Optional[Union[eventarc.GetGoogleApiSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> google_api_source.GoogleApiSource: + async def get_google_api_source( + self, + request: Optional[Union[eventarc.GetGoogleApiSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> google_api_source.GoogleApiSource: r"""Get a single GoogleApiSource. .. code-block:: python @@ -4695,10 +4922,14 @@ async def sample_get_google_api_source(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4712,14 +4943,14 @@ async def sample_get_google_api_source(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_google_api_source] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_google_api_source + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -4736,14 +4967,15 @@ async def sample_get_google_api_source(): # Done; return the response. return response - async def list_google_api_sources(self, - request: Optional[Union[eventarc.ListGoogleApiSourcesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListGoogleApiSourcesAsyncPager: + async def list_google_api_sources( + self, + request: Optional[Union[eventarc.ListGoogleApiSourcesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListGoogleApiSourcesAsyncPager: r"""List GoogleApiSources. .. code-block:: python @@ -4805,10 +5037,14 @@ async def sample_list_google_api_sources(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4822,14 +5058,14 @@ async def sample_list_google_api_sources(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_google_api_sources] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_google_api_sources + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -4857,16 +5093,17 @@ async def sample_list_google_api_sources(): # Done; return the response. return response - async def create_google_api_source(self, - request: Optional[Union[eventarc.CreateGoogleApiSourceRequest, dict]] = None, - *, - parent: Optional[str] = None, - google_api_source: Optional[gce_google_api_source.GoogleApiSource] = None, - google_api_source_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def create_google_api_source( + self, + request: Optional[Union[eventarc.CreateGoogleApiSourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + google_api_source: Optional[gce_google_api_source.GoogleApiSource] = None, + google_api_source_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Create a new GoogleApiSource in a particular project and location. @@ -4954,10 +5191,14 @@ async def sample_create_google_api_source(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, google_api_source, google_api_source_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4975,14 +5216,14 @@ async def sample_create_google_api_source(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_google_api_source] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_google_api_source + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -5007,15 +5248,16 @@ async def sample_create_google_api_source(): # Done; return the response. return response - async def update_google_api_source(self, - request: Optional[Union[eventarc.UpdateGoogleApiSourceRequest, dict]] = None, - *, - google_api_source: Optional[gce_google_api_source.GoogleApiSource] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def update_google_api_source( + self, + request: Optional[Union[eventarc.UpdateGoogleApiSourceRequest, dict]] = None, + *, + google_api_source: Optional[gce_google_api_source.GoogleApiSource] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Update a single GoogleApiSource. .. code-block:: python @@ -5095,10 +5337,14 @@ async def sample_update_google_api_source(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [google_api_source, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -5114,14 +5360,16 @@ async def sample_update_google_api_source(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_google_api_source] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_google_api_source + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("google_api_source.name", request.google_api_source.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("google_api_source.name", request.google_api_source.name),) + ), ) # Validate the universe domain. @@ -5146,15 +5394,16 @@ async def sample_update_google_api_source(): # Done; return the response. return response - async def delete_google_api_source(self, - request: Optional[Union[eventarc.DeleteGoogleApiSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - etag: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def delete_google_api_source( + self, + request: Optional[Union[eventarc.DeleteGoogleApiSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Delete a single GoogleApiSource. .. code-block:: python @@ -5228,10 +5477,14 @@ async def sample_delete_google_api_source(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, etag] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -5247,14 +5500,14 @@ async def sample_delete_google_api_source(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_google_api_source] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_google_api_source + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -5321,8 +5574,7 @@ async def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -5330,7 +5582,11 @@ async def list_operations( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -5377,8 +5633,7 @@ async def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -5386,7 +5641,11 @@ async def get_operation( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -5437,15 +5696,19 @@ async def delete_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) async def cancel_operation( self, @@ -5492,15 +5755,19 @@ async def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) async def set_iam_policy( self, @@ -5611,7 +5878,8 @@ async def set_iam_policy( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request_pb.resource),)), + (("resource", request_pb.resource),) + ), ) # Validate the universe domain. @@ -5619,7 +5887,11 @@ async def set_iam_policy( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -5734,7 +6006,8 @@ async def get_iam_policy( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request_pb.resource),)), + (("resource", request_pb.resource),) + ), ) # Validate the universe domain. @@ -5742,7 +6015,11 @@ async def get_iam_policy( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -5789,13 +6066,16 @@ async def test_iam_permissions( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.test_iam_permissions] + rpc = self.transport._wrapped_methods[ + self._client._transport.test_iam_permissions + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request_pb.resource),)), + (("resource", request_pb.resource),) + ), ) # Validate the universe domain. @@ -5803,7 +6083,11 @@ async def test_iam_permissions( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -5850,8 +6134,7 @@ async def get_location( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -5859,7 +6142,11 @@ async def get_location( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -5906,8 +6193,7 @@ async def list_locations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -5915,7 +6201,11 @@ async def list_locations( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -5926,12 +6216,13 @@ async def __aenter__(self) -> "EventarcAsyncClient": async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "EventarcAsyncClient", -) +__all__ = ("EventarcAsyncClient",) diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py index b3f36793c0be..8ce831f5752c 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py @@ -19,7 +19,19 @@ import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +from typing import ( + Dict, + Callable, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) import warnings from google.cloud.eventarc_v1 import gapic_version as package_version @@ -28,11 +40,11 @@ from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.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.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 import google.protobuf try: @@ -42,6 +54,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -60,7 +73,9 @@ from google.cloud.eventarc_v1.types import google_api_source from google.cloud.eventarc_v1.types import google_api_source as gce_google_api_source from google.cloud.eventarc_v1.types import google_channel_config -from google.cloud.eventarc_v1.types import google_channel_config as gce_google_channel_config +from google.cloud.eventarc_v1.types import ( + google_channel_config as gce_google_channel_config, +) from google.cloud.eventarc_v1.types import logging_config from google.cloud.eventarc_v1.types import message_bus from google.cloud.eventarc_v1.types import message_bus as gce_message_bus @@ -68,10 +83,10 @@ from google.cloud.eventarc_v1.types import pipeline as gce_pipeline from google.cloud.eventarc_v1.types import trigger from google.cloud.eventarc_v1.types import trigger as gce_trigger -from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.api_core.operation as operation # type: ignore import google.api_core.operation_async as operation_async # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore @@ -89,14 +104,16 @@ class EventarcClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ + _transport_registry = OrderedDict() # type: Dict[str, Type[EventarcTransport]] _transport_registry["grpc"] = EventarcGrpcTransport _transport_registry["grpc_asyncio"] = EventarcGrpcAsyncIOTransport _transport_registry["rest"] = EventarcRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[EventarcTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[EventarcTransport]: """Returns an appropriate transport class. Args: @@ -175,14 +192,16 @@ def _use_client_cert_effective(): bool: whether client certificate should be used for mTLS Raises: ValueError: (If using a version of google-auth without should_use_client_cert and - GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) """ # check if google-auth version supports should_use_client_cert for automatic mTLS enablement if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER return mtls.should_use_client_cert() - else: # pragma: NO COVER + else: # pragma: NO COVER # if unsupported, fallback to reading from env var - use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() if use_client_cert_str not in ("true", "false"): raise ValueError( "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" @@ -221,8 +240,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: EventarcClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -239,124 +257,249 @@ def transport(self) -> EventarcTransport: return self._transport @staticmethod - def channel_path(project: str,location: str,channel: str,) -> str: + def channel_path( + project: str, + location: str, + channel: str, + ) -> str: """Returns a fully-qualified channel string.""" - return "projects/{project}/locations/{location}/channels/{channel}".format(project=project, location=location, channel=channel, ) + return "projects/{project}/locations/{location}/channels/{channel}".format( + project=project, + location=location, + channel=channel, + ) @staticmethod - def parse_channel_path(path: str) -> Dict[str,str]: + def parse_channel_path(path: str) -> Dict[str, str]: """Parses a channel path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/channels/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/channels/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def channel_connection_path(project: str,location: str,channel_connection: str,) -> str: + def channel_connection_path( + project: str, + location: str, + channel_connection: str, + ) -> str: """Returns a fully-qualified channel_connection string.""" - return "projects/{project}/locations/{location}/channelConnections/{channel_connection}".format(project=project, location=location, channel_connection=channel_connection, ) + return "projects/{project}/locations/{location}/channelConnections/{channel_connection}".format( + project=project, + location=location, + channel_connection=channel_connection, + ) @staticmethod - def parse_channel_connection_path(path: str) -> Dict[str,str]: + def parse_channel_connection_path(path: str) -> Dict[str, str]: """Parses a channel_connection path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/channelConnections/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/channelConnections/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def cloud_function_path(project: str,location: str,function: str,) -> str: + def cloud_function_path( + project: str, + location: str, + function: str, + ) -> str: """Returns a fully-qualified cloud_function string.""" - return "projects/{project}/locations/{location}/functions/{function}".format(project=project, location=location, function=function, ) + return "projects/{project}/locations/{location}/functions/{function}".format( + project=project, + location=location, + function=function, + ) @staticmethod - def parse_cloud_function_path(path: str) -> Dict[str,str]: + def parse_cloud_function_path(path: str) -> Dict[str, str]: """Parses a cloud_function path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/functions/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/functions/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def crypto_key_path(project: str,location: str,key_ring: str,crypto_key: str,) -> str: + def crypto_key_path( + project: str, + location: str, + key_ring: str, + crypto_key: str, + ) -> str: """Returns a fully-qualified crypto_key string.""" - return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + ) @staticmethod - def parse_crypto_key_path(path: str) -> Dict[str,str]: + def parse_crypto_key_path(path: str) -> Dict[str, str]: """Parses a crypto_key path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def enrollment_path(project: str,location: str,enrollment: str,) -> str: + def enrollment_path( + project: str, + location: str, + enrollment: str, + ) -> str: """Returns a fully-qualified enrollment string.""" - return "projects/{project}/locations/{location}/enrollments/{enrollment}".format(project=project, location=location, enrollment=enrollment, ) + return ( + "projects/{project}/locations/{location}/enrollments/{enrollment}".format( + project=project, + location=location, + enrollment=enrollment, + ) + ) @staticmethod - def parse_enrollment_path(path: str) -> Dict[str,str]: + def parse_enrollment_path(path: str) -> Dict[str, str]: """Parses a enrollment path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/enrollments/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/enrollments/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def google_api_source_path(project: str,location: str,google_api_source: str,) -> str: + def google_api_source_path( + project: str, + location: str, + google_api_source: str, + ) -> str: """Returns a fully-qualified google_api_source string.""" - return "projects/{project}/locations/{location}/googleApiSources/{google_api_source}".format(project=project, location=location, google_api_source=google_api_source, ) + return "projects/{project}/locations/{location}/googleApiSources/{google_api_source}".format( + project=project, + location=location, + google_api_source=google_api_source, + ) @staticmethod - def parse_google_api_source_path(path: str) -> Dict[str,str]: + def parse_google_api_source_path(path: str) -> Dict[str, str]: """Parses a google_api_source path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/googleApiSources/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/googleApiSources/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def google_channel_config_path(project: str,location: str,) -> str: + def google_channel_config_path( + project: str, + location: str, + ) -> str: """Returns a fully-qualified google_channel_config string.""" - return "projects/{project}/locations/{location}/googleChannelConfig".format(project=project, location=location, ) + return "projects/{project}/locations/{location}/googleChannelConfig".format( + project=project, + location=location, + ) @staticmethod - def parse_google_channel_config_path(path: str) -> Dict[str,str]: + def parse_google_channel_config_path(path: str) -> Dict[str, str]: """Parses a google_channel_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/googleChannelConfig$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/googleChannelConfig$", + path, + ) return m.groupdict() if m else {} @staticmethod - def message_bus_path(project: str,location: str,message_bus: str,) -> str: + def message_bus_path( + project: str, + location: str, + message_bus: str, + ) -> str: """Returns a fully-qualified message_bus string.""" - return "projects/{project}/locations/{location}/messageBuses/{message_bus}".format(project=project, location=location, message_bus=message_bus, ) + return ( + "projects/{project}/locations/{location}/messageBuses/{message_bus}".format( + project=project, + location=location, + message_bus=message_bus, + ) + ) @staticmethod - def parse_message_bus_path(path: str) -> Dict[str,str]: + def parse_message_bus_path(path: str) -> Dict[str, str]: """Parses a message_bus path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/messageBuses/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/messageBuses/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def network_attachment_path(project: str,region: str,networkattachment: str,) -> str: + def network_attachment_path( + project: str, + region: str, + networkattachment: str, + ) -> str: """Returns a fully-qualified network_attachment string.""" - return "projects/{project}/regions/{region}/networkAttachments/{networkattachment}".format(project=project, region=region, networkattachment=networkattachment, ) + return "projects/{project}/regions/{region}/networkAttachments/{networkattachment}".format( + project=project, + region=region, + networkattachment=networkattachment, + ) @staticmethod - def parse_network_attachment_path(path: str) -> Dict[str,str]: + def parse_network_attachment_path(path: str) -> Dict[str, str]: """Parses a network_attachment path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/regions/(?P.+?)/networkAttachments/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/regions/(?P.+?)/networkAttachments/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def pipeline_path(project: str,location: str,pipeline: str,) -> str: + def pipeline_path( + project: str, + location: str, + pipeline: str, + ) -> str: """Returns a fully-qualified pipeline string.""" - return "projects/{project}/locations/{location}/pipelines/{pipeline}".format(project=project, location=location, pipeline=pipeline, ) + return "projects/{project}/locations/{location}/pipelines/{pipeline}".format( + project=project, + location=location, + pipeline=pipeline, + ) @staticmethod - def parse_pipeline_path(path: str) -> Dict[str,str]: + def parse_pipeline_path(path: str) -> Dict[str, str]: """Parses a pipeline path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/pipelines/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/pipelines/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def provider_path(project: str,location: str,provider: str,) -> str: + def provider_path( + project: str, + location: str, + provider: str, + ) -> str: """Returns a fully-qualified provider string.""" - return "projects/{project}/locations/{location}/providers/{provider}".format(project=project, location=location, provider=provider, ) + return "projects/{project}/locations/{location}/providers/{provider}".format( + project=project, + location=location, + provider=provider, + ) @staticmethod - def parse_provider_path(path: str) -> Dict[str,str]: + def parse_provider_path(path: str) -> Dict[str, str]: """Parses a provider path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/providers/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/providers/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod @@ -365,112 +508,173 @@ def service_path() -> str: return "*".format() @staticmethod - def parse_service_path(path: str) -> Dict[str,str]: + def parse_service_path(path: str) -> Dict[str, str]: """Parses a service path into its component segments.""" m = re.match(r"^.*$", path) return m.groupdict() if m else {} @staticmethod - def service_account_path(project: str,service_account: str,) -> str: + def service_account_path( + project: str, + service_account: str, + ) -> str: """Returns a fully-qualified service_account string.""" - return "projects/{project}/serviceAccounts/{service_account}".format(project=project, service_account=service_account, ) + return "projects/{project}/serviceAccounts/{service_account}".format( + project=project, + service_account=service_account, + ) @staticmethod - def parse_service_account_path(path: str) -> Dict[str,str]: + def parse_service_account_path(path: str) -> Dict[str, str]: """Parses a service_account path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/serviceAccounts/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/serviceAccounts/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def topic_path(project: str,topic: str,) -> str: + def topic_path( + project: str, + topic: str, + ) -> str: """Returns a fully-qualified topic string.""" - return "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) + return "projects/{project}/topics/{topic}".format( + project=project, + topic=topic, + ) @staticmethod - def parse_topic_path(path: str) -> Dict[str,str]: + def parse_topic_path(path: str) -> Dict[str, str]: """Parses a topic path into its component segments.""" m = re.match(r"^projects/(?P.+?)/topics/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def trigger_path(project: str,location: str,trigger: str,) -> str: + def trigger_path( + project: str, + location: str, + trigger: str, + ) -> str: """Returns a fully-qualified trigger string.""" - return "projects/{project}/locations/{location}/triggers/{trigger}".format(project=project, location=location, trigger=trigger, ) + return "projects/{project}/locations/{location}/triggers/{trigger}".format( + project=project, + location=location, + trigger=trigger, + ) @staticmethod - def parse_trigger_path(path: str) -> Dict[str,str]: + def parse_trigger_path(path: str) -> Dict[str, str]: """Parses a trigger path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/triggers/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/triggers/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def workflow_path(project: str,location: str,workflow: str,) -> str: + def workflow_path( + project: str, + location: str, + workflow: str, + ) -> str: """Returns a fully-qualified workflow string.""" - return "projects/{project}/locations/{location}/workflows/{workflow}".format(project=project, location=location, workflow=workflow, ) + return "projects/{project}/locations/{location}/workflows/{workflow}".format( + project=project, + location=location, + workflow=workflow, + ) @staticmethod - def parse_workflow_path(path: str) -> Dict[str,str]: + def parse_workflow_path(path: str) -> Dict[str, str]: """Parses a workflow path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workflows/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/workflows/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + def common_billing_account_path( + billing_account: str, + ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path(folder: str, ) -> str: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path(organization: str, ) -> str: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path(project: str, ) -> str: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path(project: str, location: str, ) -> str: + def common_location_path( + project: str, + location: str, + ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -502,14 +706,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = EventarcClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Figure out the client cert source to use. client_cert_source = None @@ -522,7 +730,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): api_endpoint = cls.DEFAULT_MTLS_ENDPOINT else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -547,7 +757,9 @@ def _read_environment_variables(): use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod @@ -570,7 +782,9 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: """Return the API endpoint used by the client. Args: @@ -586,17 +800,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): _default_universe = EventarcClient._DEFAULT_UNIVERSE if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) api_endpoint = EventarcClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = EventarcClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = EventarcClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) return api_endpoint @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: """Return the universe domain used by the client. Args: @@ -632,15 +854,18 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError + self, error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: return cred = self._transport._credentials @@ -673,12 +898,16 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, EventarcTransport, Callable[..., EventarcTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, EventarcTransport, Callable[..., EventarcTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the eventarc client. Args: @@ -736,13 +965,23 @@ def __init__(self, *, self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = EventarcClient._read_environment_variables() - self._client_cert_source = EventarcClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = EventarcClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = EventarcClient._read_environment_variables() + self._client_cert_source = EventarcClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = EventarcClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -754,7 +993,9 @@ def __init__(self, *, api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -763,8 +1004,10 @@ def __init__(self, *, if transport_provided: # transport is a EventarcTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if self._client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes " @@ -773,20 +1016,26 @@ def __init__(self, *, self._transport = cast(EventarcTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - EventarcClient._get_api_endpoint( - self._client_options.api_endpoint, - self._client_cert_source, - self._universe_domain, - self._use_mtls_endpoint)) + self._api_endpoint = self._api_endpoint or EventarcClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) - transport_init: Union[Type[EventarcTransport], Callable[..., EventarcTransport]] = ( + transport_init: Union[ + Type[EventarcTransport], Callable[..., EventarcTransport] + ] = ( EventarcClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., EventarcTransport], transport) @@ -805,28 +1054,37 @@ def __init__(self, *, ) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.eventarc_v1.EventarcClient`.", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { "serviceName": "google.cloud.eventarc.v1.Eventarc", "credentialsType": None, - } + }, ) - def get_trigger(self, - request: Optional[Union[eventarc.GetTriggerRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> trigger.Trigger: + def get_trigger( + self, + request: Optional[Union[eventarc.GetTriggerRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> trigger.Trigger: r"""Get a single trigger. .. code-block:: python @@ -884,10 +1142,14 @@ def sample_get_trigger(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -905,9 +1167,7 @@ def sample_get_trigger(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -924,14 +1184,15 @@ def sample_get_trigger(): # Done; return the response. return response - def list_triggers(self, - request: Optional[Union[eventarc.ListTriggersRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListTriggersPager: + def list_triggers( + self, + request: Optional[Union[eventarc.ListTriggersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListTriggersPager: r"""List triggers. .. code-block:: python @@ -992,10 +1253,14 @@ def sample_list_triggers(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1013,9 +1278,7 @@ def sample_list_triggers(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1043,16 +1306,17 @@ def sample_list_triggers(): # Done; return the response. return response - def create_trigger(self, - request: Optional[Union[eventarc.CreateTriggerRequest, dict]] = None, - *, - parent: Optional[str] = None, - trigger: Optional[gce_trigger.Trigger] = None, - trigger_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_trigger( + self, + request: Optional[Union[eventarc.CreateTriggerRequest, dict]] = None, + *, + parent: Optional[str] = None, + trigger: Optional[gce_trigger.Trigger] = None, + trigger_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Create a new trigger in a particular project and location. @@ -1139,10 +1403,14 @@ def sample_create_trigger(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, trigger, trigger_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1164,9 +1432,7 @@ def sample_create_trigger(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1191,16 +1457,17 @@ def sample_create_trigger(): # Done; return the response. return response - def update_trigger(self, - request: Optional[Union[eventarc.UpdateTriggerRequest, dict]] = None, - *, - trigger: Optional[gce_trigger.Trigger] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - allow_missing: Optional[bool] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_trigger( + self, + request: Optional[Union[eventarc.UpdateTriggerRequest, dict]] = None, + *, + trigger: Optional[gce_trigger.Trigger] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + allow_missing: Optional[bool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Update a single trigger. .. code-block:: python @@ -1279,10 +1546,14 @@ def sample_update_trigger(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [trigger, update_mask, allow_missing] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1304,9 +1575,9 @@ def sample_update_trigger(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("trigger.name", request.trigger.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("trigger.name", request.trigger.name),) + ), ) # Validate the universe domain. @@ -1331,15 +1602,16 @@ def sample_update_trigger(): # Done; return the response. return response - def delete_trigger(self, - request: Optional[Union[eventarc.DeleteTriggerRequest, dict]] = None, - *, - name: Optional[str] = None, - allow_missing: Optional[bool] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_trigger( + self, + request: Optional[Union[eventarc.DeleteTriggerRequest, dict]] = None, + *, + name: Optional[str] = None, + allow_missing: Optional[bool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Delete a single trigger. .. code-block:: python @@ -1412,10 +1684,14 @@ def sample_delete_trigger(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, allow_missing] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1435,9 +1711,7 @@ def sample_delete_trigger(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1462,14 +1736,15 @@ def sample_delete_trigger(): # Done; return the response. return response - def get_channel(self, - request: Optional[Union[eventarc.GetChannelRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> channel.Channel: + def get_channel( + self, + request: Optional[Union[eventarc.GetChannelRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> channel.Channel: r"""Get a single Channel. .. code-block:: python @@ -1533,10 +1808,14 @@ def sample_get_channel(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1554,9 +1833,7 @@ def sample_get_channel(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1573,14 +1850,15 @@ def sample_get_channel(): # Done; return the response. return response - def list_channels(self, - request: Optional[Union[eventarc.ListChannelsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListChannelsPager: + def list_channels( + self, + request: Optional[Union[eventarc.ListChannelsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListChannelsPager: r"""List channels. .. code-block:: python @@ -1641,10 +1919,14 @@ def sample_list_channels(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1662,9 +1944,7 @@ def sample_list_channels(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1692,16 +1972,17 @@ def sample_list_channels(): # Done; return the response. return response - def create_channel(self, - request: Optional[Union[eventarc.CreateChannelRequest, dict]] = None, - *, - parent: Optional[str] = None, - channel: Optional[gce_channel.Channel] = None, - channel_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_channel( + self, + request: Optional[Union[eventarc.CreateChannelRequest, dict]] = None, + *, + parent: Optional[str] = None, + channel: Optional[gce_channel.Channel] = None, + channel_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Create a new channel in a particular project and location. @@ -1788,10 +2069,14 @@ def sample_create_channel(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, channel, channel_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1813,9 +2098,7 @@ def sample_create_channel(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1840,15 +2123,16 @@ def sample_create_channel(): # Done; return the response. return response - def update_channel(self, - request: Optional[Union[eventarc.UpdateChannelRequest, dict]] = None, - *, - channel: Optional[gce_channel.Channel] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_channel( + self, + request: Optional[Union[eventarc.UpdateChannelRequest, dict]] = None, + *, + channel: Optional[gce_channel.Channel] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Update a single channel. .. code-block:: python @@ -1922,10 +2206,14 @@ def sample_update_channel(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [channel, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1945,9 +2233,9 @@ def sample_update_channel(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("channel.name", request.channel.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("channel.name", request.channel.name),) + ), ) # Validate the universe domain. @@ -1972,14 +2260,15 @@ def sample_update_channel(): # Done; return the response. return response - def delete_channel(self, - request: Optional[Union[eventarc.DeleteChannelRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_channel( + self, + request: Optional[Union[eventarc.DeleteChannelRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Delete a single channel. .. code-block:: python @@ -2047,10 +2336,14 @@ def sample_delete_channel(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2068,9 +2361,7 @@ def sample_delete_channel(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2095,14 +2386,15 @@ def sample_delete_channel(): # Done; return the response. return response - def get_provider(self, - request: Optional[Union[eventarc.GetProviderRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> discovery.Provider: + def get_provider( + self, + request: Optional[Union[eventarc.GetProviderRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> discovery.Provider: r"""Get a single Provider. .. code-block:: python @@ -2160,10 +2452,14 @@ def sample_get_provider(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2181,9 +2477,7 @@ def sample_get_provider(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2200,14 +2494,15 @@ def sample_get_provider(): # Done; return the response. return response - def list_providers(self, - request: Optional[Union[eventarc.ListProvidersRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListProvidersPager: + def list_providers( + self, + request: Optional[Union[eventarc.ListProvidersRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListProvidersPager: r"""List providers. .. code-block:: python @@ -2268,10 +2563,14 @@ def sample_list_providers(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2289,9 +2588,7 @@ def sample_list_providers(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2319,14 +2616,15 @@ def sample_list_providers(): # Done; return the response. return response - def get_channel_connection(self, - request: Optional[Union[eventarc.GetChannelConnectionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> channel_connection.ChannelConnection: + def get_channel_connection( + self, + request: Optional[Union[eventarc.GetChannelConnectionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> channel_connection.ChannelConnection: r"""Get a single ChannelConnection. .. code-block:: python @@ -2389,10 +2687,14 @@ def sample_get_channel_connection(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2410,9 +2712,7 @@ def sample_get_channel_connection(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2429,14 +2729,15 @@ def sample_get_channel_connection(): # Done; return the response. return response - def list_channel_connections(self, - request: Optional[Union[eventarc.ListChannelConnectionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListChannelConnectionsPager: + def list_channel_connections( + self, + request: Optional[Union[eventarc.ListChannelConnectionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListChannelConnectionsPager: r"""List channel connections. .. code-block:: python @@ -2498,10 +2799,14 @@ def sample_list_channel_connections(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2519,9 +2824,7 @@ def sample_list_channel_connections(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2549,16 +2852,17 @@ def sample_list_channel_connections(): # Done; return the response. return response - def create_channel_connection(self, - request: Optional[Union[eventarc.CreateChannelConnectionRequest, dict]] = None, - *, - parent: Optional[str] = None, - channel_connection: Optional[gce_channel_connection.ChannelConnection] = None, - channel_connection_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_channel_connection( + self, + request: Optional[Union[eventarc.CreateChannelConnectionRequest, dict]] = None, + *, + parent: Optional[str] = None, + channel_connection: Optional[gce_channel_connection.ChannelConnection] = None, + channel_connection_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Create a new ChannelConnection in a particular project and location. @@ -2646,10 +2950,14 @@ def sample_create_channel_connection(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, channel_connection, channel_connection_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2666,14 +2974,14 @@ def sample_create_channel_connection(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_channel_connection] + rpc = self._transport._wrapped_methods[ + self._transport.create_channel_connection + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2698,14 +3006,15 @@ def sample_create_channel_connection(): # Done; return the response. return response - def delete_channel_connection(self, - request: Optional[Union[eventarc.DeleteChannelConnectionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_channel_connection( + self, + request: Optional[Union[eventarc.DeleteChannelConnectionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Delete a single ChannelConnection. .. code-block:: python @@ -2772,10 +3081,14 @@ def sample_delete_channel_connection(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2788,14 +3101,14 @@ def sample_delete_channel_connection(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_channel_connection] + rpc = self._transport._wrapped_methods[ + self._transport.delete_channel_connection + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2820,14 +3133,15 @@ def sample_delete_channel_connection(): # Done; return the response. return response - def get_google_channel_config(self, - request: Optional[Union[eventarc.GetGoogleChannelConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> google_channel_config.GoogleChannelConfig: + def get_google_channel_config( + self, + request: Optional[Union[eventarc.GetGoogleChannelConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> google_channel_config.GoogleChannelConfig: r"""Get a GoogleChannelConfig. The name of the GoogleChannelConfig in the response is ALWAYS coded with projectID. @@ -2893,10 +3207,14 @@ def sample_get_google_channel_config(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2909,14 +3227,14 @@ def sample_get_google_channel_config(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_google_channel_config] + rpc = self._transport._wrapped_methods[ + self._transport.get_google_channel_config + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2933,15 +3251,20 @@ def sample_get_google_channel_config(): # Done; return the response. return response - def update_google_channel_config(self, - request: Optional[Union[eventarc.UpdateGoogleChannelConfigRequest, dict]] = None, - *, - google_channel_config: Optional[gce_google_channel_config.GoogleChannelConfig] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gce_google_channel_config.GoogleChannelConfig: + def update_google_channel_config( + self, + request: Optional[ + Union[eventarc.UpdateGoogleChannelConfigRequest, dict] + ] = None, + *, + google_channel_config: Optional[ + gce_google_channel_config.GoogleChannelConfig + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gce_google_channel_config.GoogleChannelConfig: r"""Update a single GoogleChannelConfig .. code-block:: python @@ -3015,10 +3338,14 @@ def sample_update_google_channel_config(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [google_channel_config, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3033,14 +3360,16 @@ def sample_update_google_channel_config(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_google_channel_config] + rpc = self._transport._wrapped_methods[ + self._transport.update_google_channel_config + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("google_channel_config.name", request.google_channel_config.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("google_channel_config.name", request.google_channel_config.name),) + ), ) # Validate the universe domain. @@ -3057,14 +3386,15 @@ def sample_update_google_channel_config(): # Done; return the response. return response - def get_message_bus(self, - request: Optional[Union[eventarc.GetMessageBusRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> message_bus.MessageBus: + def get_message_bus( + self, + request: Optional[Union[eventarc.GetMessageBusRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> message_bus.MessageBus: r"""Get a single MessageBus. .. code-block:: python @@ -3128,10 +3458,14 @@ def sample_get_message_bus(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3149,9 +3483,7 @@ def sample_get_message_bus(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3168,14 +3500,15 @@ def sample_get_message_bus(): # Done; return the response. return response - def list_message_buses(self, - request: Optional[Union[eventarc.ListMessageBusesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListMessageBusesPager: + def list_message_buses( + self, + request: Optional[Union[eventarc.ListMessageBusesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMessageBusesPager: r"""List message buses. .. code-block:: python @@ -3236,10 +3569,14 @@ def sample_list_message_buses(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3257,9 +3594,7 @@ def sample_list_message_buses(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -3287,14 +3622,17 @@ def sample_list_message_buses(): # Done; return the response. return response - def list_message_bus_enrollments(self, - request: Optional[Union[eventarc.ListMessageBusEnrollmentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListMessageBusEnrollmentsPager: + def list_message_bus_enrollments( + self, + request: Optional[ + Union[eventarc.ListMessageBusEnrollmentsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMessageBusEnrollmentsPager: r"""List message bus enrollments. .. code-block:: python @@ -3356,10 +3694,14 @@ def sample_list_message_bus_enrollments(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3372,14 +3714,14 @@ def sample_list_message_bus_enrollments(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_message_bus_enrollments] + rpc = self._transport._wrapped_methods[ + self._transport.list_message_bus_enrollments + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -3407,16 +3749,17 @@ def sample_list_message_bus_enrollments(): # Done; return the response. return response - def create_message_bus(self, - request: Optional[Union[eventarc.CreateMessageBusRequest, dict]] = None, - *, - parent: Optional[str] = None, - message_bus: Optional[gce_message_bus.MessageBus] = None, - message_bus_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_message_bus( + self, + request: Optional[Union[eventarc.CreateMessageBusRequest, dict]] = None, + *, + parent: Optional[str] = None, + message_bus: Optional[gce_message_bus.MessageBus] = None, + message_bus_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Create a new MessageBus in a particular project and location. @@ -3498,10 +3841,14 @@ def sample_create_message_bus(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, message_bus, message_bus_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3523,9 +3870,7 @@ def sample_create_message_bus(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -3550,15 +3895,16 @@ def sample_create_message_bus(): # Done; return the response. return response - def update_message_bus(self, - request: Optional[Union[eventarc.UpdateMessageBusRequest, dict]] = None, - *, - message_bus: Optional[gce_message_bus.MessageBus] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_message_bus( + self, + request: Optional[Union[eventarc.UpdateMessageBusRequest, dict]] = None, + *, + message_bus: Optional[gce_message_bus.MessageBus] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Update a single message bus. .. code-block:: python @@ -3634,10 +3980,14 @@ def sample_update_message_bus(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [message_bus, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3657,9 +4007,9 @@ def sample_update_message_bus(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("message_bus.name", request.message_bus.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("message_bus.name", request.message_bus.name),) + ), ) # Validate the universe domain. @@ -3684,15 +4034,16 @@ def sample_update_message_bus(): # Done; return the response. return response - def delete_message_bus(self, - request: Optional[Union[eventarc.DeleteMessageBusRequest, dict]] = None, - *, - name: Optional[str] = None, - etag: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_message_bus( + self, + request: Optional[Union[eventarc.DeleteMessageBusRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Delete a single message bus. .. code-block:: python @@ -3767,10 +4118,14 @@ def sample_delete_message_bus(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, etag] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3790,9 +4145,7 @@ def sample_delete_message_bus(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3817,14 +4170,15 @@ def sample_delete_message_bus(): # Done; return the response. return response - def get_enrollment(self, - request: Optional[Union[eventarc.GetEnrollmentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> enrollment.Enrollment: + def get_enrollment( + self, + request: Optional[Union[eventarc.GetEnrollmentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> enrollment.Enrollment: r"""Get a single Enrollment. .. code-block:: python @@ -3886,10 +4240,14 @@ def sample_get_enrollment(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3907,9 +4265,7 @@ def sample_get_enrollment(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3926,14 +4282,15 @@ def sample_get_enrollment(): # Done; return the response. return response - def list_enrollments(self, - request: Optional[Union[eventarc.ListEnrollmentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListEnrollmentsPager: + def list_enrollments( + self, + request: Optional[Union[eventarc.ListEnrollmentsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListEnrollmentsPager: r"""List Enrollments. .. code-block:: python @@ -3994,10 +4351,14 @@ def sample_list_enrollments(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4015,9 +4376,7 @@ def sample_list_enrollments(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -4045,16 +4404,17 @@ def sample_list_enrollments(): # Done; return the response. return response - def create_enrollment(self, - request: Optional[Union[eventarc.CreateEnrollmentRequest, dict]] = None, - *, - parent: Optional[str] = None, - enrollment: Optional[gce_enrollment.Enrollment] = None, - enrollment_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_enrollment( + self, + request: Optional[Union[eventarc.CreateEnrollmentRequest, dict]] = None, + *, + parent: Optional[str] = None, + enrollment: Optional[gce_enrollment.Enrollment] = None, + enrollment_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Create a new Enrollment in a particular project and location. @@ -4141,10 +4501,14 @@ def sample_create_enrollment(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, enrollment, enrollment_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4166,9 +4530,7 @@ def sample_create_enrollment(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -4193,15 +4555,16 @@ def sample_create_enrollment(): # Done; return the response. return response - def update_enrollment(self, - request: Optional[Union[eventarc.UpdateEnrollmentRequest, dict]] = None, - *, - enrollment: Optional[gce_enrollment.Enrollment] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_enrollment( + self, + request: Optional[Union[eventarc.UpdateEnrollmentRequest, dict]] = None, + *, + enrollment: Optional[gce_enrollment.Enrollment] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Update a single Enrollment. .. code-block:: python @@ -4282,10 +4645,14 @@ def sample_update_enrollment(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [enrollment, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4305,9 +4672,9 @@ def sample_update_enrollment(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("enrollment.name", request.enrollment.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("enrollment.name", request.enrollment.name),) + ), ) # Validate the universe domain. @@ -4332,15 +4699,16 @@ def sample_update_enrollment(): # Done; return the response. return response - def delete_enrollment(self, - request: Optional[Union[eventarc.DeleteEnrollmentRequest, dict]] = None, - *, - name: Optional[str] = None, - etag: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_enrollment( + self, + request: Optional[Union[eventarc.DeleteEnrollmentRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Delete a single Enrollment. .. code-block:: python @@ -4414,10 +4782,14 @@ def sample_delete_enrollment(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, etag] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4437,9 +4809,7 @@ def sample_delete_enrollment(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -4464,14 +4834,15 @@ def sample_delete_enrollment(): # Done; return the response. return response - def get_pipeline(self, - request: Optional[Union[eventarc.GetPipelineRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pipeline.Pipeline: + def get_pipeline( + self, + request: Optional[Union[eventarc.GetPipelineRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pipeline.Pipeline: r"""Get a single Pipeline. .. code-block:: python @@ -4529,10 +4900,14 @@ def sample_get_pipeline(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4550,9 +4925,7 @@ def sample_get_pipeline(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -4569,14 +4942,15 @@ def sample_get_pipeline(): # Done; return the response. return response - def list_pipelines(self, - request: Optional[Union[eventarc.ListPipelinesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListPipelinesPager: + def list_pipelines( + self, + request: Optional[Union[eventarc.ListPipelinesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPipelinesPager: r"""List pipelines. .. code-block:: python @@ -4638,10 +5012,14 @@ def sample_list_pipelines(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4659,9 +5037,7 @@ def sample_list_pipelines(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -4689,16 +5065,17 @@ def sample_list_pipelines(): # Done; return the response. return response - def create_pipeline(self, - request: Optional[Union[eventarc.CreatePipelineRequest, dict]] = None, - *, - parent: Optional[str] = None, - pipeline: Optional[gce_pipeline.Pipeline] = None, - pipeline_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_pipeline( + self, + request: Optional[Union[eventarc.CreatePipelineRequest, dict]] = None, + *, + parent: Optional[str] = None, + pipeline: Optional[gce_pipeline.Pipeline] = None, + pipeline_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Create a new Pipeline in a particular project and location. @@ -4782,10 +5159,14 @@ def sample_create_pipeline(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, pipeline, pipeline_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4807,9 +5188,7 @@ def sample_create_pipeline(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -4834,15 +5213,16 @@ def sample_create_pipeline(): # Done; return the response. return response - def update_pipeline(self, - request: Optional[Union[eventarc.UpdatePipelineRequest, dict]] = None, - *, - pipeline: Optional[gce_pipeline.Pipeline] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_pipeline( + self, + request: Optional[Union[eventarc.UpdatePipelineRequest, dict]] = None, + *, + pipeline: Optional[gce_pipeline.Pipeline] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Update a single pipeline. .. code-block:: python @@ -4918,10 +5298,14 @@ def sample_update_pipeline(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [pipeline, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4941,9 +5325,9 @@ def sample_update_pipeline(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("pipeline.name", request.pipeline.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("pipeline.name", request.pipeline.name),) + ), ) # Validate the universe domain. @@ -4968,15 +5352,16 @@ def sample_update_pipeline(): # Done; return the response. return response - def delete_pipeline(self, - request: Optional[Union[eventarc.DeletePipelineRequest, dict]] = None, - *, - name: Optional[str] = None, - etag: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_pipeline( + self, + request: Optional[Union[eventarc.DeletePipelineRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Delete a single pipeline. .. code-block:: python @@ -5049,10 +5434,14 @@ def sample_delete_pipeline(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, etag] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -5072,9 +5461,7 @@ def sample_delete_pipeline(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -5099,14 +5486,15 @@ def sample_delete_pipeline(): # Done; return the response. return response - def get_google_api_source(self, - request: Optional[Union[eventarc.GetGoogleApiSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> google_api_source.GoogleApiSource: + def get_google_api_source( + self, + request: Optional[Union[eventarc.GetGoogleApiSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> google_api_source.GoogleApiSource: r"""Get a single GoogleApiSource. .. code-block:: python @@ -5165,10 +5553,14 @@ def sample_get_google_api_source(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -5186,9 +5578,7 @@ def sample_get_google_api_source(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -5205,14 +5595,15 @@ def sample_get_google_api_source(): # Done; return the response. return response - def list_google_api_sources(self, - request: Optional[Union[eventarc.ListGoogleApiSourcesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListGoogleApiSourcesPager: + def list_google_api_sources( + self, + request: Optional[Union[eventarc.ListGoogleApiSourcesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListGoogleApiSourcesPager: r"""List GoogleApiSources. .. code-block:: python @@ -5274,10 +5665,14 @@ def sample_list_google_api_sources(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -5295,9 +5690,7 @@ def sample_list_google_api_sources(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -5325,16 +5718,17 @@ def sample_list_google_api_sources(): # Done; return the response. return response - def create_google_api_source(self, - request: Optional[Union[eventarc.CreateGoogleApiSourceRequest, dict]] = None, - *, - parent: Optional[str] = None, - google_api_source: Optional[gce_google_api_source.GoogleApiSource] = None, - google_api_source_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_google_api_source( + self, + request: Optional[Union[eventarc.CreateGoogleApiSourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + google_api_source: Optional[gce_google_api_source.GoogleApiSource] = None, + google_api_source_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Create a new GoogleApiSource in a particular project and location. @@ -5422,10 +5816,14 @@ def sample_create_google_api_source(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, google_api_source, google_api_source_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -5447,9 +5845,7 @@ def sample_create_google_api_source(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -5474,15 +5870,16 @@ def sample_create_google_api_source(): # Done; return the response. return response - def update_google_api_source(self, - request: Optional[Union[eventarc.UpdateGoogleApiSourceRequest, dict]] = None, - *, - google_api_source: Optional[gce_google_api_source.GoogleApiSource] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_google_api_source( + self, + request: Optional[Union[eventarc.UpdateGoogleApiSourceRequest, dict]] = None, + *, + google_api_source: Optional[gce_google_api_source.GoogleApiSource] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Update a single GoogleApiSource. .. code-block:: python @@ -5562,10 +5959,14 @@ def sample_update_google_api_source(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [google_api_source, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -5585,9 +5986,9 @@ def sample_update_google_api_source(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("google_api_source.name", request.google_api_source.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("google_api_source.name", request.google_api_source.name),) + ), ) # Validate the universe domain. @@ -5612,15 +6013,16 @@ def sample_update_google_api_source(): # Done; return the response. return response - def delete_google_api_source(self, - request: Optional[Union[eventarc.DeleteGoogleApiSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - etag: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_google_api_source( + self, + request: Optional[Union[eventarc.DeleteGoogleApiSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Delete a single GoogleApiSource. .. code-block:: python @@ -5694,10 +6096,14 @@ def sample_delete_google_api_source(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, etag] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -5717,9 +6123,7 @@ def sample_delete_google_api_source(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -5799,8 +6203,7 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -5809,7 +6212,11 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -5859,8 +6266,7 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -5869,7 +6275,11 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -5923,15 +6333,19 @@ def delete_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) def cancel_operation( self, @@ -5978,15 +6392,19 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) def set_iam_policy( self, @@ -6097,7 +6515,8 @@ def set_iam_policy( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request_pb.resource),)), + (("resource", request_pb.resource),) + ), ) # Validate the universe domain. @@ -6106,7 +6525,11 @@ def set_iam_policy( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -6224,7 +6647,8 @@ def get_iam_policy( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request_pb.resource),)), + (("resource", request_pb.resource),) + ), ) # Validate the universe domain. @@ -6233,7 +6657,11 @@ def get_iam_policy( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -6289,7 +6717,8 @@ def test_iam_permissions( # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("resource", request_pb.resource),)), + (("resource", request_pb.resource),) + ), ) # Validate the universe domain. @@ -6298,7 +6727,11 @@ def test_iam_permissions( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -6348,8 +6781,7 @@ def get_location( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -6358,7 +6790,11 @@ def get_location( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -6408,8 +6844,7 @@ def list_locations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -6418,7 +6853,11 @@ def list_locations( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -6427,11 +6866,11 @@ def list_locations( raise e -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "EventarcClient", -) +__all__ = ("EventarcClient",) diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py index 11885ff9813a..8c15e35a488f 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py @@ -25,7 +25,7 @@ from google.api_core import retry as retries from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf from google.cloud.eventarc_v1.types import channel @@ -35,16 +35,20 @@ from google.cloud.eventarc_v1.types import eventarc from google.cloud.eventarc_v1.types import google_api_source from google.cloud.eventarc_v1.types import google_channel_config -from google.cloud.eventarc_v1.types import google_channel_config as gce_google_channel_config +from google.cloud.eventarc_v1.types import ( + google_channel_config as gce_google_channel_config, +) from google.cloud.eventarc_v1.types import message_bus from google.cloud.eventarc_v1.types import pipeline from google.cloud.eventarc_v1.types import trigger -from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ @@ -53,24 +57,23 @@ class EventarcTransport(abc.ABC): """Abstract transport class for Eventarc.""" - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - DEFAULT_HOST: str = 'eventarc.googleapis.com' + DEFAULT_HOST: str = "eventarc.googleapis.com" def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -109,31 +112,43 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host self._wrapped_methods: Dict[Callable, Callable] = {} @@ -385,14 +400,14 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -402,354 +417,383 @@ def operations_client(self): raise NotImplementedError() @property - def get_trigger(self) -> Callable[ - [eventarc.GetTriggerRequest], - Union[ - trigger.Trigger, - Awaitable[trigger.Trigger] - ]]: + def get_trigger( + self, + ) -> Callable[ + [eventarc.GetTriggerRequest], Union[trigger.Trigger, Awaitable[trigger.Trigger]] + ]: raise NotImplementedError() @property - def list_triggers(self) -> Callable[ - [eventarc.ListTriggersRequest], - Union[ - eventarc.ListTriggersResponse, - Awaitable[eventarc.ListTriggersResponse] - ]]: + def list_triggers( + self, + ) -> Callable[ + [eventarc.ListTriggersRequest], + Union[eventarc.ListTriggersResponse, Awaitable[eventarc.ListTriggersResponse]], + ]: raise NotImplementedError() @property - def create_trigger(self) -> Callable[ - [eventarc.CreateTriggerRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_trigger( + self, + ) -> Callable[ + [eventarc.CreateTriggerRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def update_trigger(self) -> Callable[ - [eventarc.UpdateTriggerRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def update_trigger( + self, + ) -> Callable[ + [eventarc.UpdateTriggerRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def delete_trigger(self) -> Callable[ - [eventarc.DeleteTriggerRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def delete_trigger( + self, + ) -> Callable[ + [eventarc.DeleteTriggerRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def get_channel(self) -> Callable[ - [eventarc.GetChannelRequest], - Union[ - channel.Channel, - Awaitable[channel.Channel] - ]]: + def get_channel( + self, + ) -> Callable[ + [eventarc.GetChannelRequest], Union[channel.Channel, Awaitable[channel.Channel]] + ]: raise NotImplementedError() @property - def list_channels(self) -> Callable[ - [eventarc.ListChannelsRequest], - Union[ - eventarc.ListChannelsResponse, - Awaitable[eventarc.ListChannelsResponse] - ]]: + def list_channels( + self, + ) -> Callable[ + [eventarc.ListChannelsRequest], + Union[eventarc.ListChannelsResponse, Awaitable[eventarc.ListChannelsResponse]], + ]: raise NotImplementedError() @property - def create_channel_(self) -> Callable[ - [eventarc.CreateChannelRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_channel_( + self, + ) -> Callable[ + [eventarc.CreateChannelRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def update_channel(self) -> Callable[ - [eventarc.UpdateChannelRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def update_channel( + self, + ) -> Callable[ + [eventarc.UpdateChannelRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def delete_channel(self) -> Callable[ - [eventarc.DeleteChannelRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def delete_channel( + self, + ) -> Callable[ + [eventarc.DeleteChannelRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def get_provider(self) -> Callable[ - [eventarc.GetProviderRequest], - Union[ - discovery.Provider, - Awaitable[discovery.Provider] - ]]: + def get_provider( + self, + ) -> Callable[ + [eventarc.GetProviderRequest], + Union[discovery.Provider, Awaitable[discovery.Provider]], + ]: raise NotImplementedError() @property - def list_providers(self) -> Callable[ - [eventarc.ListProvidersRequest], - Union[ - eventarc.ListProvidersResponse, - Awaitable[eventarc.ListProvidersResponse] - ]]: + def list_providers( + self, + ) -> Callable[ + [eventarc.ListProvidersRequest], + Union[ + eventarc.ListProvidersResponse, Awaitable[eventarc.ListProvidersResponse] + ], + ]: raise NotImplementedError() @property - def get_channel_connection(self) -> Callable[ - [eventarc.GetChannelConnectionRequest], - Union[ - channel_connection.ChannelConnection, - Awaitable[channel_connection.ChannelConnection] - ]]: + def get_channel_connection( + self, + ) -> Callable[ + [eventarc.GetChannelConnectionRequest], + Union[ + channel_connection.ChannelConnection, + Awaitable[channel_connection.ChannelConnection], + ], + ]: raise NotImplementedError() @property - def list_channel_connections(self) -> Callable[ - [eventarc.ListChannelConnectionsRequest], - Union[ - eventarc.ListChannelConnectionsResponse, - Awaitable[eventarc.ListChannelConnectionsResponse] - ]]: + def list_channel_connections( + self, + ) -> Callable[ + [eventarc.ListChannelConnectionsRequest], + Union[ + eventarc.ListChannelConnectionsResponse, + Awaitable[eventarc.ListChannelConnectionsResponse], + ], + ]: raise NotImplementedError() @property - def create_channel_connection(self) -> Callable[ - [eventarc.CreateChannelConnectionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_channel_connection( + self, + ) -> Callable[ + [eventarc.CreateChannelConnectionRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def delete_channel_connection(self) -> Callable[ - [eventarc.DeleteChannelConnectionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def delete_channel_connection( + self, + ) -> Callable[ + [eventarc.DeleteChannelConnectionRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def get_google_channel_config(self) -> Callable[ - [eventarc.GetGoogleChannelConfigRequest], - Union[ - google_channel_config.GoogleChannelConfig, - Awaitable[google_channel_config.GoogleChannelConfig] - ]]: + def get_google_channel_config( + self, + ) -> Callable[ + [eventarc.GetGoogleChannelConfigRequest], + Union[ + google_channel_config.GoogleChannelConfig, + Awaitable[google_channel_config.GoogleChannelConfig], + ], + ]: raise NotImplementedError() @property - def update_google_channel_config(self) -> Callable[ - [eventarc.UpdateGoogleChannelConfigRequest], - Union[ - gce_google_channel_config.GoogleChannelConfig, - Awaitable[gce_google_channel_config.GoogleChannelConfig] - ]]: + def update_google_channel_config( + self, + ) -> Callable[ + [eventarc.UpdateGoogleChannelConfigRequest], + Union[ + gce_google_channel_config.GoogleChannelConfig, + Awaitable[gce_google_channel_config.GoogleChannelConfig], + ], + ]: raise NotImplementedError() @property - def get_message_bus(self) -> Callable[ - [eventarc.GetMessageBusRequest], - Union[ - message_bus.MessageBus, - Awaitable[message_bus.MessageBus] - ]]: + def get_message_bus( + self, + ) -> Callable[ + [eventarc.GetMessageBusRequest], + Union[message_bus.MessageBus, Awaitable[message_bus.MessageBus]], + ]: raise NotImplementedError() @property - def list_message_buses(self) -> Callable[ - [eventarc.ListMessageBusesRequest], - Union[ - eventarc.ListMessageBusesResponse, - Awaitable[eventarc.ListMessageBusesResponse] - ]]: + def list_message_buses( + self, + ) -> Callable[ + [eventarc.ListMessageBusesRequest], + Union[ + eventarc.ListMessageBusesResponse, + Awaitable[eventarc.ListMessageBusesResponse], + ], + ]: raise NotImplementedError() @property - def list_message_bus_enrollments(self) -> Callable[ - [eventarc.ListMessageBusEnrollmentsRequest], - Union[ - eventarc.ListMessageBusEnrollmentsResponse, - Awaitable[eventarc.ListMessageBusEnrollmentsResponse] - ]]: + def list_message_bus_enrollments( + self, + ) -> Callable[ + [eventarc.ListMessageBusEnrollmentsRequest], + Union[ + eventarc.ListMessageBusEnrollmentsResponse, + Awaitable[eventarc.ListMessageBusEnrollmentsResponse], + ], + ]: raise NotImplementedError() @property - def create_message_bus(self) -> Callable[ - [eventarc.CreateMessageBusRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_message_bus( + self, + ) -> Callable[ + [eventarc.CreateMessageBusRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def update_message_bus(self) -> Callable[ - [eventarc.UpdateMessageBusRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def update_message_bus( + self, + ) -> Callable[ + [eventarc.UpdateMessageBusRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def delete_message_bus(self) -> Callable[ - [eventarc.DeleteMessageBusRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def delete_message_bus( + self, + ) -> Callable[ + [eventarc.DeleteMessageBusRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def get_enrollment(self) -> Callable[ - [eventarc.GetEnrollmentRequest], - Union[ - enrollment.Enrollment, - Awaitable[enrollment.Enrollment] - ]]: + def get_enrollment( + self, + ) -> Callable[ + [eventarc.GetEnrollmentRequest], + Union[enrollment.Enrollment, Awaitable[enrollment.Enrollment]], + ]: raise NotImplementedError() @property - def list_enrollments(self) -> Callable[ - [eventarc.ListEnrollmentsRequest], - Union[ - eventarc.ListEnrollmentsResponse, - Awaitable[eventarc.ListEnrollmentsResponse] - ]]: + def list_enrollments( + self, + ) -> Callable[ + [eventarc.ListEnrollmentsRequest], + Union[ + eventarc.ListEnrollmentsResponse, + Awaitable[eventarc.ListEnrollmentsResponse], + ], + ]: raise NotImplementedError() @property - def create_enrollment(self) -> Callable[ - [eventarc.CreateEnrollmentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_enrollment( + self, + ) -> Callable[ + [eventarc.CreateEnrollmentRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def update_enrollment(self) -> Callable[ - [eventarc.UpdateEnrollmentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def update_enrollment( + self, + ) -> Callable[ + [eventarc.UpdateEnrollmentRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def delete_enrollment(self) -> Callable[ - [eventarc.DeleteEnrollmentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def delete_enrollment( + self, + ) -> Callable[ + [eventarc.DeleteEnrollmentRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def get_pipeline(self) -> Callable[ - [eventarc.GetPipelineRequest], - Union[ - pipeline.Pipeline, - Awaitable[pipeline.Pipeline] - ]]: + def get_pipeline( + self, + ) -> Callable[ + [eventarc.GetPipelineRequest], + Union[pipeline.Pipeline, Awaitable[pipeline.Pipeline]], + ]: raise NotImplementedError() @property - def list_pipelines(self) -> Callable[ - [eventarc.ListPipelinesRequest], - Union[ - eventarc.ListPipelinesResponse, - Awaitable[eventarc.ListPipelinesResponse] - ]]: + def list_pipelines( + self, + ) -> Callable[ + [eventarc.ListPipelinesRequest], + Union[ + eventarc.ListPipelinesResponse, Awaitable[eventarc.ListPipelinesResponse] + ], + ]: raise NotImplementedError() @property - def create_pipeline(self) -> Callable[ - [eventarc.CreatePipelineRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_pipeline( + self, + ) -> Callable[ + [eventarc.CreatePipelineRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def update_pipeline(self) -> Callable[ - [eventarc.UpdatePipelineRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def update_pipeline( + self, + ) -> Callable[ + [eventarc.UpdatePipelineRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def delete_pipeline(self) -> Callable[ - [eventarc.DeletePipelineRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def delete_pipeline( + self, + ) -> Callable[ + [eventarc.DeletePipelineRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def get_google_api_source(self) -> Callable[ - [eventarc.GetGoogleApiSourceRequest], - Union[ - google_api_source.GoogleApiSource, - Awaitable[google_api_source.GoogleApiSource] - ]]: + def get_google_api_source( + self, + ) -> Callable[ + [eventarc.GetGoogleApiSourceRequest], + Union[ + google_api_source.GoogleApiSource, + Awaitable[google_api_source.GoogleApiSource], + ], + ]: raise NotImplementedError() @property - def list_google_api_sources(self) -> Callable[ - [eventarc.ListGoogleApiSourcesRequest], - Union[ - eventarc.ListGoogleApiSourcesResponse, - Awaitable[eventarc.ListGoogleApiSourcesResponse] - ]]: + def list_google_api_sources( + self, + ) -> Callable[ + [eventarc.ListGoogleApiSourcesRequest], + Union[ + eventarc.ListGoogleApiSourcesResponse, + Awaitable[eventarc.ListGoogleApiSourcesResponse], + ], + ]: raise NotImplementedError() @property - def create_google_api_source(self) -> Callable[ - [eventarc.CreateGoogleApiSourceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_google_api_source( + self, + ) -> Callable[ + [eventarc.CreateGoogleApiSourceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def update_google_api_source(self) -> Callable[ - [eventarc.UpdateGoogleApiSourceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def update_google_api_source( + self, + ) -> Callable[ + [eventarc.UpdateGoogleApiSourceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def delete_google_api_source(self) -> Callable[ - [eventarc.DeleteGoogleApiSourceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def delete_google_api_source( + self, + ) -> Callable[ + [eventarc.DeleteGoogleApiSourceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property @@ -757,7 +801,10 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], ]: raise NotImplementedError() @@ -773,19 +820,13 @@ def get_operation( @property def cancel_operation( self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: raise NotImplementedError() @property def delete_operation( self, - ) -> Callable[ - [operations_pb2.DeleteOperationRequest], - None, - ]: + ) -> Callable[[operations_pb2.DeleteOperationRequest], None,]: raise NotImplementedError() @property @@ -819,7 +860,8 @@ def test_iam_permissions( raise NotImplementedError() @property - def get_location(self, + def get_location( + self, ) -> Callable[ [locations_pb2.GetLocationRequest], Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], @@ -827,10 +869,14 @@ def get_location(self, raise NotImplementedError() @property - def list_locations(self, + def list_locations( + self, ) -> Callable[ [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], ]: raise NotImplementedError() @@ -839,6 +885,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'EventarcTransport', -) +__all__ = ("EventarcTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/rest.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/rest.py index 3ddf316f5b35..9e9c49dcd99e 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/rest.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/rest.py @@ -29,7 +29,7 @@ from google.api_core import operations_v1 from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from requests import __version__ as requests_version import dataclasses @@ -44,7 +44,9 @@ from google.cloud.eventarc_v1.types import eventarc from google.cloud.eventarc_v1.types import google_api_source from google.cloud.eventarc_v1.types import google_channel_config -from google.cloud.eventarc_v1.types import google_channel_config as gce_google_channel_config +from google.cloud.eventarc_v1.types import ( + google_channel_config as gce_google_channel_config, +) from google.cloud.eventarc_v1.types import message_bus from google.cloud.eventarc_v1.types import pipeline from google.cloud.eventarc_v1.types import trigger @@ -61,6 +63,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -409,7 +412,12 @@ def post_update_trigger(self, response): """ - def pre_create_channel(self, request: eventarc.CreateChannelRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.CreateChannelRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_create_channel( + self, + request: eventarc.CreateChannelRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[eventarc.CreateChannelRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for create_channel Override in a subclass to manipulate the request or metadata @@ -417,7 +425,9 @@ def pre_create_channel(self, request: eventarc.CreateChannelRequest, metadata: S """ return request, metadata - def post_create_channel(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_create_channel( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for create_channel DEPRECATED. Please use the `post_create_channel_with_metadata` @@ -430,7 +440,11 @@ def post_create_channel(self, response: operations_pb2.Operation) -> operations_ """ return response - def post_create_channel_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_create_channel_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for create_channel Override in a subclass to read or manipulate the response or metadata after it @@ -445,7 +459,13 @@ def post_create_channel_with_metadata(self, response: operations_pb2.Operation, """ return response, metadata - def pre_create_channel_connection(self, request: eventarc.CreateChannelConnectionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.CreateChannelConnectionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_create_channel_connection( + self, + request: eventarc.CreateChannelConnectionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + eventarc.CreateChannelConnectionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for create_channel_connection Override in a subclass to manipulate the request or metadata @@ -453,7 +473,9 @@ def pre_create_channel_connection(self, request: eventarc.CreateChannelConnectio """ return request, metadata - def post_create_channel_connection(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_create_channel_connection( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for create_channel_connection DEPRECATED. Please use the `post_create_channel_connection_with_metadata` @@ -466,7 +488,11 @@ def post_create_channel_connection(self, response: operations_pb2.Operation) -> """ return response - def post_create_channel_connection_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_create_channel_connection_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for create_channel_connection Override in a subclass to read or manipulate the response or metadata after it @@ -481,7 +507,13 @@ def post_create_channel_connection_with_metadata(self, response: operations_pb2. """ return response, metadata - def pre_create_enrollment(self, request: eventarc.CreateEnrollmentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.CreateEnrollmentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_create_enrollment( + self, + request: eventarc.CreateEnrollmentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + eventarc.CreateEnrollmentRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for create_enrollment Override in a subclass to manipulate the request or metadata @@ -489,7 +521,9 @@ def pre_create_enrollment(self, request: eventarc.CreateEnrollmentRequest, metad """ return request, metadata - def post_create_enrollment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_create_enrollment( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for create_enrollment DEPRECATED. Please use the `post_create_enrollment_with_metadata` @@ -502,7 +536,11 @@ def post_create_enrollment(self, response: operations_pb2.Operation) -> operatio """ return response - def post_create_enrollment_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_create_enrollment_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for create_enrollment Override in a subclass to read or manipulate the response or metadata after it @@ -517,7 +555,13 @@ def post_create_enrollment_with_metadata(self, response: operations_pb2.Operatio """ return response, metadata - def pre_create_google_api_source(self, request: eventarc.CreateGoogleApiSourceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.CreateGoogleApiSourceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_create_google_api_source( + self, + request: eventarc.CreateGoogleApiSourceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + eventarc.CreateGoogleApiSourceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for create_google_api_source Override in a subclass to manipulate the request or metadata @@ -525,7 +569,9 @@ def pre_create_google_api_source(self, request: eventarc.CreateGoogleApiSourceRe """ return request, metadata - def post_create_google_api_source(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_create_google_api_source( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for create_google_api_source DEPRECATED. Please use the `post_create_google_api_source_with_metadata` @@ -538,7 +584,11 @@ def post_create_google_api_source(self, response: operations_pb2.Operation) -> o """ return response - def post_create_google_api_source_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_create_google_api_source_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for create_google_api_source Override in a subclass to read or manipulate the response or metadata after it @@ -553,7 +603,13 @@ def post_create_google_api_source_with_metadata(self, response: operations_pb2.O """ return response, metadata - def pre_create_message_bus(self, request: eventarc.CreateMessageBusRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.CreateMessageBusRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_create_message_bus( + self, + request: eventarc.CreateMessageBusRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + eventarc.CreateMessageBusRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for create_message_bus Override in a subclass to manipulate the request or metadata @@ -561,7 +617,9 @@ def pre_create_message_bus(self, request: eventarc.CreateMessageBusRequest, meta """ return request, metadata - def post_create_message_bus(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_create_message_bus( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for create_message_bus DEPRECATED. Please use the `post_create_message_bus_with_metadata` @@ -574,7 +632,11 @@ def post_create_message_bus(self, response: operations_pb2.Operation) -> operati """ return response - def post_create_message_bus_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_create_message_bus_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for create_message_bus Override in a subclass to read or manipulate the response or metadata after it @@ -589,7 +651,11 @@ def post_create_message_bus_with_metadata(self, response: operations_pb2.Operati """ return response, metadata - def pre_create_pipeline(self, request: eventarc.CreatePipelineRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.CreatePipelineRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_create_pipeline( + self, + request: eventarc.CreatePipelineRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[eventarc.CreatePipelineRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for create_pipeline Override in a subclass to manipulate the request or metadata @@ -597,7 +663,9 @@ def pre_create_pipeline(self, request: eventarc.CreatePipelineRequest, metadata: """ return request, metadata - def post_create_pipeline(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_create_pipeline( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for create_pipeline DEPRECATED. Please use the `post_create_pipeline_with_metadata` @@ -610,7 +678,11 @@ def post_create_pipeline(self, response: operations_pb2.Operation) -> operations """ return response - def post_create_pipeline_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_create_pipeline_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for create_pipeline Override in a subclass to read or manipulate the response or metadata after it @@ -625,7 +697,11 @@ def post_create_pipeline_with_metadata(self, response: operations_pb2.Operation, """ return response, metadata - def pre_create_trigger(self, request: eventarc.CreateTriggerRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.CreateTriggerRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_create_trigger( + self, + request: eventarc.CreateTriggerRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[eventarc.CreateTriggerRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for create_trigger Override in a subclass to manipulate the request or metadata @@ -633,7 +709,9 @@ def pre_create_trigger(self, request: eventarc.CreateTriggerRequest, metadata: S """ return request, metadata - def post_create_trigger(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_create_trigger( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for create_trigger DEPRECATED. Please use the `post_create_trigger_with_metadata` @@ -646,7 +724,11 @@ def post_create_trigger(self, response: operations_pb2.Operation) -> operations_ """ return response - def post_create_trigger_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_create_trigger_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for create_trigger Override in a subclass to read or manipulate the response or metadata after it @@ -661,7 +743,11 @@ def post_create_trigger_with_metadata(self, response: operations_pb2.Operation, """ return response, metadata - def pre_delete_channel(self, request: eventarc.DeleteChannelRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.DeleteChannelRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_delete_channel( + self, + request: eventarc.DeleteChannelRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[eventarc.DeleteChannelRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for delete_channel Override in a subclass to manipulate the request or metadata @@ -669,7 +755,9 @@ def pre_delete_channel(self, request: eventarc.DeleteChannelRequest, metadata: S """ return request, metadata - def post_delete_channel(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_delete_channel( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for delete_channel DEPRECATED. Please use the `post_delete_channel_with_metadata` @@ -682,7 +770,11 @@ def post_delete_channel(self, response: operations_pb2.Operation) -> operations_ """ return response - def post_delete_channel_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_delete_channel_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for delete_channel Override in a subclass to read or manipulate the response or metadata after it @@ -697,7 +789,13 @@ def post_delete_channel_with_metadata(self, response: operations_pb2.Operation, """ return response, metadata - def pre_delete_channel_connection(self, request: eventarc.DeleteChannelConnectionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.DeleteChannelConnectionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_delete_channel_connection( + self, + request: eventarc.DeleteChannelConnectionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + eventarc.DeleteChannelConnectionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for delete_channel_connection Override in a subclass to manipulate the request or metadata @@ -705,7 +803,9 @@ def pre_delete_channel_connection(self, request: eventarc.DeleteChannelConnectio """ return request, metadata - def post_delete_channel_connection(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_delete_channel_connection( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for delete_channel_connection DEPRECATED. Please use the `post_delete_channel_connection_with_metadata` @@ -718,7 +818,11 @@ def post_delete_channel_connection(self, response: operations_pb2.Operation) -> """ return response - def post_delete_channel_connection_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_delete_channel_connection_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for delete_channel_connection Override in a subclass to read or manipulate the response or metadata after it @@ -733,7 +837,13 @@ def post_delete_channel_connection_with_metadata(self, response: operations_pb2. """ return response, metadata - def pre_delete_enrollment(self, request: eventarc.DeleteEnrollmentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.DeleteEnrollmentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_delete_enrollment( + self, + request: eventarc.DeleteEnrollmentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + eventarc.DeleteEnrollmentRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for delete_enrollment Override in a subclass to manipulate the request or metadata @@ -741,7 +851,9 @@ def pre_delete_enrollment(self, request: eventarc.DeleteEnrollmentRequest, metad """ return request, metadata - def post_delete_enrollment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_delete_enrollment( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for delete_enrollment DEPRECATED. Please use the `post_delete_enrollment_with_metadata` @@ -754,7 +866,11 @@ def post_delete_enrollment(self, response: operations_pb2.Operation) -> operatio """ return response - def post_delete_enrollment_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_delete_enrollment_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for delete_enrollment Override in a subclass to read or manipulate the response or metadata after it @@ -769,7 +885,13 @@ def post_delete_enrollment_with_metadata(self, response: operations_pb2.Operatio """ return response, metadata - def pre_delete_google_api_source(self, request: eventarc.DeleteGoogleApiSourceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.DeleteGoogleApiSourceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_delete_google_api_source( + self, + request: eventarc.DeleteGoogleApiSourceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + eventarc.DeleteGoogleApiSourceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for delete_google_api_source Override in a subclass to manipulate the request or metadata @@ -777,7 +899,9 @@ def pre_delete_google_api_source(self, request: eventarc.DeleteGoogleApiSourceRe """ return request, metadata - def post_delete_google_api_source(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_delete_google_api_source( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for delete_google_api_source DEPRECATED. Please use the `post_delete_google_api_source_with_metadata` @@ -790,7 +914,11 @@ def post_delete_google_api_source(self, response: operations_pb2.Operation) -> o """ return response - def post_delete_google_api_source_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_delete_google_api_source_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for delete_google_api_source Override in a subclass to read or manipulate the response or metadata after it @@ -805,7 +933,13 @@ def post_delete_google_api_source_with_metadata(self, response: operations_pb2.O """ return response, metadata - def pre_delete_message_bus(self, request: eventarc.DeleteMessageBusRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.DeleteMessageBusRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_delete_message_bus( + self, + request: eventarc.DeleteMessageBusRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + eventarc.DeleteMessageBusRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for delete_message_bus Override in a subclass to manipulate the request or metadata @@ -813,7 +947,9 @@ def pre_delete_message_bus(self, request: eventarc.DeleteMessageBusRequest, meta """ return request, metadata - def post_delete_message_bus(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_delete_message_bus( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for delete_message_bus DEPRECATED. Please use the `post_delete_message_bus_with_metadata` @@ -826,7 +962,11 @@ def post_delete_message_bus(self, response: operations_pb2.Operation) -> operati """ return response - def post_delete_message_bus_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_delete_message_bus_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for delete_message_bus Override in a subclass to read or manipulate the response or metadata after it @@ -841,7 +981,11 @@ def post_delete_message_bus_with_metadata(self, response: operations_pb2.Operati """ return response, metadata - def pre_delete_pipeline(self, request: eventarc.DeletePipelineRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.DeletePipelineRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_delete_pipeline( + self, + request: eventarc.DeletePipelineRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[eventarc.DeletePipelineRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for delete_pipeline Override in a subclass to manipulate the request or metadata @@ -849,7 +993,9 @@ def pre_delete_pipeline(self, request: eventarc.DeletePipelineRequest, metadata: """ return request, metadata - def post_delete_pipeline(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_delete_pipeline( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for delete_pipeline DEPRECATED. Please use the `post_delete_pipeline_with_metadata` @@ -862,7 +1008,11 @@ def post_delete_pipeline(self, response: operations_pb2.Operation) -> operations """ return response - def post_delete_pipeline_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_delete_pipeline_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for delete_pipeline Override in a subclass to read or manipulate the response or metadata after it @@ -877,7 +1027,11 @@ def post_delete_pipeline_with_metadata(self, response: operations_pb2.Operation, """ return response, metadata - def pre_delete_trigger(self, request: eventarc.DeleteTriggerRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.DeleteTriggerRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_delete_trigger( + self, + request: eventarc.DeleteTriggerRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[eventarc.DeleteTriggerRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for delete_trigger Override in a subclass to manipulate the request or metadata @@ -885,7 +1039,9 @@ def pre_delete_trigger(self, request: eventarc.DeleteTriggerRequest, metadata: S """ return request, metadata - def post_delete_trigger(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_delete_trigger( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for delete_trigger DEPRECATED. Please use the `post_delete_trigger_with_metadata` @@ -898,7 +1054,11 @@ def post_delete_trigger(self, response: operations_pb2.Operation) -> operations_ """ return response - def post_delete_trigger_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_delete_trigger_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for delete_trigger Override in a subclass to read or manipulate the response or metadata after it @@ -913,7 +1073,11 @@ def post_delete_trigger_with_metadata(self, response: operations_pb2.Operation, """ return response, metadata - def pre_get_channel(self, request: eventarc.GetChannelRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.GetChannelRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_get_channel( + self, + request: eventarc.GetChannelRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[eventarc.GetChannelRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_channel Override in a subclass to manipulate the request or metadata @@ -934,7 +1098,11 @@ def post_get_channel(self, response: channel.Channel) -> channel.Channel: """ return response - def post_get_channel_with_metadata(self, response: channel.Channel, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[channel.Channel, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_channel_with_metadata( + self, + response: channel.Channel, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[channel.Channel, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_channel Override in a subclass to read or manipulate the response or metadata after it @@ -949,7 +1117,13 @@ def post_get_channel_with_metadata(self, response: channel.Channel, metadata: Se """ return response, metadata - def pre_get_channel_connection(self, request: eventarc.GetChannelConnectionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.GetChannelConnectionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_get_channel_connection( + self, + request: eventarc.GetChannelConnectionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + eventarc.GetChannelConnectionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_channel_connection Override in a subclass to manipulate the request or metadata @@ -957,7 +1131,9 @@ def pre_get_channel_connection(self, request: eventarc.GetChannelConnectionReque """ return request, metadata - def post_get_channel_connection(self, response: channel_connection.ChannelConnection) -> channel_connection.ChannelConnection: + def post_get_channel_connection( + self, response: channel_connection.ChannelConnection + ) -> channel_connection.ChannelConnection: """Post-rpc interceptor for get_channel_connection DEPRECATED. Please use the `post_get_channel_connection_with_metadata` @@ -970,7 +1146,13 @@ def post_get_channel_connection(self, response: channel_connection.ChannelConnec """ return response - def post_get_channel_connection_with_metadata(self, response: channel_connection.ChannelConnection, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[channel_connection.ChannelConnection, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_channel_connection_with_metadata( + self, + response: channel_connection.ChannelConnection, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + channel_connection.ChannelConnection, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for get_channel_connection Override in a subclass to read or manipulate the response or metadata after it @@ -985,7 +1167,11 @@ def post_get_channel_connection_with_metadata(self, response: channel_connection """ return response, metadata - def pre_get_enrollment(self, request: eventarc.GetEnrollmentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.GetEnrollmentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_get_enrollment( + self, + request: eventarc.GetEnrollmentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[eventarc.GetEnrollmentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_enrollment Override in a subclass to manipulate the request or metadata @@ -993,7 +1179,9 @@ def pre_get_enrollment(self, request: eventarc.GetEnrollmentRequest, metadata: S """ return request, metadata - def post_get_enrollment(self, response: enrollment.Enrollment) -> enrollment.Enrollment: + def post_get_enrollment( + self, response: enrollment.Enrollment + ) -> enrollment.Enrollment: """Post-rpc interceptor for get_enrollment DEPRECATED. Please use the `post_get_enrollment_with_metadata` @@ -1006,7 +1194,11 @@ def post_get_enrollment(self, response: enrollment.Enrollment) -> enrollment.Enr """ return response - def post_get_enrollment_with_metadata(self, response: enrollment.Enrollment, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[enrollment.Enrollment, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_enrollment_with_metadata( + self, + response: enrollment.Enrollment, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[enrollment.Enrollment, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_enrollment Override in a subclass to read or manipulate the response or metadata after it @@ -1021,7 +1213,13 @@ def post_get_enrollment_with_metadata(self, response: enrollment.Enrollment, met """ return response, metadata - def pre_get_google_api_source(self, request: eventarc.GetGoogleApiSourceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.GetGoogleApiSourceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_get_google_api_source( + self, + request: eventarc.GetGoogleApiSourceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + eventarc.GetGoogleApiSourceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_google_api_source Override in a subclass to manipulate the request or metadata @@ -1029,7 +1227,9 @@ def pre_get_google_api_source(self, request: eventarc.GetGoogleApiSourceRequest, """ return request, metadata - def post_get_google_api_source(self, response: google_api_source.GoogleApiSource) -> google_api_source.GoogleApiSource: + def post_get_google_api_source( + self, response: google_api_source.GoogleApiSource + ) -> google_api_source.GoogleApiSource: """Post-rpc interceptor for get_google_api_source DEPRECATED. Please use the `post_get_google_api_source_with_metadata` @@ -1042,7 +1242,13 @@ def post_get_google_api_source(self, response: google_api_source.GoogleApiSource """ return response - def post_get_google_api_source_with_metadata(self, response: google_api_source.GoogleApiSource, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[google_api_source.GoogleApiSource, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_google_api_source_with_metadata( + self, + response: google_api_source.GoogleApiSource, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + google_api_source.GoogleApiSource, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for get_google_api_source Override in a subclass to read or manipulate the response or metadata after it @@ -1057,7 +1263,13 @@ def post_get_google_api_source_with_metadata(self, response: google_api_source.G """ return response, metadata - def pre_get_google_channel_config(self, request: eventarc.GetGoogleChannelConfigRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.GetGoogleChannelConfigRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_get_google_channel_config( + self, + request: eventarc.GetGoogleChannelConfigRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + eventarc.GetGoogleChannelConfigRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_google_channel_config Override in a subclass to manipulate the request or metadata @@ -1065,7 +1277,9 @@ def pre_get_google_channel_config(self, request: eventarc.GetGoogleChannelConfig """ return request, metadata - def post_get_google_channel_config(self, response: google_channel_config.GoogleChannelConfig) -> google_channel_config.GoogleChannelConfig: + def post_get_google_channel_config( + self, response: google_channel_config.GoogleChannelConfig + ) -> google_channel_config.GoogleChannelConfig: """Post-rpc interceptor for get_google_channel_config DEPRECATED. Please use the `post_get_google_channel_config_with_metadata` @@ -1078,7 +1292,14 @@ def post_get_google_channel_config(self, response: google_channel_config.GoogleC """ return response - def post_get_google_channel_config_with_metadata(self, response: google_channel_config.GoogleChannelConfig, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[google_channel_config.GoogleChannelConfig, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_google_channel_config_with_metadata( + self, + response: google_channel_config.GoogleChannelConfig, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + google_channel_config.GoogleChannelConfig, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for get_google_channel_config Override in a subclass to read or manipulate the response or metadata after it @@ -1093,7 +1314,11 @@ def post_get_google_channel_config_with_metadata(self, response: google_channel_ """ return response, metadata - def pre_get_message_bus(self, request: eventarc.GetMessageBusRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.GetMessageBusRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_get_message_bus( + self, + request: eventarc.GetMessageBusRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[eventarc.GetMessageBusRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_message_bus Override in a subclass to manipulate the request or metadata @@ -1101,7 +1326,9 @@ def pre_get_message_bus(self, request: eventarc.GetMessageBusRequest, metadata: """ return request, metadata - def post_get_message_bus(self, response: message_bus.MessageBus) -> message_bus.MessageBus: + def post_get_message_bus( + self, response: message_bus.MessageBus + ) -> message_bus.MessageBus: """Post-rpc interceptor for get_message_bus DEPRECATED. Please use the `post_get_message_bus_with_metadata` @@ -1114,7 +1341,11 @@ def post_get_message_bus(self, response: message_bus.MessageBus) -> message_bus. """ return response - def post_get_message_bus_with_metadata(self, response: message_bus.MessageBus, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[message_bus.MessageBus, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_message_bus_with_metadata( + self, + response: message_bus.MessageBus, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[message_bus.MessageBus, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_message_bus Override in a subclass to read or manipulate the response or metadata after it @@ -1129,7 +1360,11 @@ def post_get_message_bus_with_metadata(self, response: message_bus.MessageBus, m """ return response, metadata - def pre_get_pipeline(self, request: eventarc.GetPipelineRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.GetPipelineRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_get_pipeline( + self, + request: eventarc.GetPipelineRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[eventarc.GetPipelineRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_pipeline Override in a subclass to manipulate the request or metadata @@ -1150,7 +1385,11 @@ def post_get_pipeline(self, response: pipeline.Pipeline) -> pipeline.Pipeline: """ return response - def post_get_pipeline_with_metadata(self, response: pipeline.Pipeline, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[pipeline.Pipeline, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_pipeline_with_metadata( + self, + response: pipeline.Pipeline, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[pipeline.Pipeline, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_pipeline Override in a subclass to read or manipulate the response or metadata after it @@ -1165,7 +1404,11 @@ def post_get_pipeline_with_metadata(self, response: pipeline.Pipeline, metadata: """ return response, metadata - def pre_get_provider(self, request: eventarc.GetProviderRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.GetProviderRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_get_provider( + self, + request: eventarc.GetProviderRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[eventarc.GetProviderRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_provider Override in a subclass to manipulate the request or metadata @@ -1186,7 +1429,11 @@ def post_get_provider(self, response: discovery.Provider) -> discovery.Provider: """ return response - def post_get_provider_with_metadata(self, response: discovery.Provider, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[discovery.Provider, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_provider_with_metadata( + self, + response: discovery.Provider, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[discovery.Provider, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_provider Override in a subclass to read or manipulate the response or metadata after it @@ -1201,7 +1448,11 @@ def post_get_provider_with_metadata(self, response: discovery.Provider, metadata """ return response, metadata - def pre_get_trigger(self, request: eventarc.GetTriggerRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.GetTriggerRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_get_trigger( + self, + request: eventarc.GetTriggerRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[eventarc.GetTriggerRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_trigger Override in a subclass to manipulate the request or metadata @@ -1222,7 +1473,11 @@ def post_get_trigger(self, response: trigger.Trigger) -> trigger.Trigger: """ return response - def post_get_trigger_with_metadata(self, response: trigger.Trigger, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[trigger.Trigger, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_trigger_with_metadata( + self, + response: trigger.Trigger, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[trigger.Trigger, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_trigger Override in a subclass to read or manipulate the response or metadata after it @@ -1237,7 +1492,13 @@ def post_get_trigger_with_metadata(self, response: trigger.Trigger, metadata: Se """ return response, metadata - def pre_list_channel_connections(self, request: eventarc.ListChannelConnectionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.ListChannelConnectionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_channel_connections( + self, + request: eventarc.ListChannelConnectionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + eventarc.ListChannelConnectionsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_channel_connections Override in a subclass to manipulate the request or metadata @@ -1245,7 +1506,9 @@ def pre_list_channel_connections(self, request: eventarc.ListChannelConnectionsR """ return request, metadata - def post_list_channel_connections(self, response: eventarc.ListChannelConnectionsResponse) -> eventarc.ListChannelConnectionsResponse: + def post_list_channel_connections( + self, response: eventarc.ListChannelConnectionsResponse + ) -> eventarc.ListChannelConnectionsResponse: """Post-rpc interceptor for list_channel_connections DEPRECATED. Please use the `post_list_channel_connections_with_metadata` @@ -1258,7 +1521,13 @@ def post_list_channel_connections(self, response: eventarc.ListChannelConnection """ return response - def post_list_channel_connections_with_metadata(self, response: eventarc.ListChannelConnectionsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.ListChannelConnectionsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_channel_connections_with_metadata( + self, + response: eventarc.ListChannelConnectionsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + eventarc.ListChannelConnectionsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for list_channel_connections Override in a subclass to read or manipulate the response or metadata after it @@ -1273,7 +1542,11 @@ def post_list_channel_connections_with_metadata(self, response: eventarc.ListCha """ return response, metadata - def pre_list_channels(self, request: eventarc.ListChannelsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.ListChannelsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_channels( + self, + request: eventarc.ListChannelsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[eventarc.ListChannelsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for list_channels Override in a subclass to manipulate the request or metadata @@ -1281,7 +1554,9 @@ def pre_list_channels(self, request: eventarc.ListChannelsRequest, metadata: Seq """ return request, metadata - def post_list_channels(self, response: eventarc.ListChannelsResponse) -> eventarc.ListChannelsResponse: + def post_list_channels( + self, response: eventarc.ListChannelsResponse + ) -> eventarc.ListChannelsResponse: """Post-rpc interceptor for list_channels DEPRECATED. Please use the `post_list_channels_with_metadata` @@ -1294,7 +1569,11 @@ def post_list_channels(self, response: eventarc.ListChannelsResponse) -> eventar """ return response - def post_list_channels_with_metadata(self, response: eventarc.ListChannelsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.ListChannelsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_channels_with_metadata( + self, + response: eventarc.ListChannelsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[eventarc.ListChannelsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for list_channels Override in a subclass to read or manipulate the response or metadata after it @@ -1309,7 +1588,13 @@ def post_list_channels_with_metadata(self, response: eventarc.ListChannelsRespon """ return response, metadata - def pre_list_enrollments(self, request: eventarc.ListEnrollmentsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.ListEnrollmentsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_enrollments( + self, + request: eventarc.ListEnrollmentsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + eventarc.ListEnrollmentsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_enrollments Override in a subclass to manipulate the request or metadata @@ -1317,7 +1602,9 @@ def pre_list_enrollments(self, request: eventarc.ListEnrollmentsRequest, metadat """ return request, metadata - def post_list_enrollments(self, response: eventarc.ListEnrollmentsResponse) -> eventarc.ListEnrollmentsResponse: + def post_list_enrollments( + self, response: eventarc.ListEnrollmentsResponse + ) -> eventarc.ListEnrollmentsResponse: """Post-rpc interceptor for list_enrollments DEPRECATED. Please use the `post_list_enrollments_with_metadata` @@ -1330,7 +1617,13 @@ def post_list_enrollments(self, response: eventarc.ListEnrollmentsResponse) -> e """ return response - def post_list_enrollments_with_metadata(self, response: eventarc.ListEnrollmentsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.ListEnrollmentsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_enrollments_with_metadata( + self, + response: eventarc.ListEnrollmentsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + eventarc.ListEnrollmentsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for list_enrollments Override in a subclass to read or manipulate the response or metadata after it @@ -1345,7 +1638,13 @@ def post_list_enrollments_with_metadata(self, response: eventarc.ListEnrollments """ return response, metadata - def pre_list_google_api_sources(self, request: eventarc.ListGoogleApiSourcesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.ListGoogleApiSourcesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_google_api_sources( + self, + request: eventarc.ListGoogleApiSourcesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + eventarc.ListGoogleApiSourcesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_google_api_sources Override in a subclass to manipulate the request or metadata @@ -1353,7 +1652,9 @@ def pre_list_google_api_sources(self, request: eventarc.ListGoogleApiSourcesRequ """ return request, metadata - def post_list_google_api_sources(self, response: eventarc.ListGoogleApiSourcesResponse) -> eventarc.ListGoogleApiSourcesResponse: + def post_list_google_api_sources( + self, response: eventarc.ListGoogleApiSourcesResponse + ) -> eventarc.ListGoogleApiSourcesResponse: """Post-rpc interceptor for list_google_api_sources DEPRECATED. Please use the `post_list_google_api_sources_with_metadata` @@ -1366,7 +1667,13 @@ def post_list_google_api_sources(self, response: eventarc.ListGoogleApiSourcesRe """ return response - def post_list_google_api_sources_with_metadata(self, response: eventarc.ListGoogleApiSourcesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.ListGoogleApiSourcesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_google_api_sources_with_metadata( + self, + response: eventarc.ListGoogleApiSourcesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + eventarc.ListGoogleApiSourcesResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for list_google_api_sources Override in a subclass to read or manipulate the response or metadata after it @@ -1381,7 +1688,14 @@ def post_list_google_api_sources_with_metadata(self, response: eventarc.ListGoog """ return response, metadata - def pre_list_message_bus_enrollments(self, request: eventarc.ListMessageBusEnrollmentsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.ListMessageBusEnrollmentsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_message_bus_enrollments( + self, + request: eventarc.ListMessageBusEnrollmentsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + eventarc.ListMessageBusEnrollmentsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for list_message_bus_enrollments Override in a subclass to manipulate the request or metadata @@ -1389,7 +1703,9 @@ def pre_list_message_bus_enrollments(self, request: eventarc.ListMessageBusEnrol """ return request, metadata - def post_list_message_bus_enrollments(self, response: eventarc.ListMessageBusEnrollmentsResponse) -> eventarc.ListMessageBusEnrollmentsResponse: + def post_list_message_bus_enrollments( + self, response: eventarc.ListMessageBusEnrollmentsResponse + ) -> eventarc.ListMessageBusEnrollmentsResponse: """Post-rpc interceptor for list_message_bus_enrollments DEPRECATED. Please use the `post_list_message_bus_enrollments_with_metadata` @@ -1402,7 +1718,14 @@ def post_list_message_bus_enrollments(self, response: eventarc.ListMessageBusEnr """ return response - def post_list_message_bus_enrollments_with_metadata(self, response: eventarc.ListMessageBusEnrollmentsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.ListMessageBusEnrollmentsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_message_bus_enrollments_with_metadata( + self, + response: eventarc.ListMessageBusEnrollmentsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + eventarc.ListMessageBusEnrollmentsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for list_message_bus_enrollments Override in a subclass to read or manipulate the response or metadata after it @@ -1417,7 +1740,13 @@ def post_list_message_bus_enrollments_with_metadata(self, response: eventarc.Lis """ return response, metadata - def pre_list_message_buses(self, request: eventarc.ListMessageBusesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.ListMessageBusesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_message_buses( + self, + request: eventarc.ListMessageBusesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + eventarc.ListMessageBusesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_message_buses Override in a subclass to manipulate the request or metadata @@ -1425,7 +1754,9 @@ def pre_list_message_buses(self, request: eventarc.ListMessageBusesRequest, meta """ return request, metadata - def post_list_message_buses(self, response: eventarc.ListMessageBusesResponse) -> eventarc.ListMessageBusesResponse: + def post_list_message_buses( + self, response: eventarc.ListMessageBusesResponse + ) -> eventarc.ListMessageBusesResponse: """Post-rpc interceptor for list_message_buses DEPRECATED. Please use the `post_list_message_buses_with_metadata` @@ -1438,7 +1769,13 @@ def post_list_message_buses(self, response: eventarc.ListMessageBusesResponse) - """ return response - def post_list_message_buses_with_metadata(self, response: eventarc.ListMessageBusesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.ListMessageBusesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_message_buses_with_metadata( + self, + response: eventarc.ListMessageBusesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + eventarc.ListMessageBusesResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for list_message_buses Override in a subclass to read or manipulate the response or metadata after it @@ -1453,7 +1790,11 @@ def post_list_message_buses_with_metadata(self, response: eventarc.ListMessageBu """ return response, metadata - def pre_list_pipelines(self, request: eventarc.ListPipelinesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.ListPipelinesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_pipelines( + self, + request: eventarc.ListPipelinesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[eventarc.ListPipelinesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for list_pipelines Override in a subclass to manipulate the request or metadata @@ -1461,7 +1802,9 @@ def pre_list_pipelines(self, request: eventarc.ListPipelinesRequest, metadata: S """ return request, metadata - def post_list_pipelines(self, response: eventarc.ListPipelinesResponse) -> eventarc.ListPipelinesResponse: + def post_list_pipelines( + self, response: eventarc.ListPipelinesResponse + ) -> eventarc.ListPipelinesResponse: """Post-rpc interceptor for list_pipelines DEPRECATED. Please use the `post_list_pipelines_with_metadata` @@ -1474,7 +1817,11 @@ def post_list_pipelines(self, response: eventarc.ListPipelinesResponse) -> event """ return response - def post_list_pipelines_with_metadata(self, response: eventarc.ListPipelinesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.ListPipelinesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_pipelines_with_metadata( + self, + response: eventarc.ListPipelinesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[eventarc.ListPipelinesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for list_pipelines Override in a subclass to read or manipulate the response or metadata after it @@ -1489,7 +1836,11 @@ def post_list_pipelines_with_metadata(self, response: eventarc.ListPipelinesResp """ return response, metadata - def pre_list_providers(self, request: eventarc.ListProvidersRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.ListProvidersRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_providers( + self, + request: eventarc.ListProvidersRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[eventarc.ListProvidersRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for list_providers Override in a subclass to manipulate the request or metadata @@ -1497,7 +1848,9 @@ def pre_list_providers(self, request: eventarc.ListProvidersRequest, metadata: S """ return request, metadata - def post_list_providers(self, response: eventarc.ListProvidersResponse) -> eventarc.ListProvidersResponse: + def post_list_providers( + self, response: eventarc.ListProvidersResponse + ) -> eventarc.ListProvidersResponse: """Post-rpc interceptor for list_providers DEPRECATED. Please use the `post_list_providers_with_metadata` @@ -1510,7 +1863,11 @@ def post_list_providers(self, response: eventarc.ListProvidersResponse) -> event """ return response - def post_list_providers_with_metadata(self, response: eventarc.ListProvidersResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.ListProvidersResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_providers_with_metadata( + self, + response: eventarc.ListProvidersResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[eventarc.ListProvidersResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for list_providers Override in a subclass to read or manipulate the response or metadata after it @@ -1525,7 +1882,11 @@ def post_list_providers_with_metadata(self, response: eventarc.ListProvidersResp """ return response, metadata - def pre_list_triggers(self, request: eventarc.ListTriggersRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.ListTriggersRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_triggers( + self, + request: eventarc.ListTriggersRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[eventarc.ListTriggersRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for list_triggers Override in a subclass to manipulate the request or metadata @@ -1533,7 +1894,9 @@ def pre_list_triggers(self, request: eventarc.ListTriggersRequest, metadata: Seq """ return request, metadata - def post_list_triggers(self, response: eventarc.ListTriggersResponse) -> eventarc.ListTriggersResponse: + def post_list_triggers( + self, response: eventarc.ListTriggersResponse + ) -> eventarc.ListTriggersResponse: """Post-rpc interceptor for list_triggers DEPRECATED. Please use the `post_list_triggers_with_metadata` @@ -1546,7 +1909,11 @@ def post_list_triggers(self, response: eventarc.ListTriggersResponse) -> eventar """ return response - def post_list_triggers_with_metadata(self, response: eventarc.ListTriggersResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.ListTriggersResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_triggers_with_metadata( + self, + response: eventarc.ListTriggersResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[eventarc.ListTriggersResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for list_triggers Override in a subclass to read or manipulate the response or metadata after it @@ -1561,7 +1928,11 @@ def post_list_triggers_with_metadata(self, response: eventarc.ListTriggersRespon """ return response, metadata - def pre_update_channel(self, request: eventarc.UpdateChannelRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.UpdateChannelRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_update_channel( + self, + request: eventarc.UpdateChannelRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[eventarc.UpdateChannelRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for update_channel Override in a subclass to manipulate the request or metadata @@ -1569,7 +1940,9 @@ def pre_update_channel(self, request: eventarc.UpdateChannelRequest, metadata: S """ return request, metadata - def post_update_channel(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_update_channel( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for update_channel DEPRECATED. Please use the `post_update_channel_with_metadata` @@ -1582,7 +1955,11 @@ def post_update_channel(self, response: operations_pb2.Operation) -> operations_ """ return response - def post_update_channel_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_update_channel_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for update_channel Override in a subclass to read or manipulate the response or metadata after it @@ -1597,7 +1974,13 @@ def post_update_channel_with_metadata(self, response: operations_pb2.Operation, """ return response, metadata - def pre_update_enrollment(self, request: eventarc.UpdateEnrollmentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.UpdateEnrollmentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_update_enrollment( + self, + request: eventarc.UpdateEnrollmentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + eventarc.UpdateEnrollmentRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for update_enrollment Override in a subclass to manipulate the request or metadata @@ -1605,7 +1988,9 @@ def pre_update_enrollment(self, request: eventarc.UpdateEnrollmentRequest, metad """ return request, metadata - def post_update_enrollment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_update_enrollment( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for update_enrollment DEPRECATED. Please use the `post_update_enrollment_with_metadata` @@ -1618,7 +2003,11 @@ def post_update_enrollment(self, response: operations_pb2.Operation) -> operatio """ return response - def post_update_enrollment_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_update_enrollment_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for update_enrollment Override in a subclass to read or manipulate the response or metadata after it @@ -1633,7 +2022,13 @@ def post_update_enrollment_with_metadata(self, response: operations_pb2.Operatio """ return response, metadata - def pre_update_google_api_source(self, request: eventarc.UpdateGoogleApiSourceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.UpdateGoogleApiSourceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_update_google_api_source( + self, + request: eventarc.UpdateGoogleApiSourceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + eventarc.UpdateGoogleApiSourceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for update_google_api_source Override in a subclass to manipulate the request or metadata @@ -1641,7 +2036,9 @@ def pre_update_google_api_source(self, request: eventarc.UpdateGoogleApiSourceRe """ return request, metadata - def post_update_google_api_source(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_update_google_api_source( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for update_google_api_source DEPRECATED. Please use the `post_update_google_api_source_with_metadata` @@ -1654,7 +2051,11 @@ def post_update_google_api_source(self, response: operations_pb2.Operation) -> o """ return response - def post_update_google_api_source_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_update_google_api_source_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for update_google_api_source Override in a subclass to read or manipulate the response or metadata after it @@ -1669,7 +2070,14 @@ def post_update_google_api_source_with_metadata(self, response: operations_pb2.O """ return response, metadata - def pre_update_google_channel_config(self, request: eventarc.UpdateGoogleChannelConfigRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.UpdateGoogleChannelConfigRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_update_google_channel_config( + self, + request: eventarc.UpdateGoogleChannelConfigRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + eventarc.UpdateGoogleChannelConfigRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for update_google_channel_config Override in a subclass to manipulate the request or metadata @@ -1677,7 +2085,9 @@ def pre_update_google_channel_config(self, request: eventarc.UpdateGoogleChannel """ return request, metadata - def post_update_google_channel_config(self, response: gce_google_channel_config.GoogleChannelConfig) -> gce_google_channel_config.GoogleChannelConfig: + def post_update_google_channel_config( + self, response: gce_google_channel_config.GoogleChannelConfig + ) -> gce_google_channel_config.GoogleChannelConfig: """Post-rpc interceptor for update_google_channel_config DEPRECATED. Please use the `post_update_google_channel_config_with_metadata` @@ -1690,7 +2100,14 @@ def post_update_google_channel_config(self, response: gce_google_channel_config. """ return response - def post_update_google_channel_config_with_metadata(self, response: gce_google_channel_config.GoogleChannelConfig, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gce_google_channel_config.GoogleChannelConfig, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_update_google_channel_config_with_metadata( + self, + response: gce_google_channel_config.GoogleChannelConfig, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gce_google_channel_config.GoogleChannelConfig, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for update_google_channel_config Override in a subclass to read or manipulate the response or metadata after it @@ -1705,7 +2122,13 @@ def post_update_google_channel_config_with_metadata(self, response: gce_google_c """ return response, metadata - def pre_update_message_bus(self, request: eventarc.UpdateMessageBusRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.UpdateMessageBusRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_update_message_bus( + self, + request: eventarc.UpdateMessageBusRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + eventarc.UpdateMessageBusRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for update_message_bus Override in a subclass to manipulate the request or metadata @@ -1713,7 +2136,9 @@ def pre_update_message_bus(self, request: eventarc.UpdateMessageBusRequest, meta """ return request, metadata - def post_update_message_bus(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_update_message_bus( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for update_message_bus DEPRECATED. Please use the `post_update_message_bus_with_metadata` @@ -1726,7 +2151,11 @@ def post_update_message_bus(self, response: operations_pb2.Operation) -> operati """ return response - def post_update_message_bus_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_update_message_bus_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for update_message_bus Override in a subclass to read or manipulate the response or metadata after it @@ -1741,7 +2170,11 @@ def post_update_message_bus_with_metadata(self, response: operations_pb2.Operati """ return response, metadata - def pre_update_pipeline(self, request: eventarc.UpdatePipelineRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.UpdatePipelineRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_update_pipeline( + self, + request: eventarc.UpdatePipelineRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[eventarc.UpdatePipelineRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for update_pipeline Override in a subclass to manipulate the request or metadata @@ -1749,7 +2182,9 @@ def pre_update_pipeline(self, request: eventarc.UpdatePipelineRequest, metadata: """ return request, metadata - def post_update_pipeline(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_update_pipeline( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for update_pipeline DEPRECATED. Please use the `post_update_pipeline_with_metadata` @@ -1762,7 +2197,11 @@ def post_update_pipeline(self, response: operations_pb2.Operation) -> operations """ return response - def post_update_pipeline_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_update_pipeline_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for update_pipeline Override in a subclass to read or manipulate the response or metadata after it @@ -1777,7 +2216,11 @@ def post_update_pipeline_with_metadata(self, response: operations_pb2.Operation, """ return response, metadata - def pre_update_trigger(self, request: eventarc.UpdateTriggerRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[eventarc.UpdateTriggerRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_update_trigger( + self, + request: eventarc.UpdateTriggerRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[eventarc.UpdateTriggerRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for update_trigger Override in a subclass to manipulate the request or metadata @@ -1785,7 +2228,9 @@ def pre_update_trigger(self, request: eventarc.UpdateTriggerRequest, metadata: S """ return request, metadata - def post_update_trigger(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_update_trigger( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for update_trigger DEPRECATED. Please use the `post_update_trigger_with_metadata` @@ -1798,7 +2243,11 @@ def post_update_trigger(self, response: operations_pb2.Operation) -> operations_ """ return response - def post_update_trigger_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_update_trigger_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for update_trigger Override in a subclass to read or manipulate the response or metadata after it @@ -1814,8 +2263,12 @@ def post_update_trigger_with_metadata(self, response: operations_pb2.Operation, return response, metadata def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_location Override in a subclass to manipulate the request or metadata @@ -1835,8 +2288,12 @@ def post_get_location( return response def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_locations Override in a subclass to manipulate the request or metadata @@ -1856,8 +2313,12 @@ def post_list_locations( return response def pre_get_iam_policy( - self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: iam_policy_pb2.GetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_iam_policy Override in a subclass to manipulate the request or metadata @@ -1865,9 +2326,7 @@ def pre_get_iam_policy( """ return request, metadata - def post_get_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: + def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: """Post-rpc interceptor for get_iam_policy Override in a subclass to manipulate the response @@ -1877,8 +2336,12 @@ def post_get_iam_policy( return response def pre_set_iam_policy( - self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: iam_policy_pb2.SetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for set_iam_policy Override in a subclass to manipulate the request or metadata @@ -1886,9 +2349,7 @@ def pre_set_iam_policy( """ return request, metadata - def post_set_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: + def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: """Post-rpc interceptor for set_iam_policy Override in a subclass to manipulate the response @@ -1898,8 +2359,13 @@ def post_set_iam_policy( return response def pre_test_iam_permissions( - self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.TestIamPermissionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for test_iam_permissions Override in a subclass to manipulate the request or metadata @@ -1919,8 +2385,12 @@ def post_test_iam_permissions( return response def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for cancel_operation Override in a subclass to manipulate the request or metadata @@ -1928,9 +2398,7 @@ def pre_cancel_operation( """ return request, metadata - def post_cancel_operation( - self, response: None - ) -> None: + def post_cancel_operation(self, response: None) -> None: """Post-rpc interceptor for cancel_operation Override in a subclass to manipulate the response @@ -1940,8 +2408,12 @@ def post_cancel_operation( return response def pre_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for delete_operation Override in a subclass to manipulate the request or metadata @@ -1949,9 +2421,7 @@ def pre_delete_operation( """ return request, metadata - def post_delete_operation( - self, response: None - ) -> None: + def post_delete_operation(self, response: None) -> None: """Post-rpc interceptor for delete_operation Override in a subclass to manipulate the response @@ -1961,8 +2431,12 @@ def post_delete_operation( return response def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_operation Override in a subclass to manipulate the request or metadata @@ -1982,8 +2456,12 @@ def post_get_operation( return response def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_operations Override in a subclass to manipulate the request or metadata @@ -2024,62 +2502,63 @@ class EventarcRestTransport(_BaseEventarcRestTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__(self, *, - host: str = 'eventarc.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[EventarcRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: + def __init__( + self, + *, + host: str = "eventarc.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[EventarcRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. - NOTE: This REST transport functionality is currently in a beta - state (preview). We welcome your feedback via a GitHub issue in - this library's repository. Thank you! - - Args: - host (Optional[str]): - The hostname to connect to (default: 'eventarc.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. This argument will be - removed in the next major version of this library. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - interceptor (Optional[EventarcRestInterceptor]): Interceptor used - to manipulate requests, request metadata, and responses. - api_audience (Optional[str]): The intended audience for the API calls - to the service that will be set when using certain 3rd party - authentication flows. Audience is typically a resource identifier. - If not set, the host value will be used as a default. + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to (default: 'eventarc.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[EventarcRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. """ # Run the base constructor # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. @@ -2091,10 +2570,11 @@ def __init__(self, *, client_info=client_info, always_use_jwt_access=always_use_jwt_access, url_scheme=url_scheme, - api_audience=api_audience + api_audience=api_audience, ) self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) + self._credentials, default_host=self.DEFAULT_HOST + ) self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None if client_cert_source_for_mtls: self._session.configure_mtls_channel(client_cert_source_for_mtls) @@ -2111,47 +2591,52 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Only create a new client if we do not already have one. if self._operations_client is None: http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ + "google.longrunning.Operations.CancelOperation": [ { - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", }, ], - 'google.longrunning.Operations.DeleteOperation': [ + "google.longrunning.Operations.DeleteOperation": [ { - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", }, ], - 'google.longrunning.Operations.GetOperation': [ + "google.longrunning.Operations.GetOperation": [ { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", }, ], - 'google.longrunning.Operations.ListOperations': [ + "google.longrunning.Operations.ListOperations": [ { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", }, ], } rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) # Return the client from cache. return self._operations_client - class _CreateChannel(_BaseEventarcRestTransport._BaseCreateChannel, EventarcRestStub): + class _CreateChannel( + _BaseEventarcRestTransport._BaseCreateChannel, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.CreateChannel") @@ -2163,27 +2648,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: eventarc.CreateChannelRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: eventarc.CreateChannelRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the create channel method over HTTP. Args: @@ -2206,32 +2693,48 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseCreateChannel._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseCreateChannel._get_http_options() + ) request, metadata = self._interceptor.pre_create_channel(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseCreateChannel._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseEventarcRestTransport._BaseCreateChannel._get_transcoded_request( + http_options, request + ) + ) - body = _BaseEventarcRestTransport._BaseCreateChannel._get_request_body_json(transcoded_request) + body = _BaseEventarcRestTransport._BaseCreateChannel._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseCreateChannel._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseCreateChannel._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.CreateChannel", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "CreateChannel", "httpRequest": http_request, @@ -2240,7 +2743,15 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._CreateChannel._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = EventarcRestTransport._CreateChannel._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2253,20 +2764,24 @@ def __call__(self, resp = self._interceptor.post_create_channel(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_channel_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_create_channel_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.create_channel_", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "CreateChannel", "metadata": http_response["headers"], @@ -2275,7 +2790,9 @@ def __call__(self, ) return resp - class _CreateChannelConnection(_BaseEventarcRestTransport._BaseCreateChannelConnection, EventarcRestStub): + class _CreateChannelConnection( + _BaseEventarcRestTransport._BaseCreateChannelConnection, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.CreateChannelConnection") @@ -2287,27 +2804,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: eventarc.CreateChannelConnectionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: eventarc.CreateChannelConnectionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the create channel connection method over HTTP. Args: @@ -2330,32 +2849,46 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseCreateChannelConnection._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseCreateChannelConnection._get_http_options() + ) - request, metadata = self._interceptor.pre_create_channel_connection(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseCreateChannelConnection._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_create_channel_connection( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseCreateChannelConnection._get_transcoded_request( + http_options, request + ) - body = _BaseEventarcRestTransport._BaseCreateChannelConnection._get_request_body_json(transcoded_request) + body = _BaseEventarcRestTransport._BaseCreateChannelConnection._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseCreateChannelConnection._get_query_params_json(transcoded_request) + query_params = _BaseEventarcRestTransport._BaseCreateChannelConnection._get_query_params_json( + transcoded_request + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.CreateChannelConnection", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "CreateChannelConnection", "httpRequest": http_request, @@ -2364,7 +2897,15 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._CreateChannelConnection._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = EventarcRestTransport._CreateChannelConnection._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2377,20 +2918,24 @@ def __call__(self, resp = self._interceptor.post_create_channel_connection(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_channel_connection_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_create_channel_connection_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.create_channel_connection", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "CreateChannelConnection", "metadata": http_response["headers"], @@ -2399,7 +2944,9 @@ def __call__(self, ) return resp - class _CreateEnrollment(_BaseEventarcRestTransport._BaseCreateEnrollment, EventarcRestStub): + class _CreateEnrollment( + _BaseEventarcRestTransport._BaseCreateEnrollment, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.CreateEnrollment") @@ -2411,27 +2958,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: eventarc.CreateEnrollmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: eventarc.CreateEnrollmentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the create enrollment method over HTTP. Args: @@ -2454,32 +3003,50 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseCreateEnrollment._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseCreateEnrollment._get_http_options() + ) - request, metadata = self._interceptor.pre_create_enrollment(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseCreateEnrollment._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_create_enrollment( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseCreateEnrollment._get_transcoded_request( + http_options, request + ) - body = _BaseEventarcRestTransport._BaseCreateEnrollment._get_request_body_json(transcoded_request) + body = ( + _BaseEventarcRestTransport._BaseCreateEnrollment._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseCreateEnrollment._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseCreateEnrollment._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.CreateEnrollment", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "CreateEnrollment", "httpRequest": http_request, @@ -2488,7 +3055,15 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._CreateEnrollment._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = EventarcRestTransport._CreateEnrollment._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2501,20 +3076,24 @@ def __call__(self, resp = self._interceptor.post_create_enrollment(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_enrollment_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_create_enrollment_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.create_enrollment", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "CreateEnrollment", "metadata": http_response["headers"], @@ -2523,7 +3102,9 @@ def __call__(self, ) return resp - class _CreateGoogleApiSource(_BaseEventarcRestTransport._BaseCreateGoogleApiSource, EventarcRestStub): + class _CreateGoogleApiSource( + _BaseEventarcRestTransport._BaseCreateGoogleApiSource, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.CreateGoogleApiSource") @@ -2535,27 +3116,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: eventarc.CreateGoogleApiSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: eventarc.CreateGoogleApiSourceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the create google api source method over HTTP. Args: @@ -2578,32 +3161,46 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseCreateGoogleApiSource._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseCreateGoogleApiSource._get_http_options() + ) - request, metadata = self._interceptor.pre_create_google_api_source(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseCreateGoogleApiSource._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_create_google_api_source( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseCreateGoogleApiSource._get_transcoded_request( + http_options, request + ) - body = _BaseEventarcRestTransport._BaseCreateGoogleApiSource._get_request_body_json(transcoded_request) + body = _BaseEventarcRestTransport._BaseCreateGoogleApiSource._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseCreateGoogleApiSource._get_query_params_json(transcoded_request) + query_params = _BaseEventarcRestTransport._BaseCreateGoogleApiSource._get_query_params_json( + transcoded_request + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.CreateGoogleApiSource", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "CreateGoogleApiSource", "httpRequest": http_request, @@ -2612,7 +3209,15 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._CreateGoogleApiSource._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = EventarcRestTransport._CreateGoogleApiSource._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2625,20 +3230,24 @@ def __call__(self, resp = self._interceptor.post_create_google_api_source(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_google_api_source_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_create_google_api_source_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.create_google_api_source", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "CreateGoogleApiSource", "metadata": http_response["headers"], @@ -2647,7 +3256,9 @@ def __call__(self, ) return resp - class _CreateMessageBus(_BaseEventarcRestTransport._BaseCreateMessageBus, EventarcRestStub): + class _CreateMessageBus( + _BaseEventarcRestTransport._BaseCreateMessageBus, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.CreateMessageBus") @@ -2659,27 +3270,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: eventarc.CreateMessageBusRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: eventarc.CreateMessageBusRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the create message bus method over HTTP. Args: @@ -2702,32 +3315,50 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseCreateMessageBus._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseCreateMessageBus._get_http_options() + ) - request, metadata = self._interceptor.pre_create_message_bus(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseCreateMessageBus._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_create_message_bus( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseCreateMessageBus._get_transcoded_request( + http_options, request + ) - body = _BaseEventarcRestTransport._BaseCreateMessageBus._get_request_body_json(transcoded_request) + body = ( + _BaseEventarcRestTransport._BaseCreateMessageBus._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseCreateMessageBus._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseCreateMessageBus._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.CreateMessageBus", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "CreateMessageBus", "httpRequest": http_request, @@ -2736,7 +3367,15 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._CreateMessageBus._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = EventarcRestTransport._CreateMessageBus._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2749,20 +3388,24 @@ def __call__(self, resp = self._interceptor.post_create_message_bus(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_message_bus_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_create_message_bus_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.create_message_bus", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "CreateMessageBus", "metadata": http_response["headers"], @@ -2771,7 +3414,9 @@ def __call__(self, ) return resp - class _CreatePipeline(_BaseEventarcRestTransport._BaseCreatePipeline, EventarcRestStub): + class _CreatePipeline( + _BaseEventarcRestTransport._BaseCreatePipeline, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.CreatePipeline") @@ -2783,27 +3428,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: eventarc.CreatePipelineRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: eventarc.CreatePipelineRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the create pipeline method over HTTP. Args: @@ -2826,32 +3473,50 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseCreatePipeline._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseCreatePipeline._get_http_options() + ) request, metadata = self._interceptor.pre_create_pipeline(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseCreatePipeline._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseEventarcRestTransport._BaseCreatePipeline._get_transcoded_request( + http_options, request + ) + ) - body = _BaseEventarcRestTransport._BaseCreatePipeline._get_request_body_json(transcoded_request) + body = ( + _BaseEventarcRestTransport._BaseCreatePipeline._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseCreatePipeline._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseCreatePipeline._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.CreatePipeline", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "CreatePipeline", "httpRequest": http_request, @@ -2860,7 +3525,15 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._CreatePipeline._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = EventarcRestTransport._CreatePipeline._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2873,20 +3546,24 @@ def __call__(self, resp = self._interceptor.post_create_pipeline(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_pipeline_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_create_pipeline_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.create_pipeline", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "CreatePipeline", "metadata": http_response["headers"], @@ -2895,7 +3572,9 @@ def __call__(self, ) return resp - class _CreateTrigger(_BaseEventarcRestTransport._BaseCreateTrigger, EventarcRestStub): + class _CreateTrigger( + _BaseEventarcRestTransport._BaseCreateTrigger, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.CreateTrigger") @@ -2907,27 +3586,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: eventarc.CreateTriggerRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: eventarc.CreateTriggerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the create trigger method over HTTP. Args: @@ -2950,32 +3631,48 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseCreateTrigger._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseCreateTrigger._get_http_options() + ) request, metadata = self._interceptor.pre_create_trigger(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseCreateTrigger._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseEventarcRestTransport._BaseCreateTrigger._get_transcoded_request( + http_options, request + ) + ) - body = _BaseEventarcRestTransport._BaseCreateTrigger._get_request_body_json(transcoded_request) + body = _BaseEventarcRestTransport._BaseCreateTrigger._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseCreateTrigger._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseCreateTrigger._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.CreateTrigger", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "CreateTrigger", "httpRequest": http_request, @@ -2984,7 +3681,15 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._CreateTrigger._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = EventarcRestTransport._CreateTrigger._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2997,20 +3702,24 @@ def __call__(self, resp = self._interceptor.post_create_trigger(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_trigger_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_create_trigger_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.create_trigger", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "CreateTrigger", "metadata": http_response["headers"], @@ -3019,7 +3728,9 @@ def __call__(self, ) return resp - class _DeleteChannel(_BaseEventarcRestTransport._BaseDeleteChannel, EventarcRestStub): + class _DeleteChannel( + _BaseEventarcRestTransport._BaseDeleteChannel, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.DeleteChannel") @@ -3031,26 +3742,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: eventarc.DeleteChannelRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: eventarc.DeleteChannelRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the delete channel method over HTTP. Args: @@ -3073,30 +3786,44 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseDeleteChannel._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseDeleteChannel._get_http_options() + ) request, metadata = self._interceptor.pre_delete_channel(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseDeleteChannel._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseEventarcRestTransport._BaseDeleteChannel._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseDeleteChannel._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseDeleteChannel._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.DeleteChannel", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "DeleteChannel", "httpRequest": http_request, @@ -3105,7 +3832,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._DeleteChannel._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._DeleteChannel._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3118,20 +3852,24 @@ def __call__(self, resp = self._interceptor.post_delete_channel(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_channel_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_delete_channel_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.delete_channel", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "DeleteChannel", "metadata": http_response["headers"], @@ -3140,7 +3878,9 @@ def __call__(self, ) return resp - class _DeleteChannelConnection(_BaseEventarcRestTransport._BaseDeleteChannelConnection, EventarcRestStub): + class _DeleteChannelConnection( + _BaseEventarcRestTransport._BaseDeleteChannelConnection, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.DeleteChannelConnection") @@ -3152,26 +3892,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: eventarc.DeleteChannelConnectionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: eventarc.DeleteChannelConnectionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the delete channel connection method over HTTP. Args: @@ -3194,30 +3936,42 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseDeleteChannelConnection._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseDeleteChannelConnection._get_http_options() + ) - request, metadata = self._interceptor.pre_delete_channel_connection(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseDeleteChannelConnection._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_delete_channel_connection( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseDeleteChannelConnection._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseDeleteChannelConnection._get_query_params_json(transcoded_request) + query_params = _BaseEventarcRestTransport._BaseDeleteChannelConnection._get_query_params_json( + transcoded_request + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.DeleteChannelConnection", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "DeleteChannelConnection", "httpRequest": http_request, @@ -3226,7 +3980,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._DeleteChannelConnection._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._DeleteChannelConnection._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3239,20 +4000,24 @@ def __call__(self, resp = self._interceptor.post_delete_channel_connection(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_channel_connection_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_delete_channel_connection_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.delete_channel_connection", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "DeleteChannelConnection", "metadata": http_response["headers"], @@ -3261,7 +4026,9 @@ def __call__(self, ) return resp - class _DeleteEnrollment(_BaseEventarcRestTransport._BaseDeleteEnrollment, EventarcRestStub): + class _DeleteEnrollment( + _BaseEventarcRestTransport._BaseDeleteEnrollment, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.DeleteEnrollment") @@ -3273,26 +4040,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: eventarc.DeleteEnrollmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: eventarc.DeleteEnrollmentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the delete enrollment method over HTTP. Args: @@ -3315,30 +4084,44 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseDeleteEnrollment._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseDeleteEnrollment._get_http_options() + ) - request, metadata = self._interceptor.pre_delete_enrollment(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseDeleteEnrollment._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_delete_enrollment( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseDeleteEnrollment._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseDeleteEnrollment._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseDeleteEnrollment._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.DeleteEnrollment", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "DeleteEnrollment", "httpRequest": http_request, @@ -3347,7 +4130,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._DeleteEnrollment._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._DeleteEnrollment._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3360,20 +4150,24 @@ def __call__(self, resp = self._interceptor.post_delete_enrollment(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_enrollment_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_delete_enrollment_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.delete_enrollment", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "DeleteEnrollment", "metadata": http_response["headers"], @@ -3382,7 +4176,9 @@ def __call__(self, ) return resp - class _DeleteGoogleApiSource(_BaseEventarcRestTransport._BaseDeleteGoogleApiSource, EventarcRestStub): + class _DeleteGoogleApiSource( + _BaseEventarcRestTransport._BaseDeleteGoogleApiSource, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.DeleteGoogleApiSource") @@ -3394,26 +4190,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: eventarc.DeleteGoogleApiSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: eventarc.DeleteGoogleApiSourceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the delete google api source method over HTTP. Args: @@ -3436,30 +4234,42 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseDeleteGoogleApiSource._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseDeleteGoogleApiSource._get_http_options() + ) - request, metadata = self._interceptor.pre_delete_google_api_source(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseDeleteGoogleApiSource._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_delete_google_api_source( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseDeleteGoogleApiSource._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseDeleteGoogleApiSource._get_query_params_json(transcoded_request) + query_params = _BaseEventarcRestTransport._BaseDeleteGoogleApiSource._get_query_params_json( + transcoded_request + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.DeleteGoogleApiSource", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "DeleteGoogleApiSource", "httpRequest": http_request, @@ -3468,7 +4278,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._DeleteGoogleApiSource._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._DeleteGoogleApiSource._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3481,20 +4298,24 @@ def __call__(self, resp = self._interceptor.post_delete_google_api_source(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_google_api_source_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_delete_google_api_source_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.delete_google_api_source", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "DeleteGoogleApiSource", "metadata": http_response["headers"], @@ -3503,7 +4324,9 @@ def __call__(self, ) return resp - class _DeleteMessageBus(_BaseEventarcRestTransport._BaseDeleteMessageBus, EventarcRestStub): + class _DeleteMessageBus( + _BaseEventarcRestTransport._BaseDeleteMessageBus, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.DeleteMessageBus") @@ -3515,26 +4338,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: eventarc.DeleteMessageBusRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: eventarc.DeleteMessageBusRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the delete message bus method over HTTP. Args: @@ -3557,30 +4382,44 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseDeleteMessageBus._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseDeleteMessageBus._get_http_options() + ) - request, metadata = self._interceptor.pre_delete_message_bus(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseDeleteMessageBus._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_delete_message_bus( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseDeleteMessageBus._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseDeleteMessageBus._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseDeleteMessageBus._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.DeleteMessageBus", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "DeleteMessageBus", "httpRequest": http_request, @@ -3589,7 +4428,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._DeleteMessageBus._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._DeleteMessageBus._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3602,20 +4448,24 @@ def __call__(self, resp = self._interceptor.post_delete_message_bus(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_message_bus_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_delete_message_bus_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.delete_message_bus", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "DeleteMessageBus", "metadata": http_response["headers"], @@ -3624,7 +4474,9 @@ def __call__(self, ) return resp - class _DeletePipeline(_BaseEventarcRestTransport._BaseDeletePipeline, EventarcRestStub): + class _DeletePipeline( + _BaseEventarcRestTransport._BaseDeletePipeline, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.DeletePipeline") @@ -3636,26 +4488,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: eventarc.DeletePipelineRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: eventarc.DeletePipelineRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the delete pipeline method over HTTP. Args: @@ -3678,30 +4532,44 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseDeletePipeline._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseDeletePipeline._get_http_options() + ) request, metadata = self._interceptor.pre_delete_pipeline(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseDeletePipeline._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseEventarcRestTransport._BaseDeletePipeline._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseDeletePipeline._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseDeletePipeline._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.DeletePipeline", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "DeletePipeline", "httpRequest": http_request, @@ -3710,7 +4578,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._DeletePipeline._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._DeletePipeline._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3723,20 +4598,24 @@ def __call__(self, resp = self._interceptor.post_delete_pipeline(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_pipeline_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_delete_pipeline_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.delete_pipeline", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "DeletePipeline", "metadata": http_response["headers"], @@ -3745,7 +4624,9 @@ def __call__(self, ) return resp - class _DeleteTrigger(_BaseEventarcRestTransport._BaseDeleteTrigger, EventarcRestStub): + class _DeleteTrigger( + _BaseEventarcRestTransport._BaseDeleteTrigger, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.DeleteTrigger") @@ -3757,26 +4638,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: eventarc.DeleteTriggerRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: eventarc.DeleteTriggerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the delete trigger method over HTTP. Args: @@ -3799,30 +4682,44 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseDeleteTrigger._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseDeleteTrigger._get_http_options() + ) request, metadata = self._interceptor.pre_delete_trigger(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseDeleteTrigger._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseEventarcRestTransport._BaseDeleteTrigger._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseDeleteTrigger._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseDeleteTrigger._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.DeleteTrigger", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "DeleteTrigger", "httpRequest": http_request, @@ -3831,7 +4728,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._DeleteTrigger._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._DeleteTrigger._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3844,20 +4748,24 @@ def __call__(self, resp = self._interceptor.post_delete_trigger(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_trigger_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_delete_trigger_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.delete_trigger", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "DeleteTrigger", "metadata": http_response["headers"], @@ -3878,26 +4786,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: eventarc.GetChannelRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> channel.Channel: + def __call__( + self, + request: eventarc.GetChannelRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> channel.Channel: r"""Call the get channel method over HTTP. Args: @@ -3925,30 +4835,44 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseGetChannel._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseGetChannel._get_http_options() + ) request, metadata = self._interceptor.pre_get_channel(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseGetChannel._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseEventarcRestTransport._BaseGetChannel._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseGetChannel._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseGetChannel._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.GetChannel", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "GetChannel", "httpRequest": http_request, @@ -3957,7 +4881,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._GetChannel._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._GetChannel._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3972,20 +4903,24 @@ def __call__(self, resp = self._interceptor.post_get_channel(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_channel_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_channel_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = channel.Channel.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.get_channel", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "GetChannel", "metadata": http_response["headers"], @@ -3994,7 +4929,9 @@ def __call__(self, ) return resp - class _GetChannelConnection(_BaseEventarcRestTransport._BaseGetChannelConnection, EventarcRestStub): + class _GetChannelConnection( + _BaseEventarcRestTransport._BaseGetChannelConnection, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.GetChannelConnection") @@ -4006,26 +4943,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: eventarc.GetChannelConnectionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> channel_connection.ChannelConnection: + def __call__( + self, + request: eventarc.GetChannelConnectionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> channel_connection.ChannelConnection: r"""Call the get channel connection method over HTTP. Args: @@ -4052,30 +4991,42 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseGetChannelConnection._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseGetChannelConnection._get_http_options() + ) - request, metadata = self._interceptor.pre_get_channel_connection(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseGetChannelConnection._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_get_channel_connection( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseGetChannelConnection._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseGetChannelConnection._get_query_params_json(transcoded_request) + query_params = _BaseEventarcRestTransport._BaseGetChannelConnection._get_query_params_json( + transcoded_request + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.GetChannelConnection", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "GetChannelConnection", "httpRequest": http_request, @@ -4084,7 +5035,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._GetChannelConnection._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._GetChannelConnection._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -4099,20 +5057,26 @@ def __call__(self, resp = self._interceptor.post_get_channel_connection(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_channel_connection_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_channel_connection_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = channel_connection.ChannelConnection.to_json(response) + response_payload = channel_connection.ChannelConnection.to_json( + response + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.get_channel_connection", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "GetChannelConnection", "metadata": http_response["headers"], @@ -4121,7 +5085,9 @@ def __call__(self, ) return resp - class _GetEnrollment(_BaseEventarcRestTransport._BaseGetEnrollment, EventarcRestStub): + class _GetEnrollment( + _BaseEventarcRestTransport._BaseGetEnrollment, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.GetEnrollment") @@ -4133,26 +5099,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: eventarc.GetEnrollmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> enrollment.Enrollment: + def __call__( + self, + request: eventarc.GetEnrollmentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> enrollment.Enrollment: r"""Call the get enrollment method over HTTP. Args: @@ -4178,30 +5146,44 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseGetEnrollment._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseGetEnrollment._get_http_options() + ) request, metadata = self._interceptor.pre_get_enrollment(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseGetEnrollment._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseEventarcRestTransport._BaseGetEnrollment._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseGetEnrollment._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseGetEnrollment._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.GetEnrollment", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "GetEnrollment", "httpRequest": http_request, @@ -4210,7 +5192,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._GetEnrollment._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._GetEnrollment._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -4225,20 +5214,24 @@ def __call__(self, resp = self._interceptor.post_get_enrollment(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_enrollment_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_enrollment_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = enrollment.Enrollment.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.get_enrollment", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "GetEnrollment", "metadata": http_response["headers"], @@ -4247,7 +5240,9 @@ def __call__(self, ) return resp - class _GetGoogleApiSource(_BaseEventarcRestTransport._BaseGetGoogleApiSource, EventarcRestStub): + class _GetGoogleApiSource( + _BaseEventarcRestTransport._BaseGetGoogleApiSource, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.GetGoogleApiSource") @@ -4259,26 +5254,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: eventarc.GetGoogleApiSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> google_api_source.GoogleApiSource: + def __call__( + self, + request: eventarc.GetGoogleApiSourceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> google_api_source.GoogleApiSource: r"""Call the get google api source method over HTTP. Args: @@ -4301,30 +5298,42 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseGetGoogleApiSource._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseGetGoogleApiSource._get_http_options() + ) - request, metadata = self._interceptor.pre_get_google_api_source(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseGetGoogleApiSource._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_get_google_api_source( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseGetGoogleApiSource._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseGetGoogleApiSource._get_query_params_json(transcoded_request) + query_params = _BaseEventarcRestTransport._BaseGetGoogleApiSource._get_query_params_json( + transcoded_request + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.GetGoogleApiSource", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "GetGoogleApiSource", "httpRequest": http_request, @@ -4333,7 +5342,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._GetGoogleApiSource._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._GetGoogleApiSource._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -4348,20 +5364,26 @@ def __call__(self, resp = self._interceptor.post_get_google_api_source(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_google_api_source_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_google_api_source_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = google_api_source.GoogleApiSource.to_json(response) + response_payload = google_api_source.GoogleApiSource.to_json( + response + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.get_google_api_source", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "GetGoogleApiSource", "metadata": http_response["headers"], @@ -4370,7 +5392,9 @@ def __call__(self, ) return resp - class _GetGoogleChannelConfig(_BaseEventarcRestTransport._BaseGetGoogleChannelConfig, EventarcRestStub): + class _GetGoogleChannelConfig( + _BaseEventarcRestTransport._BaseGetGoogleChannelConfig, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.GetGoogleChannelConfig") @@ -4382,26 +5406,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: eventarc.GetGoogleChannelConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> google_channel_config.GoogleChannelConfig: + def __call__( + self, + request: eventarc.GetGoogleChannelConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> google_channel_config.GoogleChannelConfig: r"""Call the get google channel config method over HTTP. Args: @@ -4429,30 +5455,42 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseGetGoogleChannelConfig._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseGetGoogleChannelConfig._get_http_options() + ) - request, metadata = self._interceptor.pre_get_google_channel_config(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseGetGoogleChannelConfig._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_get_google_channel_config( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseGetGoogleChannelConfig._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseGetGoogleChannelConfig._get_query_params_json(transcoded_request) + query_params = _BaseEventarcRestTransport._BaseGetGoogleChannelConfig._get_query_params_json( + transcoded_request + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.GetGoogleChannelConfig", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "GetGoogleChannelConfig", "httpRequest": http_request, @@ -4461,7 +5499,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._GetGoogleChannelConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._GetGoogleChannelConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -4476,20 +5521,26 @@ def __call__(self, resp = self._interceptor.post_get_google_channel_config(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_google_channel_config_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_google_channel_config_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = google_channel_config.GoogleChannelConfig.to_json(response) + response_payload = ( + google_channel_config.GoogleChannelConfig.to_json(response) + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.get_google_channel_config", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "GetGoogleChannelConfig", "metadata": http_response["headers"], @@ -4498,7 +5549,9 @@ def __call__(self, ) return resp - class _GetMessageBus(_BaseEventarcRestTransport._BaseGetMessageBus, EventarcRestStub): + class _GetMessageBus( + _BaseEventarcRestTransport._BaseGetMessageBus, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.GetMessageBus") @@ -4510,26 +5563,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: eventarc.GetMessageBusRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> message_bus.MessageBus: + def __call__( + self, + request: eventarc.GetMessageBusRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> message_bus.MessageBus: r"""Call the get message bus method over HTTP. Args: @@ -4557,30 +5612,44 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseGetMessageBus._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseGetMessageBus._get_http_options() + ) request, metadata = self._interceptor.pre_get_message_bus(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseGetMessageBus._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseEventarcRestTransport._BaseGetMessageBus._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseGetMessageBus._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseGetMessageBus._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.GetMessageBus", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "GetMessageBus", "httpRequest": http_request, @@ -4589,7 +5658,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._GetMessageBus._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._GetMessageBus._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -4604,20 +5680,24 @@ def __call__(self, resp = self._interceptor.post_get_message_bus(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_message_bus_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_message_bus_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = message_bus.MessageBus.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.get_message_bus", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "GetMessageBus", "metadata": http_response["headers"], @@ -4638,26 +5718,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: eventarc.GetPipelineRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> pipeline.Pipeline: + def __call__( + self, + request: eventarc.GetPipelineRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pipeline.Pipeline: r"""Call the get pipeline method over HTTP. Args: @@ -4679,30 +5761,44 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseGetPipeline._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseGetPipeline._get_http_options() + ) request, metadata = self._interceptor.pre_get_pipeline(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseGetPipeline._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseEventarcRestTransport._BaseGetPipeline._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseGetPipeline._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseGetPipeline._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.GetPipeline", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "GetPipeline", "httpRequest": http_request, @@ -4711,7 +5807,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._GetPipeline._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._GetPipeline._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -4726,20 +5829,24 @@ def __call__(self, resp = self._interceptor.post_get_pipeline(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_pipeline_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_pipeline_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = pipeline.Pipeline.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.get_pipeline", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "GetPipeline", "metadata": http_response["headers"], @@ -4760,26 +5867,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: eventarc.GetProviderRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> discovery.Provider: + def __call__( + self, + request: eventarc.GetProviderRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> discovery.Provider: r"""Call the get provider method over HTTP. Args: @@ -4801,30 +5910,44 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseGetProvider._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseGetProvider._get_http_options() + ) request, metadata = self._interceptor.pre_get_provider(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseGetProvider._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseEventarcRestTransport._BaseGetProvider._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseGetProvider._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseGetProvider._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.GetProvider", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "GetProvider", "httpRequest": http_request, @@ -4833,7 +5956,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._GetProvider._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._GetProvider._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -4848,20 +5978,24 @@ def __call__(self, resp = self._interceptor.post_get_provider(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_provider_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_provider_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = discovery.Provider.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.get_provider", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "GetProvider", "metadata": http_response["headers"], @@ -4882,26 +6016,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: eventarc.GetTriggerRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> trigger.Trigger: + def __call__( + self, + request: eventarc.GetTriggerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> trigger.Trigger: r"""Call the get trigger method over HTTP. Args: @@ -4923,30 +6059,44 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseGetTrigger._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseGetTrigger._get_http_options() + ) request, metadata = self._interceptor.pre_get_trigger(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseGetTrigger._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseEventarcRestTransport._BaseGetTrigger._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseGetTrigger._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseGetTrigger._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.GetTrigger", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "GetTrigger", "httpRequest": http_request, @@ -4955,7 +6105,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._GetTrigger._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._GetTrigger._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -4970,20 +6127,24 @@ def __call__(self, resp = self._interceptor.post_get_trigger(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_trigger_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_trigger_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = trigger.Trigger.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.get_trigger", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "GetTrigger", "metadata": http_response["headers"], @@ -4992,7 +6153,9 @@ def __call__(self, ) return resp - class _ListChannelConnections(_BaseEventarcRestTransport._BaseListChannelConnections, EventarcRestStub): + class _ListChannelConnections( + _BaseEventarcRestTransport._BaseListChannelConnections, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.ListChannelConnections") @@ -5004,26 +6167,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: eventarc.ListChannelConnectionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> eventarc.ListChannelConnectionsResponse: + def __call__( + self, + request: eventarc.ListChannelConnectionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> eventarc.ListChannelConnectionsResponse: r"""Call the list channel connections method over HTTP. Args: @@ -5045,30 +6210,42 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseListChannelConnections._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseListChannelConnections._get_http_options() + ) - request, metadata = self._interceptor.pre_list_channel_connections(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseListChannelConnections._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_list_channel_connections( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseListChannelConnections._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseListChannelConnections._get_query_params_json(transcoded_request) + query_params = _BaseEventarcRestTransport._BaseListChannelConnections._get_query_params_json( + transcoded_request + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.ListChannelConnections", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "ListChannelConnections", "httpRequest": http_request, @@ -5077,7 +6254,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._ListChannelConnections._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._ListChannelConnections._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -5092,20 +6276,26 @@ def __call__(self, resp = self._interceptor.post_list_channel_connections(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_channel_connections_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_channel_connections_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = eventarc.ListChannelConnectionsResponse.to_json(response) + response_payload = eventarc.ListChannelConnectionsResponse.to_json( + response + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.list_channel_connections", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "ListChannelConnections", "metadata": http_response["headers"], @@ -5126,26 +6316,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: eventarc.ListChannelsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> eventarc.ListChannelsResponse: + def __call__( + self, + request: eventarc.ListChannelsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> eventarc.ListChannelsResponse: r"""Call the list channels method over HTTP. Args: @@ -5165,30 +6357,44 @@ def __call__(self, The response message for the ``ListChannels`` method. """ - http_options = _BaseEventarcRestTransport._BaseListChannels._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseListChannels._get_http_options() + ) request, metadata = self._interceptor.pre_list_channels(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseListChannels._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseEventarcRestTransport._BaseListChannels._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseListChannels._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseListChannels._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.ListChannels", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "ListChannels", "httpRequest": http_request, @@ -5197,7 +6403,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._ListChannels._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._ListChannels._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -5212,20 +6425,24 @@ def __call__(self, resp = self._interceptor.post_list_channels(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_channels_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_channels_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = eventarc.ListChannelsResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.list_channels", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "ListChannels", "metadata": http_response["headers"], @@ -5234,7 +6451,9 @@ def __call__(self, ) return resp - class _ListEnrollments(_BaseEventarcRestTransport._BaseListEnrollments, EventarcRestStub): + class _ListEnrollments( + _BaseEventarcRestTransport._BaseListEnrollments, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.ListEnrollments") @@ -5246,26 +6465,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: eventarc.ListEnrollmentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> eventarc.ListEnrollmentsResponse: + def __call__( + self, + request: eventarc.ListEnrollmentsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> eventarc.ListEnrollmentsResponse: r"""Call the list enrollments method over HTTP. Args: @@ -5285,30 +6506,46 @@ def __call__(self, The response message for the ``ListEnrollments`` method. """ - http_options = _BaseEventarcRestTransport._BaseListEnrollments._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseListEnrollments._get_http_options() + ) - request, metadata = self._interceptor.pre_list_enrollments(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseListEnrollments._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_list_enrollments( + request, metadata + ) + transcoded_request = ( + _BaseEventarcRestTransport._BaseListEnrollments._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseListEnrollments._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseListEnrollments._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.ListEnrollments", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "ListEnrollments", "httpRequest": http_request, @@ -5317,7 +6554,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._ListEnrollments._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._ListEnrollments._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -5332,20 +6576,26 @@ def __call__(self, resp = self._interceptor.post_list_enrollments(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_enrollments_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_enrollments_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = eventarc.ListEnrollmentsResponse.to_json(response) + response_payload = eventarc.ListEnrollmentsResponse.to_json( + response + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.list_enrollments", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "ListEnrollments", "metadata": http_response["headers"], @@ -5354,7 +6604,9 @@ def __call__(self, ) return resp - class _ListGoogleApiSources(_BaseEventarcRestTransport._BaseListGoogleApiSources, EventarcRestStub): + class _ListGoogleApiSources( + _BaseEventarcRestTransport._BaseListGoogleApiSources, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.ListGoogleApiSources") @@ -5366,26 +6618,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: eventarc.ListGoogleApiSourcesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> eventarc.ListGoogleApiSourcesResponse: + def __call__( + self, + request: eventarc.ListGoogleApiSourcesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> eventarc.ListGoogleApiSourcesResponse: r"""Call the list google api sources method over HTTP. Args: @@ -5407,30 +6661,42 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseListGoogleApiSources._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseListGoogleApiSources._get_http_options() + ) - request, metadata = self._interceptor.pre_list_google_api_sources(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseListGoogleApiSources._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_list_google_api_sources( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseListGoogleApiSources._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseListGoogleApiSources._get_query_params_json(transcoded_request) + query_params = _BaseEventarcRestTransport._BaseListGoogleApiSources._get_query_params_json( + transcoded_request + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.ListGoogleApiSources", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "ListGoogleApiSources", "httpRequest": http_request, @@ -5439,7 +6705,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._ListGoogleApiSources._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._ListGoogleApiSources._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -5454,20 +6727,26 @@ def __call__(self, resp = self._interceptor.post_list_google_api_sources(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_google_api_sources_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_google_api_sources_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = eventarc.ListGoogleApiSourcesResponse.to_json(response) + response_payload = eventarc.ListGoogleApiSourcesResponse.to_json( + response + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.list_google_api_sources", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "ListGoogleApiSources", "metadata": http_response["headers"], @@ -5476,7 +6755,9 @@ def __call__(self, ) return resp - class _ListMessageBusEnrollments(_BaseEventarcRestTransport._BaseListMessageBusEnrollments, EventarcRestStub): + class _ListMessageBusEnrollments( + _BaseEventarcRestTransport._BaseListMessageBusEnrollments, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.ListMessageBusEnrollments") @@ -5488,72 +6769,86 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: eventarc.ListMessageBusEnrollmentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> eventarc.ListMessageBusEnrollmentsResponse: + def __call__( + self, + request: eventarc.ListMessageBusEnrollmentsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> eventarc.ListMessageBusEnrollmentsResponse: r"""Call the list message bus - enrollments method over HTTP. - - Args: - request (~.eventarc.ListMessageBusEnrollmentsRequest): - The request object. The request message for the - ``ListMessageBusEnrollments`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.eventarc.ListMessageBusEnrollmentsResponse: - The response message for the - ``ListMessageBusEnrollments`` method.\` + enrollments method over HTTP. + + Args: + request (~.eventarc.ListMessageBusEnrollmentsRequest): + The request object. The request message for the + ``ListMessageBusEnrollments`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.eventarc.ListMessageBusEnrollmentsResponse: + The response message for the + ``ListMessageBusEnrollments`` method.\` """ - http_options = _BaseEventarcRestTransport._BaseListMessageBusEnrollments._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseListMessageBusEnrollments._get_http_options() + ) - request, metadata = self._interceptor.pre_list_message_bus_enrollments(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseListMessageBusEnrollments._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_list_message_bus_enrollments( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseListMessageBusEnrollments._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseListMessageBusEnrollments._get_query_params_json(transcoded_request) + query_params = _BaseEventarcRestTransport._BaseListMessageBusEnrollments._get_query_params_json( + transcoded_request + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.ListMessageBusEnrollments", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "ListMessageBusEnrollments", "httpRequest": http_request, @@ -5562,7 +6857,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._ListMessageBusEnrollments._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._ListMessageBusEnrollments._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -5577,20 +6879,26 @@ def __call__(self, resp = self._interceptor.post_list_message_bus_enrollments(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_message_bus_enrollments_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_message_bus_enrollments_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = eventarc.ListMessageBusEnrollmentsResponse.to_json(response) + response_payload = ( + eventarc.ListMessageBusEnrollmentsResponse.to_json(response) + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.list_message_bus_enrollments", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "ListMessageBusEnrollments", "metadata": http_response["headers"], @@ -5599,7 +6907,9 @@ def __call__(self, ) return resp - class _ListMessageBuses(_BaseEventarcRestTransport._BaseListMessageBuses, EventarcRestStub): + class _ListMessageBuses( + _BaseEventarcRestTransport._BaseListMessageBuses, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.ListMessageBuses") @@ -5611,26 +6921,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: eventarc.ListMessageBusesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> eventarc.ListMessageBusesResponse: + def __call__( + self, + request: eventarc.ListMessageBusesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> eventarc.ListMessageBusesResponse: r"""Call the list message buses method over HTTP. Args: @@ -5652,30 +6964,44 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseListMessageBuses._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseListMessageBuses._get_http_options() + ) - request, metadata = self._interceptor.pre_list_message_buses(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseListMessageBuses._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_list_message_buses( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseListMessageBuses._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseListMessageBuses._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseListMessageBuses._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.ListMessageBuses", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "ListMessageBuses", "httpRequest": http_request, @@ -5684,7 +7010,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._ListMessageBuses._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._ListMessageBuses._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -5699,20 +7032,26 @@ def __call__(self, resp = self._interceptor.post_list_message_buses(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_message_buses_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_message_buses_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = eventarc.ListMessageBusesResponse.to_json(response) + response_payload = eventarc.ListMessageBusesResponse.to_json( + response + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.list_message_buses", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "ListMessageBuses", "metadata": http_response["headers"], @@ -5721,7 +7060,9 @@ def __call__(self, ) return resp - class _ListPipelines(_BaseEventarcRestTransport._BaseListPipelines, EventarcRestStub): + class _ListPipelines( + _BaseEventarcRestTransport._BaseListPipelines, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.ListPipelines") @@ -5733,26 +7074,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: eventarc.ListPipelinesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> eventarc.ListPipelinesResponse: + def __call__( + self, + request: eventarc.ListPipelinesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> eventarc.ListPipelinesResponse: r"""Call the list pipelines method over HTTP. Args: @@ -5774,30 +7117,44 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseListPipelines._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseListPipelines._get_http_options() + ) request, metadata = self._interceptor.pre_list_pipelines(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseListPipelines._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseEventarcRestTransport._BaseListPipelines._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseListPipelines._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseListPipelines._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.ListPipelines", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "ListPipelines", "httpRequest": http_request, @@ -5806,7 +7163,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._ListPipelines._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._ListPipelines._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -5821,20 +7185,24 @@ def __call__(self, resp = self._interceptor.post_list_pipelines(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_pipelines_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_pipelines_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = eventarc.ListPipelinesResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.list_pipelines", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "ListPipelines", "metadata": http_response["headers"], @@ -5843,7 +7211,9 @@ def __call__(self, ) return resp - class _ListProviders(_BaseEventarcRestTransport._BaseListProviders, EventarcRestStub): + class _ListProviders( + _BaseEventarcRestTransport._BaseListProviders, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.ListProviders") @@ -5855,26 +7225,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: eventarc.ListProvidersRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> eventarc.ListProvidersResponse: + def __call__( + self, + request: eventarc.ListProvidersRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> eventarc.ListProvidersResponse: r"""Call the list providers method over HTTP. Args: @@ -5894,30 +7266,44 @@ def __call__(self, The response message for the ``ListProviders`` method. """ - http_options = _BaseEventarcRestTransport._BaseListProviders._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseListProviders._get_http_options() + ) request, metadata = self._interceptor.pre_list_providers(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseListProviders._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseEventarcRestTransport._BaseListProviders._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseListProviders._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseListProviders._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.ListProviders", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "ListProviders", "httpRequest": http_request, @@ -5926,7 +7312,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._ListProviders._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._ListProviders._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -5941,20 +7334,24 @@ def __call__(self, resp = self._interceptor.post_list_providers(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_providers_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_providers_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = eventarc.ListProvidersResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.list_providers", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "ListProviders", "metadata": http_response["headers"], @@ -5975,26 +7372,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: eventarc.ListTriggersRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> eventarc.ListTriggersResponse: + def __call__( + self, + request: eventarc.ListTriggersRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> eventarc.ListTriggersResponse: r"""Call the list triggers method over HTTP. Args: @@ -6014,30 +7413,44 @@ def __call__(self, The response message for the ``ListTriggers`` method. """ - http_options = _BaseEventarcRestTransport._BaseListTriggers._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseListTriggers._get_http_options() + ) request, metadata = self._interceptor.pre_list_triggers(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseListTriggers._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseEventarcRestTransport._BaseListTriggers._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseListTriggers._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseListTriggers._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.ListTriggers", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "ListTriggers", "httpRequest": http_request, @@ -6046,7 +7459,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._ListTriggers._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._ListTriggers._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -6061,20 +7481,24 @@ def __call__(self, resp = self._interceptor.post_list_triggers(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_triggers_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_triggers_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = eventarc.ListTriggersResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.list_triggers", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "ListTriggers", "metadata": http_response["headers"], @@ -6083,7 +7507,9 @@ def __call__(self, ) return resp - class _UpdateChannel(_BaseEventarcRestTransport._BaseUpdateChannel, EventarcRestStub): + class _UpdateChannel( + _BaseEventarcRestTransport._BaseUpdateChannel, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.UpdateChannel") @@ -6095,27 +7521,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: eventarc.UpdateChannelRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: eventarc.UpdateChannelRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the update channel method over HTTP. Args: @@ -6138,32 +7566,48 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseUpdateChannel._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseUpdateChannel._get_http_options() + ) request, metadata = self._interceptor.pre_update_channel(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseUpdateChannel._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseEventarcRestTransport._BaseUpdateChannel._get_transcoded_request( + http_options, request + ) + ) - body = _BaseEventarcRestTransport._BaseUpdateChannel._get_request_body_json(transcoded_request) + body = _BaseEventarcRestTransport._BaseUpdateChannel._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseUpdateChannel._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseUpdateChannel._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.UpdateChannel", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "UpdateChannel", "httpRequest": http_request, @@ -6172,7 +7616,15 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._UpdateChannel._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = EventarcRestTransport._UpdateChannel._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -6185,20 +7637,24 @@ def __call__(self, resp = self._interceptor.post_update_channel(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_channel_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_update_channel_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.update_channel", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "UpdateChannel", "metadata": http_response["headers"], @@ -6207,7 +7663,9 @@ def __call__(self, ) return resp - class _UpdateEnrollment(_BaseEventarcRestTransport._BaseUpdateEnrollment, EventarcRestStub): + class _UpdateEnrollment( + _BaseEventarcRestTransport._BaseUpdateEnrollment, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.UpdateEnrollment") @@ -6219,27 +7677,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: eventarc.UpdateEnrollmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: eventarc.UpdateEnrollmentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the update enrollment method over HTTP. Args: @@ -6262,32 +7722,50 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseUpdateEnrollment._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseUpdateEnrollment._get_http_options() + ) - request, metadata = self._interceptor.pre_update_enrollment(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseUpdateEnrollment._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_update_enrollment( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseUpdateEnrollment._get_transcoded_request( + http_options, request + ) - body = _BaseEventarcRestTransport._BaseUpdateEnrollment._get_request_body_json(transcoded_request) + body = ( + _BaseEventarcRestTransport._BaseUpdateEnrollment._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseUpdateEnrollment._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseUpdateEnrollment._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.UpdateEnrollment", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "UpdateEnrollment", "httpRequest": http_request, @@ -6296,7 +7774,15 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._UpdateEnrollment._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = EventarcRestTransport._UpdateEnrollment._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -6309,20 +7795,24 @@ def __call__(self, resp = self._interceptor.post_update_enrollment(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_enrollment_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_update_enrollment_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.update_enrollment", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "UpdateEnrollment", "metadata": http_response["headers"], @@ -6331,7 +7821,9 @@ def __call__(self, ) return resp - class _UpdateGoogleApiSource(_BaseEventarcRestTransport._BaseUpdateGoogleApiSource, EventarcRestStub): + class _UpdateGoogleApiSource( + _BaseEventarcRestTransport._BaseUpdateGoogleApiSource, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.UpdateGoogleApiSource") @@ -6343,27 +7835,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: eventarc.UpdateGoogleApiSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: eventarc.UpdateGoogleApiSourceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the update google api source method over HTTP. Args: @@ -6386,32 +7880,46 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseUpdateGoogleApiSource._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseUpdateGoogleApiSource._get_http_options() + ) - request, metadata = self._interceptor.pre_update_google_api_source(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseUpdateGoogleApiSource._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_update_google_api_source( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseUpdateGoogleApiSource._get_transcoded_request( + http_options, request + ) - body = _BaseEventarcRestTransport._BaseUpdateGoogleApiSource._get_request_body_json(transcoded_request) + body = _BaseEventarcRestTransport._BaseUpdateGoogleApiSource._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseUpdateGoogleApiSource._get_query_params_json(transcoded_request) + query_params = _BaseEventarcRestTransport._BaseUpdateGoogleApiSource._get_query_params_json( + transcoded_request + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.UpdateGoogleApiSource", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "UpdateGoogleApiSource", "httpRequest": http_request, @@ -6420,7 +7928,15 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._UpdateGoogleApiSource._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = EventarcRestTransport._UpdateGoogleApiSource._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -6433,20 +7949,24 @@ def __call__(self, resp = self._interceptor.post_update_google_api_source(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_google_api_source_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_update_google_api_source_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.update_google_api_source", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "UpdateGoogleApiSource", "metadata": http_response["headers"], @@ -6455,7 +7975,9 @@ def __call__(self, ) return resp - class _UpdateGoogleChannelConfig(_BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig, EventarcRestStub): + class _UpdateGoogleChannelConfig( + _BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.UpdateGoogleChannelConfig") @@ -6467,81 +7989,97 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: eventarc.UpdateGoogleChannelConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> gce_google_channel_config.GoogleChannelConfig: + def __call__( + self, + request: eventarc.UpdateGoogleChannelConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gce_google_channel_config.GoogleChannelConfig: r"""Call the update google channel - config method over HTTP. - - Args: - request (~.eventarc.UpdateGoogleChannelConfigRequest): - The request object. The request message for the - UpdateGoogleChannelConfig method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.gce_google_channel_config.GoogleChannelConfig: - A GoogleChannelConfig is a resource - that stores the custom settings - respected by Eventarc first-party - triggers in the matching region. Once - configured, first-party event data will - be protected using the specified custom - managed encryption key instead of - Google-managed encryption keys. + config method over HTTP. + + Args: + request (~.eventarc.UpdateGoogleChannelConfigRequest): + The request object. The request message for the + UpdateGoogleChannelConfig method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gce_google_channel_config.GoogleChannelConfig: + A GoogleChannelConfig is a resource + that stores the custom settings + respected by Eventarc first-party + triggers in the matching region. Once + configured, first-party event data will + be protected using the specified custom + managed encryption key instead of + Google-managed encryption keys. """ - http_options = _BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig._get_http_options() + ) - request, metadata = self._interceptor.pre_update_google_channel_config(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_update_google_channel_config( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig._get_transcoded_request( + http_options, request + ) - body = _BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig._get_request_body_json(transcoded_request) + body = _BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig._get_query_params_json(transcoded_request) + query_params = _BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig._get_query_params_json( + transcoded_request + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.UpdateGoogleChannelConfig", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "UpdateGoogleChannelConfig", "httpRequest": http_request, @@ -6550,7 +8088,15 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._UpdateGoogleChannelConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = EventarcRestTransport._UpdateGoogleChannelConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -6565,20 +8111,26 @@ def __call__(self, resp = self._interceptor.post_update_google_channel_config(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_google_channel_config_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_update_google_channel_config_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = gce_google_channel_config.GoogleChannelConfig.to_json(response) + response_payload = ( + gce_google_channel_config.GoogleChannelConfig.to_json(response) + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.update_google_channel_config", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "UpdateGoogleChannelConfig", "metadata": http_response["headers"], @@ -6587,7 +8139,9 @@ def __call__(self, ) return resp - class _UpdateMessageBus(_BaseEventarcRestTransport._BaseUpdateMessageBus, EventarcRestStub): + class _UpdateMessageBus( + _BaseEventarcRestTransport._BaseUpdateMessageBus, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.UpdateMessageBus") @@ -6599,27 +8153,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: eventarc.UpdateMessageBusRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: eventarc.UpdateMessageBusRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the update message bus method over HTTP. Args: @@ -6642,32 +8198,50 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseUpdateMessageBus._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseUpdateMessageBus._get_http_options() + ) - request, metadata = self._interceptor.pre_update_message_bus(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseUpdateMessageBus._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_update_message_bus( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseUpdateMessageBus._get_transcoded_request( + http_options, request + ) - body = _BaseEventarcRestTransport._BaseUpdateMessageBus._get_request_body_json(transcoded_request) + body = ( + _BaseEventarcRestTransport._BaseUpdateMessageBus._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseUpdateMessageBus._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseUpdateMessageBus._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.UpdateMessageBus", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "UpdateMessageBus", "httpRequest": http_request, @@ -6676,7 +8250,15 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._UpdateMessageBus._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = EventarcRestTransport._UpdateMessageBus._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -6689,20 +8271,24 @@ def __call__(self, resp = self._interceptor.post_update_message_bus(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_message_bus_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_update_message_bus_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.update_message_bus", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "UpdateMessageBus", "metadata": http_response["headers"], @@ -6711,7 +8297,9 @@ def __call__(self, ) return resp - class _UpdatePipeline(_BaseEventarcRestTransport._BaseUpdatePipeline, EventarcRestStub): + class _UpdatePipeline( + _BaseEventarcRestTransport._BaseUpdatePipeline, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.UpdatePipeline") @@ -6723,27 +8311,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: eventarc.UpdatePipelineRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: eventarc.UpdatePipelineRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the update pipeline method over HTTP. Args: @@ -6766,32 +8356,50 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseUpdatePipeline._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseUpdatePipeline._get_http_options() + ) request, metadata = self._interceptor.pre_update_pipeline(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseUpdatePipeline._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseEventarcRestTransport._BaseUpdatePipeline._get_transcoded_request( + http_options, request + ) + ) - body = _BaseEventarcRestTransport._BaseUpdatePipeline._get_request_body_json(transcoded_request) + body = ( + _BaseEventarcRestTransport._BaseUpdatePipeline._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseUpdatePipeline._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseUpdatePipeline._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.UpdatePipeline", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "UpdatePipeline", "httpRequest": http_request, @@ -6800,7 +8408,15 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._UpdatePipeline._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = EventarcRestTransport._UpdatePipeline._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -6813,20 +8429,24 @@ def __call__(self, resp = self._interceptor.post_update_pipeline(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_pipeline_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_update_pipeline_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.update_pipeline", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "UpdatePipeline", "metadata": http_response["headers"], @@ -6835,7 +8455,9 @@ def __call__(self, ) return resp - class _UpdateTrigger(_BaseEventarcRestTransport._BaseUpdateTrigger, EventarcRestStub): + class _UpdateTrigger( + _BaseEventarcRestTransport._BaseUpdateTrigger, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.UpdateTrigger") @@ -6847,27 +8469,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: eventarc.UpdateTriggerRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: eventarc.UpdateTriggerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the update trigger method over HTTP. Args: @@ -6890,32 +8514,48 @@ def __call__(self, """ - http_options = _BaseEventarcRestTransport._BaseUpdateTrigger._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseUpdateTrigger._get_http_options() + ) request, metadata = self._interceptor.pre_update_trigger(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseUpdateTrigger._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseEventarcRestTransport._BaseUpdateTrigger._get_transcoded_request( + http_options, request + ) + ) - body = _BaseEventarcRestTransport._BaseUpdateTrigger._get_request_body_json(transcoded_request) + body = _BaseEventarcRestTransport._BaseUpdateTrigger._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseUpdateTrigger._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseUpdateTrigger._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.UpdateTrigger", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "UpdateTrigger", "httpRequest": http_request, @@ -6924,7 +8564,15 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._UpdateTrigger._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = EventarcRestTransport._UpdateTrigger._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -6937,20 +8585,24 @@ def __call__(self, resp = self._interceptor.post_update_trigger(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_trigger_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_update_trigger_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcClient.update_trigger", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "UpdateTrigger", "metadata": http_response["headers"], @@ -6960,320 +8612,336 @@ def __call__(self, return resp @property - def create_channel_(self) -> Callable[ - [eventarc.CreateChannelRequest], - operations_pb2.Operation]: + def create_channel_( + self, + ) -> Callable[[eventarc.CreateChannelRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._CreateChannel(self._session, self._host, self._interceptor) # type: ignore + return self._CreateChannel(self._session, self._host, self._interceptor) # type: ignore @property - def create_channel_connection(self) -> Callable[ - [eventarc.CreateChannelConnectionRequest], - operations_pb2.Operation]: + def create_channel_connection( + self, + ) -> Callable[[eventarc.CreateChannelConnectionRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._CreateChannelConnection(self._session, self._host, self._interceptor) # type: ignore + return self._CreateChannelConnection(self._session, self._host, self._interceptor) # type: ignore @property - def create_enrollment(self) -> Callable[ - [eventarc.CreateEnrollmentRequest], - operations_pb2.Operation]: + def create_enrollment( + self, + ) -> Callable[[eventarc.CreateEnrollmentRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._CreateEnrollment(self._session, self._host, self._interceptor) # type: ignore + return self._CreateEnrollment(self._session, self._host, self._interceptor) # type: ignore @property - def create_google_api_source(self) -> Callable[ - [eventarc.CreateGoogleApiSourceRequest], - operations_pb2.Operation]: + def create_google_api_source( + self, + ) -> Callable[[eventarc.CreateGoogleApiSourceRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._CreateGoogleApiSource(self._session, self._host, self._interceptor) # type: ignore + return self._CreateGoogleApiSource(self._session, self._host, self._interceptor) # type: ignore @property - def create_message_bus(self) -> Callable[ - [eventarc.CreateMessageBusRequest], - operations_pb2.Operation]: + def create_message_bus( + self, + ) -> Callable[[eventarc.CreateMessageBusRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._CreateMessageBus(self._session, self._host, self._interceptor) # type: ignore + return self._CreateMessageBus(self._session, self._host, self._interceptor) # type: ignore @property - def create_pipeline(self) -> Callable[ - [eventarc.CreatePipelineRequest], - operations_pb2.Operation]: + def create_pipeline( + self, + ) -> Callable[[eventarc.CreatePipelineRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._CreatePipeline(self._session, self._host, self._interceptor) # type: ignore + return self._CreatePipeline(self._session, self._host, self._interceptor) # type: ignore @property - def create_trigger(self) -> Callable[ - [eventarc.CreateTriggerRequest], - operations_pb2.Operation]: + def create_trigger( + self, + ) -> Callable[[eventarc.CreateTriggerRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._CreateTrigger(self._session, self._host, self._interceptor) # type: ignore + return self._CreateTrigger(self._session, self._host, self._interceptor) # type: ignore @property - def delete_channel(self) -> Callable[ - [eventarc.DeleteChannelRequest], - operations_pb2.Operation]: + def delete_channel( + self, + ) -> Callable[[eventarc.DeleteChannelRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._DeleteChannel(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteChannel(self._session, self._host, self._interceptor) # type: ignore @property - def delete_channel_connection(self) -> Callable[ - [eventarc.DeleteChannelConnectionRequest], - operations_pb2.Operation]: + def delete_channel_connection( + self, + ) -> Callable[[eventarc.DeleteChannelConnectionRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._DeleteChannelConnection(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteChannelConnection(self._session, self._host, self._interceptor) # type: ignore @property - def delete_enrollment(self) -> Callable[ - [eventarc.DeleteEnrollmentRequest], - operations_pb2.Operation]: + def delete_enrollment( + self, + ) -> Callable[[eventarc.DeleteEnrollmentRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._DeleteEnrollment(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteEnrollment(self._session, self._host, self._interceptor) # type: ignore @property - def delete_google_api_source(self) -> Callable[ - [eventarc.DeleteGoogleApiSourceRequest], - operations_pb2.Operation]: + def delete_google_api_source( + self, + ) -> Callable[[eventarc.DeleteGoogleApiSourceRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._DeleteGoogleApiSource(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteGoogleApiSource(self._session, self._host, self._interceptor) # type: ignore @property - def delete_message_bus(self) -> Callable[ - [eventarc.DeleteMessageBusRequest], - operations_pb2.Operation]: + def delete_message_bus( + self, + ) -> Callable[[eventarc.DeleteMessageBusRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._DeleteMessageBus(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteMessageBus(self._session, self._host, self._interceptor) # type: ignore @property - def delete_pipeline(self) -> Callable[ - [eventarc.DeletePipelineRequest], - operations_pb2.Operation]: + def delete_pipeline( + self, + ) -> Callable[[eventarc.DeletePipelineRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._DeletePipeline(self._session, self._host, self._interceptor) # type: ignore + return self._DeletePipeline(self._session, self._host, self._interceptor) # type: ignore @property - def delete_trigger(self) -> Callable[ - [eventarc.DeleteTriggerRequest], - operations_pb2.Operation]: + def delete_trigger( + self, + ) -> Callable[[eventarc.DeleteTriggerRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._DeleteTrigger(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteTrigger(self._session, self._host, self._interceptor) # type: ignore @property - def get_channel(self) -> Callable[ - [eventarc.GetChannelRequest], - channel.Channel]: + def get_channel(self) -> Callable[[eventarc.GetChannelRequest], channel.Channel]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._GetChannel(self._session, self._host, self._interceptor) # type: ignore + return self._GetChannel(self._session, self._host, self._interceptor) # type: ignore @property - def get_channel_connection(self) -> Callable[ - [eventarc.GetChannelConnectionRequest], - channel_connection.ChannelConnection]: + def get_channel_connection( + self, + ) -> Callable[ + [eventarc.GetChannelConnectionRequest], channel_connection.ChannelConnection + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._GetChannelConnection(self._session, self._host, self._interceptor) # type: ignore + return self._GetChannelConnection(self._session, self._host, self._interceptor) # type: ignore @property - def get_enrollment(self) -> Callable[ - [eventarc.GetEnrollmentRequest], - enrollment.Enrollment]: + def get_enrollment( + self, + ) -> Callable[[eventarc.GetEnrollmentRequest], enrollment.Enrollment]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._GetEnrollment(self._session, self._host, self._interceptor) # type: ignore + return self._GetEnrollment(self._session, self._host, self._interceptor) # type: ignore @property - def get_google_api_source(self) -> Callable[ - [eventarc.GetGoogleApiSourceRequest], - google_api_source.GoogleApiSource]: + def get_google_api_source( + self, + ) -> Callable[ + [eventarc.GetGoogleApiSourceRequest], google_api_source.GoogleApiSource + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._GetGoogleApiSource(self._session, self._host, self._interceptor) # type: ignore + return self._GetGoogleApiSource(self._session, self._host, self._interceptor) # type: ignore @property - def get_google_channel_config(self) -> Callable[ - [eventarc.GetGoogleChannelConfigRequest], - google_channel_config.GoogleChannelConfig]: + def get_google_channel_config( + self, + ) -> Callable[ + [eventarc.GetGoogleChannelConfigRequest], + google_channel_config.GoogleChannelConfig, + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._GetGoogleChannelConfig(self._session, self._host, self._interceptor) # type: ignore + return self._GetGoogleChannelConfig(self._session, self._host, self._interceptor) # type: ignore @property - def get_message_bus(self) -> Callable[ - [eventarc.GetMessageBusRequest], - message_bus.MessageBus]: + def get_message_bus( + self, + ) -> Callable[[eventarc.GetMessageBusRequest], message_bus.MessageBus]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._GetMessageBus(self._session, self._host, self._interceptor) # type: ignore + return self._GetMessageBus(self._session, self._host, self._interceptor) # type: ignore @property - def get_pipeline(self) -> Callable[ - [eventarc.GetPipelineRequest], - pipeline.Pipeline]: + def get_pipeline( + self, + ) -> Callable[[eventarc.GetPipelineRequest], pipeline.Pipeline]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._GetPipeline(self._session, self._host, self._interceptor) # type: ignore + return self._GetPipeline(self._session, self._host, self._interceptor) # type: ignore @property - def get_provider(self) -> Callable[ - [eventarc.GetProviderRequest], - discovery.Provider]: + def get_provider( + self, + ) -> Callable[[eventarc.GetProviderRequest], discovery.Provider]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._GetProvider(self._session, self._host, self._interceptor) # type: ignore + return self._GetProvider(self._session, self._host, self._interceptor) # type: ignore @property - def get_trigger(self) -> Callable[ - [eventarc.GetTriggerRequest], - trigger.Trigger]: + def get_trigger(self) -> Callable[[eventarc.GetTriggerRequest], trigger.Trigger]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._GetTrigger(self._session, self._host, self._interceptor) # type: ignore + return self._GetTrigger(self._session, self._host, self._interceptor) # type: ignore @property - def list_channel_connections(self) -> Callable[ - [eventarc.ListChannelConnectionsRequest], - eventarc.ListChannelConnectionsResponse]: + def list_channel_connections( + self, + ) -> Callable[ + [eventarc.ListChannelConnectionsRequest], + eventarc.ListChannelConnectionsResponse, + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._ListChannelConnections(self._session, self._host, self._interceptor) # type: ignore + return self._ListChannelConnections(self._session, self._host, self._interceptor) # type: ignore @property - def list_channels(self) -> Callable[ - [eventarc.ListChannelsRequest], - eventarc.ListChannelsResponse]: + def list_channels( + self, + ) -> Callable[[eventarc.ListChannelsRequest], eventarc.ListChannelsResponse]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._ListChannels(self._session, self._host, self._interceptor) # type: ignore + return self._ListChannels(self._session, self._host, self._interceptor) # type: ignore @property - def list_enrollments(self) -> Callable[ - [eventarc.ListEnrollmentsRequest], - eventarc.ListEnrollmentsResponse]: + def list_enrollments( + self, + ) -> Callable[[eventarc.ListEnrollmentsRequest], eventarc.ListEnrollmentsResponse]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._ListEnrollments(self._session, self._host, self._interceptor) # type: ignore + return self._ListEnrollments(self._session, self._host, self._interceptor) # type: ignore @property - def list_google_api_sources(self) -> Callable[ - [eventarc.ListGoogleApiSourcesRequest], - eventarc.ListGoogleApiSourcesResponse]: + def list_google_api_sources( + self, + ) -> Callable[ + [eventarc.ListGoogleApiSourcesRequest], eventarc.ListGoogleApiSourcesResponse + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._ListGoogleApiSources(self._session, self._host, self._interceptor) # type: ignore + return self._ListGoogleApiSources(self._session, self._host, self._interceptor) # type: ignore @property - def list_message_bus_enrollments(self) -> Callable[ - [eventarc.ListMessageBusEnrollmentsRequest], - eventarc.ListMessageBusEnrollmentsResponse]: + def list_message_bus_enrollments( + self, + ) -> Callable[ + [eventarc.ListMessageBusEnrollmentsRequest], + eventarc.ListMessageBusEnrollmentsResponse, + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._ListMessageBusEnrollments(self._session, self._host, self._interceptor) # type: ignore + return self._ListMessageBusEnrollments(self._session, self._host, self._interceptor) # type: ignore @property - def list_message_buses(self) -> Callable[ - [eventarc.ListMessageBusesRequest], - eventarc.ListMessageBusesResponse]: + def list_message_buses( + self, + ) -> Callable[ + [eventarc.ListMessageBusesRequest], eventarc.ListMessageBusesResponse + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._ListMessageBuses(self._session, self._host, self._interceptor) # type: ignore + return self._ListMessageBuses(self._session, self._host, self._interceptor) # type: ignore @property - def list_pipelines(self) -> Callable[ - [eventarc.ListPipelinesRequest], - eventarc.ListPipelinesResponse]: + def list_pipelines( + self, + ) -> Callable[[eventarc.ListPipelinesRequest], eventarc.ListPipelinesResponse]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._ListPipelines(self._session, self._host, self._interceptor) # type: ignore + return self._ListPipelines(self._session, self._host, self._interceptor) # type: ignore @property - def list_providers(self) -> Callable[ - [eventarc.ListProvidersRequest], - eventarc.ListProvidersResponse]: + def list_providers( + self, + ) -> Callable[[eventarc.ListProvidersRequest], eventarc.ListProvidersResponse]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._ListProviders(self._session, self._host, self._interceptor) # type: ignore + return self._ListProviders(self._session, self._host, self._interceptor) # type: ignore @property - def list_triggers(self) -> Callable[ - [eventarc.ListTriggersRequest], - eventarc.ListTriggersResponse]: + def list_triggers( + self, + ) -> Callable[[eventarc.ListTriggersRequest], eventarc.ListTriggersResponse]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._ListTriggers(self._session, self._host, self._interceptor) # type: ignore + return self._ListTriggers(self._session, self._host, self._interceptor) # type: ignore @property - def update_channel(self) -> Callable[ - [eventarc.UpdateChannelRequest], - operations_pb2.Operation]: + def update_channel( + self, + ) -> Callable[[eventarc.UpdateChannelRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._UpdateChannel(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateChannel(self._session, self._host, self._interceptor) # type: ignore @property - def update_enrollment(self) -> Callable[ - [eventarc.UpdateEnrollmentRequest], - operations_pb2.Operation]: + def update_enrollment( + self, + ) -> Callable[[eventarc.UpdateEnrollmentRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._UpdateEnrollment(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateEnrollment(self._session, self._host, self._interceptor) # type: ignore @property - def update_google_api_source(self) -> Callable[ - [eventarc.UpdateGoogleApiSourceRequest], - operations_pb2.Operation]: + def update_google_api_source( + self, + ) -> Callable[[eventarc.UpdateGoogleApiSourceRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._UpdateGoogleApiSource(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateGoogleApiSource(self._session, self._host, self._interceptor) # type: ignore @property - def update_google_channel_config(self) -> Callable[ - [eventarc.UpdateGoogleChannelConfigRequest], - gce_google_channel_config.GoogleChannelConfig]: + def update_google_channel_config( + self, + ) -> Callable[ + [eventarc.UpdateGoogleChannelConfigRequest], + gce_google_channel_config.GoogleChannelConfig, + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._UpdateGoogleChannelConfig(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateGoogleChannelConfig(self._session, self._host, self._interceptor) # type: ignore @property - def update_message_bus(self) -> Callable[ - [eventarc.UpdateMessageBusRequest], - operations_pb2.Operation]: + def update_message_bus( + self, + ) -> Callable[[eventarc.UpdateMessageBusRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._UpdateMessageBus(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateMessageBus(self._session, self._host, self._interceptor) # type: ignore @property - def update_pipeline(self) -> Callable[ - [eventarc.UpdatePipelineRequest], - operations_pb2.Operation]: + def update_pipeline( + self, + ) -> Callable[[eventarc.UpdatePipelineRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._UpdatePipeline(self._session, self._host, self._interceptor) # type: ignore + return self._UpdatePipeline(self._session, self._host, self._interceptor) # type: ignore @property - def update_trigger(self) -> Callable[ - [eventarc.UpdateTriggerRequest], - operations_pb2.Operation]: + def update_trigger( + self, + ) -> Callable[[eventarc.UpdateTriggerRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._UpdateTrigger(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateTrigger(self._session, self._host, self._interceptor) # type: ignore @property def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore class _GetLocation(_BaseEventarcRestTransport._BaseGetLocation, EventarcRestStub): def __hash__(self): @@ -7287,27 +8955,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> locations_pb2.Location: - + def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: r"""Call the get location method over HTTP. Args: @@ -7325,30 +8994,44 @@ def __call__(self, locations_pb2.Location: Response from GetLocation method. """ - http_options = _BaseEventarcRestTransport._BaseGetLocation._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseGetLocation._get_http_options() + ) request, metadata = self._interceptor.pre_get_location(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseEventarcRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseGetLocation._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.GetLocation", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "GetLocation", "httpRequest": http_request, @@ -7357,7 +9040,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -7368,19 +9058,21 @@ def __call__(self, resp = locations_pb2.Location() resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_location(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcAsyncClient.GetLocation", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "GetLocation", "httpResponse": http_response, @@ -7391,9 +9083,11 @@ def __call__(self, @property def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - class _ListLocations(_BaseEventarcRestTransport._BaseListLocations, EventarcRestStub): + class _ListLocations( + _BaseEventarcRestTransport._BaseListLocations, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.ListLocations") @@ -7405,27 +9099,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> locations_pb2.ListLocationsResponse: - + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: r"""Call the list locations method over HTTP. Args: @@ -7443,30 +9138,44 @@ def __call__(self, locations_pb2.ListLocationsResponse: Response from ListLocations method. """ - http_options = _BaseEventarcRestTransport._BaseListLocations._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseListLocations._get_http_options() + ) request, metadata = self._interceptor.pre_list_locations(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseListLocations._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseEventarcRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseListLocations._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseListLocations._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.ListLocations", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "ListLocations", "httpRequest": http_request, @@ -7475,7 +9184,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -7486,19 +9202,21 @@ def __call__(self, resp = locations_pb2.ListLocationsResponse() resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_locations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcAsyncClient.ListLocations", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "ListLocations", "httpResponse": http_response, @@ -7509,7 +9227,7 @@ def __call__(self, @property def get_iam_policy(self): - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore class _GetIamPolicy(_BaseEventarcRestTransport._BaseGetIamPolicy, EventarcRestStub): def __hash__(self): @@ -7523,27 +9241,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> policy_pb2.Policy: - + def __call__( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: r"""Call the get iam policy method over HTTP. Args: @@ -7561,30 +9280,44 @@ def __call__(self, policy_pb2.Policy: Response from GetIamPolicy method. """ - http_options = _BaseEventarcRestTransport._BaseGetIamPolicy._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseGetIamPolicy._get_http_options() + ) request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseEventarcRestTransport._BaseGetIamPolicy._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseGetIamPolicy._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.GetIamPolicy", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "GetIamPolicy", "httpRequest": http_request, @@ -7593,7 +9326,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._GetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -7604,19 +9344,21 @@ def __call__(self, resp = policy_pb2.Policy() resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_iam_policy(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcAsyncClient.GetIamPolicy", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "GetIamPolicy", "httpResponse": http_response, @@ -7627,7 +9369,7 @@ def __call__(self, @property def set_iam_policy(self): - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore class _SetIamPolicy(_BaseEventarcRestTransport._BaseSetIamPolicy, EventarcRestStub): def __hash__(self): @@ -7641,28 +9383,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> policy_pb2.Policy: - + def __call__( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: r"""Call the set iam policy method over HTTP. Args: @@ -7680,32 +9423,48 @@ def __call__(self, policy_pb2.Policy: Response from SetIamPolicy method. """ - http_options = _BaseEventarcRestTransport._BaseSetIamPolicy._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseSetIamPolicy._get_http_options() + ) request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseEventarcRestTransport._BaseSetIamPolicy._get_transcoded_request( + http_options, request + ) + ) - body = _BaseEventarcRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) + body = _BaseEventarcRestTransport._BaseSetIamPolicy._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseSetIamPolicy._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.SetIamPolicy", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "SetIamPolicy", "httpRequest": http_request, @@ -7714,7 +9473,15 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._SetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = EventarcRestTransport._SetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -7725,19 +9492,21 @@ def __call__(self, resp = policy_pb2.Policy() resp = json_format.Parse(content, resp) resp = self._interceptor.post_set_iam_policy(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcAsyncClient.SetIamPolicy", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "SetIamPolicy", "httpResponse": http_response, @@ -7748,9 +9517,11 @@ def __call__(self, @property def test_iam_permissions(self): - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - class _TestIamPermissions(_BaseEventarcRestTransport._BaseTestIamPermissions, EventarcRestStub): + class _TestIamPermissions( + _BaseEventarcRestTransport._BaseTestIamPermissions, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.TestIamPermissions") @@ -7762,28 +9533,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - + def __call__( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Call the test iam permissions method over HTTP. Args: @@ -7801,32 +9573,46 @@ def __call__(self, iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. """ - http_options = _BaseEventarcRestTransport._BaseTestIamPermissions._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseTestIamPermissions._get_http_options() + ) - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseTestIamPermissions._get_transcoded_request( + http_options, request + ) - body = _BaseEventarcRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) + body = _BaseEventarcRestTransport._BaseTestIamPermissions._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) + query_params = _BaseEventarcRestTransport._BaseTestIamPermissions._get_query_params_json( + transcoded_request + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.TestIamPermissions", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "TestIamPermissions", "httpRequest": http_request, @@ -7835,7 +9621,15 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._TestIamPermissions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = EventarcRestTransport._TestIamPermissions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -7846,19 +9640,21 @@ def __call__(self, resp = iam_policy_pb2.TestIamPermissionsResponse() resp = json_format.Parse(content, resp) resp = self._interceptor.post_test_iam_permissions(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcAsyncClient.TestIamPermissions", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "TestIamPermissions", "httpResponse": http_response, @@ -7869,9 +9665,11 @@ def __call__(self, @property def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - class _CancelOperation(_BaseEventarcRestTransport._BaseCancelOperation, EventarcRestStub): + class _CancelOperation( + _BaseEventarcRestTransport._BaseCancelOperation, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.CancelOperation") @@ -7883,28 +9681,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> None: - + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Call the cancel operation method over HTTP. Args: @@ -7919,32 +9718,52 @@ def __call__(self, be of type `bytes`. """ - http_options = _BaseEventarcRestTransport._BaseCancelOperation._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseCancelOperation._get_http_options() + ) - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = ( + _BaseEventarcRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) + ) - body = _BaseEventarcRestTransport._BaseCancelOperation._get_request_body_json(transcoded_request) + body = ( + _BaseEventarcRestTransport._BaseCancelOperation._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.CancelOperation", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "CancelOperation", "httpRequest": http_request, @@ -7953,7 +9772,15 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._CancelOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = EventarcRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -7964,9 +9791,11 @@ def __call__(self, @property def delete_operation(self): - return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - class _DeleteOperation(_BaseEventarcRestTransport._BaseDeleteOperation, EventarcRestStub): + class _DeleteOperation( + _BaseEventarcRestTransport._BaseDeleteOperation, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.DeleteOperation") @@ -7978,27 +9807,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: operations_pb2.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> None: - + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Call the delete operation method over HTTP. Args: @@ -8013,30 +9843,46 @@ def __call__(self, be of type `bytes`. """ - http_options = _BaseEventarcRestTransport._BaseDeleteOperation._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseDeleteOperation._get_http_options() + ) - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + transcoded_request = ( + _BaseEventarcRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.DeleteOperation", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "DeleteOperation", "httpRequest": http_request, @@ -8045,7 +9891,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._DeleteOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -8056,7 +9909,7 @@ def __call__(self, @property def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore class _GetOperation(_BaseEventarcRestTransport._BaseGetOperation, EventarcRestStub): def __hash__(self): @@ -8070,27 +9923,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the get operation method over HTTP. Args: @@ -8108,30 +9962,44 @@ def __call__(self, operations_pb2.Operation: Response from GetOperation method. """ - http_options = _BaseEventarcRestTransport._BaseGetOperation._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseEventarcRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.GetOperation", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "GetOperation", "httpRequest": http_request, @@ -8140,7 +10008,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -8151,19 +10026,21 @@ def __call__(self, resp = operations_pb2.Operation() resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcAsyncClient.GetOperation", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "GetOperation", "httpResponse": http_response, @@ -8174,9 +10051,11 @@ def __call__(self, @property def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(_BaseEventarcRestTransport._BaseListOperations, EventarcRestStub): + class _ListOperations( + _BaseEventarcRestTransport._BaseListOperations, EventarcRestStub + ): def __hash__(self): return hash("EventarcRestTransport.ListOperations") @@ -8188,27 +10067,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.ListOperationsResponse: - + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: r"""Call the list operations method over HTTP. Args: @@ -8226,30 +10106,44 @@ def __call__(self, operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options = _BaseEventarcRestTransport._BaseListOperations._get_http_options() + http_options = ( + _BaseEventarcRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - transcoded_request = _BaseEventarcRestTransport._BaseListOperations._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseEventarcRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseListOperations._get_query_params_json(transcoded_request) + query_params = ( + _BaseEventarcRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.eventarc_v1.EventarcClient.ListOperations", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "ListOperations", "httpRequest": http_request, @@ -8258,7 +10152,14 @@ def __call__(self, ) # Send the request - response = EventarcRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = EventarcRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -8269,19 +10170,21 @@ def __call__(self, resp = operations_pb2.ListOperationsResponse() resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.eventarc_v1.EventarcAsyncClient.ListOperations", - extra = { + extra={ "serviceName": "google.cloud.eventarc.v1.Eventarc", "rpcName": "ListOperations", "httpResponse": http_response, @@ -8298,6 +10201,4 @@ def close(self): self._session.close() -__all__=( - 'EventarcRestTransport', -) +__all__ = ("EventarcRestTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/setup.py b/packages/gapic-generator/tests/integration/goldens/eventarc/setup.py index a7179a051924..75468d45f53e 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/setup.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/setup.py @@ -17,23 +17,25 @@ import os import re -import setuptools # type: ignore +import setuptools # type: ignore package_root = os.path.abspath(os.path.dirname(__file__)) -name = 'google-cloud-eventarc' +name = "google-cloud-eventarc" description = "Google Cloud Eventarc API client library" version = None -with open(os.path.join(package_root, 'google/cloud/eventarc_v1/gapic_version.py')) as fp: +with open( + os.path.join(package_root, "google/cloud/eventarc_v1/gapic_version.py") +) as fp: version_candidates = re.findall( r"(?<=\")\d+\.\d+\.\d+[^\"\s]*(?=\")", fp.read(), ) - assert (len(version_candidates) == 1) + assert len(version_candidates) == 1 version = version_candidates[0] if version[0] == "0": @@ -52,8 +54,7 @@ "protobuf >= 6.33.5, < 8.0.0", "grpc-google-iam-v1 >= 0.14.2, <1.0.0", ] -extras = { -} +extras = {} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-eventarc" package_root = os.path.abspath(os.path.dirname(__file__)) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/__init__.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/__init__.py index 8b559fb0b227..9c141f5306a6 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/__init__.py @@ -107,10 +107,12 @@ from .types.logging_metrics import LogMetric from .types.logging_metrics import UpdateLogMetricRequest -if hasattr(api_core, "check_python_version") and hasattr(api_core, "check_dependency_versions"): # pragma: NO COVER - api_core.check_python_version("google.cloud.logging_v2") # type: ignore - api_core.check_dependency_versions("google.cloud.logging_v2") # type: ignore -else: # pragma: NO COVER +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.cloud.logging_v2") # type: ignore + api_core.check_dependency_versions("google.cloud.logging_v2") # type: ignore +else: # pragma: NO COVER # An older version of api_core is installed which does not define the # functions above. We do equivalent checks manually. try: @@ -119,12 +121,14 @@ _py_version_str = sys.version.split()[0] _package_label = "google.cloud.logging_v2" if sys.version_info < (3, 10): - warnings.warn("You are using a non-supported Python version " + - f"({_py_version_str}). Google will not post any further " + - f"updates to {_package_label} supporting this Python version. " + - "Please upgrade to the latest Python version, or at " + - f"least to Python 3.10, and then update {_package_label}.", - FutureWarning) + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.10, and then update {_package_label}.", + FutureWarning, + ) def parse_version_to_tuple(version_string: str): """Safely converts a semantic version string to a comparable tuple of integers. @@ -162,107 +166,111 @@ def _get_version(dependency_name): _recommendation = " (we recommend 7.x)" (_version_used, _version_used_string) = _get_version(_dependency_package) if _version_used and _version_used < _next_supported_version_tuple: - warnings.warn(f"Package {_package_label} depends on " + - f"{_dependency_package}, currently installed at version " + - f"{_version_used_string}. Future updates to " + - f"{_package_label} will require {_dependency_package} at " + - f"version {_next_supported_version} or higher{_recommendation}." + - " Please ensure " + - "that either (a) your Python environment doesn't pin the " + - f"version of {_dependency_package}, so that updates to " + - f"{_package_label} can require the higher version, or " + - "(b) you manually update your Python environment to use at " + - f"least version {_next_supported_version} of " + - f"{_dependency_package}.", - FutureWarning) + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) except Exception: - warnings.warn("Could not determine the version of Python " + - "currently being used. To continue receiving " + - "updates for {_package_label}, ensure you are " + - "using a supported version of Python; see " + - "https://devguide.python.org/versions/") + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) __all__ = ( - 'ConfigServiceV2AsyncClient', - 'LoggingServiceV2AsyncClient', - 'MetricsServiceV2AsyncClient', -'BigQueryDataset', -'BigQueryOptions', -'BucketMetadata', -'CmekSettings', -'ConfigServiceV2Client', -'CopyLogEntriesMetadata', -'CopyLogEntriesRequest', -'CopyLogEntriesResponse', -'CreateBucketRequest', -'CreateExclusionRequest', -'CreateLinkRequest', -'CreateLogMetricRequest', -'CreateSinkRequest', -'CreateViewRequest', -'DeleteBucketRequest', -'DeleteExclusionRequest', -'DeleteLinkRequest', -'DeleteLogMetricRequest', -'DeleteLogRequest', -'DeleteSinkRequest', -'DeleteViewRequest', -'GetBucketRequest', -'GetCmekSettingsRequest', -'GetExclusionRequest', -'GetLinkRequest', -'GetLogMetricRequest', -'GetSettingsRequest', -'GetSinkRequest', -'GetViewRequest', -'IndexConfig', -'IndexType', -'LifecycleState', -'Link', -'LinkMetadata', -'ListBucketsRequest', -'ListBucketsResponse', -'ListExclusionsRequest', -'ListExclusionsResponse', -'ListLinksRequest', -'ListLinksResponse', -'ListLogEntriesRequest', -'ListLogEntriesResponse', -'ListLogMetricsRequest', -'ListLogMetricsResponse', -'ListLogsRequest', -'ListLogsResponse', -'ListMonitoredResourceDescriptorsRequest', -'ListMonitoredResourceDescriptorsResponse', -'ListSinksRequest', -'ListSinksResponse', -'ListViewsRequest', -'ListViewsResponse', -'LocationMetadata', -'LogBucket', -'LogEntry', -'LogEntryOperation', -'LogEntrySourceLocation', -'LogExclusion', -'LogMetric', -'LogSink', -'LogSplit', -'LogView', -'LoggingServiceV2Client', -'MetricsServiceV2Client', -'OperationState', -'Settings', -'TailLogEntriesRequest', -'TailLogEntriesResponse', -'UndeleteBucketRequest', -'UpdateBucketRequest', -'UpdateCmekSettingsRequest', -'UpdateExclusionRequest', -'UpdateLogMetricRequest', -'UpdateSettingsRequest', -'UpdateSinkRequest', -'UpdateViewRequest', -'WriteLogEntriesPartialErrors', -'WriteLogEntriesRequest', -'WriteLogEntriesResponse', + "ConfigServiceV2AsyncClient", + "LoggingServiceV2AsyncClient", + "MetricsServiceV2AsyncClient", + "BigQueryDataset", + "BigQueryOptions", + "BucketMetadata", + "CmekSettings", + "ConfigServiceV2Client", + "CopyLogEntriesMetadata", + "CopyLogEntriesRequest", + "CopyLogEntriesResponse", + "CreateBucketRequest", + "CreateExclusionRequest", + "CreateLinkRequest", + "CreateLogMetricRequest", + "CreateSinkRequest", + "CreateViewRequest", + "DeleteBucketRequest", + "DeleteExclusionRequest", + "DeleteLinkRequest", + "DeleteLogMetricRequest", + "DeleteLogRequest", + "DeleteSinkRequest", + "DeleteViewRequest", + "GetBucketRequest", + "GetCmekSettingsRequest", + "GetExclusionRequest", + "GetLinkRequest", + "GetLogMetricRequest", + "GetSettingsRequest", + "GetSinkRequest", + "GetViewRequest", + "IndexConfig", + "IndexType", + "LifecycleState", + "Link", + "LinkMetadata", + "ListBucketsRequest", + "ListBucketsResponse", + "ListExclusionsRequest", + "ListExclusionsResponse", + "ListLinksRequest", + "ListLinksResponse", + "ListLogEntriesRequest", + "ListLogEntriesResponse", + "ListLogMetricsRequest", + "ListLogMetricsResponse", + "ListLogsRequest", + "ListLogsResponse", + "ListMonitoredResourceDescriptorsRequest", + "ListMonitoredResourceDescriptorsResponse", + "ListSinksRequest", + "ListSinksResponse", + "ListViewsRequest", + "ListViewsResponse", + "LocationMetadata", + "LogBucket", + "LogEntry", + "LogEntryOperation", + "LogEntrySourceLocation", + "LogExclusion", + "LogMetric", + "LogSink", + "LogSplit", + "LogView", + "LoggingServiceV2Client", + "MetricsServiceV2Client", + "OperationState", + "Settings", + "TailLogEntriesRequest", + "TailLogEntriesResponse", + "UndeleteBucketRequest", + "UpdateBucketRequest", + "UpdateCmekSettingsRequest", + "UpdateExclusionRequest", + "UpdateLogMetricRequest", + "UpdateSettingsRequest", + "UpdateSinkRequest", + "UpdateViewRequest", + "WriteLogEntriesPartialErrors", + "WriteLogEntriesRequest", + "WriteLogEntriesResponse", ) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/async_client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/async_client.py index d453ac1aa05d..837db5faa431 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/async_client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/async_client.py @@ -16,7 +16,18 @@ import logging as std_logging from collections import OrderedDict import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union +from typing import ( + Dict, + Callable, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) from google.cloud.logging_v2 import gapic_version as package_version @@ -24,8 +35,8 @@ from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf @@ -36,7 +47,7 @@ from google.cloud.logging_v2.services.config_service_v2 import pagers from google.cloud.logging_v2.types import logging_config -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.api_core.operation as operation # type: ignore import google.api_core.operation_async as operation_async # type: ignore import google.protobuf.empty_pb2 as empty_pb2 # type: ignore @@ -48,12 +59,14 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) + class ConfigServiceV2AsyncClient: """Service for configuring sinks used to route log entries.""" @@ -67,29 +80,47 @@ class ConfigServiceV2AsyncClient: _DEFAULT_UNIVERSE = ConfigServiceV2Client._DEFAULT_UNIVERSE cmek_settings_path = staticmethod(ConfigServiceV2Client.cmek_settings_path) - parse_cmek_settings_path = staticmethod(ConfigServiceV2Client.parse_cmek_settings_path) + parse_cmek_settings_path = staticmethod( + ConfigServiceV2Client.parse_cmek_settings_path + ) link_path = staticmethod(ConfigServiceV2Client.link_path) parse_link_path = staticmethod(ConfigServiceV2Client.parse_link_path) log_bucket_path = staticmethod(ConfigServiceV2Client.log_bucket_path) parse_log_bucket_path = staticmethod(ConfigServiceV2Client.parse_log_bucket_path) log_exclusion_path = staticmethod(ConfigServiceV2Client.log_exclusion_path) - parse_log_exclusion_path = staticmethod(ConfigServiceV2Client.parse_log_exclusion_path) + parse_log_exclusion_path = staticmethod( + ConfigServiceV2Client.parse_log_exclusion_path + ) log_sink_path = staticmethod(ConfigServiceV2Client.log_sink_path) parse_log_sink_path = staticmethod(ConfigServiceV2Client.parse_log_sink_path) log_view_path = staticmethod(ConfigServiceV2Client.log_view_path) parse_log_view_path = staticmethod(ConfigServiceV2Client.parse_log_view_path) settings_path = staticmethod(ConfigServiceV2Client.settings_path) parse_settings_path = staticmethod(ConfigServiceV2Client.parse_settings_path) - common_billing_account_path = staticmethod(ConfigServiceV2Client.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ConfigServiceV2Client.parse_common_billing_account_path) + common_billing_account_path = staticmethod( + ConfigServiceV2Client.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + ConfigServiceV2Client.parse_common_billing_account_path + ) common_folder_path = staticmethod(ConfigServiceV2Client.common_folder_path) - parse_common_folder_path = staticmethod(ConfigServiceV2Client.parse_common_folder_path) - common_organization_path = staticmethod(ConfigServiceV2Client.common_organization_path) - parse_common_organization_path = staticmethod(ConfigServiceV2Client.parse_common_organization_path) + parse_common_folder_path = staticmethod( + ConfigServiceV2Client.parse_common_folder_path + ) + common_organization_path = staticmethod( + ConfigServiceV2Client.common_organization_path + ) + parse_common_organization_path = staticmethod( + ConfigServiceV2Client.parse_common_organization_path + ) common_project_path = staticmethod(ConfigServiceV2Client.common_project_path) - parse_common_project_path = staticmethod(ConfigServiceV2Client.parse_common_project_path) + parse_common_project_path = staticmethod( + ConfigServiceV2Client.parse_common_project_path + ) common_location_path = staticmethod(ConfigServiceV2Client.common_location_path) - parse_common_location_path = staticmethod(ConfigServiceV2Client.parse_common_location_path) + parse_common_location_path = staticmethod( + ConfigServiceV2Client.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -131,7 +162,9 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): """Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -194,12 +227,18 @@ def universe_domain(self) -> str: get_transport_class = ConfigServiceV2Client.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ConfigServiceV2Transport, Callable[..., ConfigServiceV2Transport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, ConfigServiceV2Transport, Callable[..., ConfigServiceV2Transport] + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the config service v2 async client. Args: @@ -254,31 +293,39 @@ def __init__(self, *, transport=transport, client_options=client_options, client_info=client_info, - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.logging_v2.ConfigServiceV2AsyncClient`.", - extra = { + extra={ "serviceName": "google.logging.v2.ConfigServiceV2", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { "serviceName": "google.logging.v2.ConfigServiceV2", "credentialsType": None, - } + }, ) - async def list_buckets(self, - request: Optional[Union[logging_config.ListBucketsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListBucketsAsyncPager: + async def list_buckets( + self, + request: Optional[Union[logging_config.ListBucketsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBucketsAsyncPager: r"""Lists log buckets. .. code-block:: python @@ -350,10 +397,14 @@ async def sample_list_buckets(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -367,14 +418,14 @@ async def sample_list_buckets(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_buckets] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_buckets + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -402,13 +453,14 @@ async def sample_list_buckets(): # Done; return the response. return response - async def get_bucket(self, - request: Optional[Union[logging_config.GetBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogBucket: + async def get_bucket( + self, + request: Optional[Union[logging_config.GetBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: r"""Gets a log bucket. .. code-block:: python @@ -462,14 +514,14 @@ async def sample_get_bucket(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_bucket] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_bucket + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -486,13 +538,14 @@ async def sample_get_bucket(): # Done; return the response. return response - async def create_bucket_async(self, - request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def create_bucket_async( + self, + request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Creates a log bucket asynchronously that can be used to store log entries. After a bucket has been created, the bucket's location @@ -557,14 +610,14 @@ async def sample_create_bucket_async(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_bucket_async] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_bucket_async + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -589,13 +642,14 @@ async def sample_create_bucket_async(): # Done; return the response. return response - async def update_bucket_async(self, - request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def update_bucket_async( + self, + request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Updates a log bucket asynchronously. If the bucket has a ``lifecycle_state`` of ``DELETE_REQUESTED``, @@ -662,14 +716,14 @@ async def sample_update_bucket_async(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_bucket_async] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_bucket_async + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -694,13 +748,14 @@ async def sample_update_bucket_async(): # Done; return the response. return response - async def create_bucket(self, - request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogBucket: + async def create_bucket( + self, + request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: r"""Creates a log bucket that can be used to store log entries. After a bucket has been created, the bucket's location cannot be changed. @@ -757,14 +812,14 @@ async def sample_create_bucket(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_bucket] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_bucket + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -781,13 +836,14 @@ async def sample_create_bucket(): # Done; return the response. return response - async def update_bucket(self, - request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogBucket: + async def update_bucket( + self, + request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: r"""Updates a log bucket. If the bucket has a ``lifecycle_state`` of ``DELETE_REQUESTED``, @@ -847,14 +903,14 @@ async def sample_update_bucket(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_bucket] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_bucket + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -871,13 +927,14 @@ async def sample_update_bucket(): # Done; return the response. return response - async def delete_bucket(self, - request: Optional[Union[logging_config.DeleteBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def delete_bucket( + self, + request: Optional[Union[logging_config.DeleteBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a log bucket. Changes the bucket's ``lifecycle_state`` to the @@ -927,14 +984,14 @@ async def sample_delete_bucket(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_bucket] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_bucket + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -948,13 +1005,14 @@ async def sample_delete_bucket(): metadata=metadata, ) - async def undelete_bucket(self, - request: Optional[Union[logging_config.UndeleteBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def undelete_bucket( + self, + request: Optional[Union[logging_config.UndeleteBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Undeletes a log bucket. A bucket that has been deleted can be undeleted within the grace period of 7 days. @@ -1001,14 +1059,14 @@ async def sample_undelete_bucket(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.undelete_bucket] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.undelete_bucket + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1022,14 +1080,15 @@ async def sample_undelete_bucket(): metadata=metadata, ) - async def list_views(self, - request: Optional[Union[logging_config.ListViewsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListViewsAsyncPager: + async def list_views( + self, + request: Optional[Union[logging_config.ListViewsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListViewsAsyncPager: r"""Lists views on a log bucket. .. code-block:: python @@ -1093,10 +1152,14 @@ async def sample_list_views(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1110,14 +1173,14 @@ async def sample_list_views(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_views] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_views + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1145,13 +1208,14 @@ async def sample_list_views(): # Done; return the response. return response - async def get_view(self, - request: Optional[Union[logging_config.GetViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogView: + async def get_view( + self, + request: Optional[Union[logging_config.GetViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: r"""Gets a view on a log bucket.. .. code-block:: python @@ -1210,9 +1274,7 @@ async def sample_get_view(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1229,13 +1291,14 @@ async def sample_get_view(): # Done; return the response. return response - async def create_view(self, - request: Optional[Union[logging_config.CreateViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogView: + async def create_view( + self, + request: Optional[Union[logging_config.CreateViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: r"""Creates a view over log entries in a log bucket. A bucket may contain a maximum of 30 views. @@ -1291,14 +1354,14 @@ async def sample_create_view(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_view] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_view + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1315,13 +1378,14 @@ async def sample_create_view(): # Done; return the response. return response - async def update_view(self, - request: Optional[Union[logging_config.UpdateViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogView: + async def update_view( + self, + request: Optional[Union[logging_config.UpdateViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: r"""Updates a view on a log bucket. This method replaces the following fields in the existing view with values from the new view: ``filter``. If an ``UNAVAILABLE`` error is returned, this @@ -1379,14 +1443,14 @@ async def sample_update_view(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_view] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_view + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1403,13 +1467,14 @@ async def sample_update_view(): # Done; return the response. return response - async def delete_view(self, - request: Optional[Union[logging_config.DeleteViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def delete_view( + self, + request: Optional[Union[logging_config.DeleteViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a view on a log bucket. If an ``UNAVAILABLE`` error is returned, this indicates that system is not in a state where it can delete the view. If this occurs, please try again in a few @@ -1457,14 +1522,14 @@ async def sample_delete_view(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_view] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_view + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1478,14 +1543,15 @@ async def sample_delete_view(): metadata=metadata, ) - async def list_sinks(self, - request: Optional[Union[logging_config.ListSinksRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListSinksAsyncPager: + async def list_sinks( + self, + request: Optional[Union[logging_config.ListSinksRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSinksAsyncPager: r"""Lists sinks. .. code-block:: python @@ -1552,10 +1618,14 @@ async def sample_list_sinks(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1569,14 +1639,14 @@ async def sample_list_sinks(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_sinks] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_sinks + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1604,14 +1674,15 @@ async def sample_list_sinks(): # Done; return the response. return response - async def get_sink(self, - request: Optional[Union[logging_config.GetSinkRequest, dict]] = None, - *, - sink_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogSink: + async def get_sink( + self, + request: Optional[Union[logging_config.GetSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: r"""Gets a sink. .. code-block:: python @@ -1685,10 +1756,14 @@ async def sample_get_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [sink_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1707,9 +1782,9 @@ async def sample_get_sink(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("sink_name", request.sink_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("sink_name", request.sink_name),) + ), ) # Validate the universe domain. @@ -1726,15 +1801,16 @@ async def sample_get_sink(): # Done; return the response. return response - async def create_sink(self, - request: Optional[Union[logging_config.CreateSinkRequest, dict]] = None, - *, - parent: Optional[str] = None, - sink: Optional[logging_config.LogSink] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogSink: + async def create_sink( + self, + request: Optional[Union[logging_config.CreateSinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + sink: Optional[logging_config.LogSink] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: r"""Creates a sink that exports specified log entries to a destination. The export of newly-ingested log entries begins immediately, unless the sink's ``writer_identity`` is not @@ -1824,10 +1900,14 @@ async def sample_create_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, sink] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1843,14 +1923,14 @@ async def sample_create_sink(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_sink] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_sink + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1867,16 +1947,17 @@ async def sample_create_sink(): # Done; return the response. return response - async def update_sink(self, - request: Optional[Union[logging_config.UpdateSinkRequest, dict]] = None, - *, - sink_name: Optional[str] = None, - sink: Optional[logging_config.LogSink] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogSink: + async def update_sink( + self, + request: Optional[Union[logging_config.UpdateSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + sink: Optional[logging_config.LogSink] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: r"""Updates a sink. This method replaces the following fields in the existing sink with values from the new sink: ``destination``, and ``filter``. @@ -1990,10 +2071,14 @@ async def sample_update_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [sink_name, sink, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2011,14 +2096,16 @@ async def sample_update_sink(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_sink] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_sink + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("sink_name", request.sink_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("sink_name", request.sink_name),) + ), ) # Validate the universe domain. @@ -2035,14 +2122,15 @@ async def sample_update_sink(): # Done; return the response. return response - async def delete_sink(self, - request: Optional[Union[logging_config.DeleteSinkRequest, dict]] = None, - *, - sink_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def delete_sink( + self, + request: Optional[Union[logging_config.DeleteSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a sink. If the sink has a unique ``writer_identity``, then that service account is also deleted. @@ -2102,10 +2190,14 @@ async def sample_delete_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [sink_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2119,14 +2211,16 @@ async def sample_delete_sink(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_sink] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_sink + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("sink_name", request.sink_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("sink_name", request.sink_name),) + ), ) # Validate the universe domain. @@ -2140,16 +2234,17 @@ async def sample_delete_sink(): metadata=metadata, ) - async def create_link(self, - request: Optional[Union[logging_config.CreateLinkRequest, dict]] = None, - *, - parent: Optional[str] = None, - link: Optional[logging_config.Link] = None, - link_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def create_link( + self, + request: Optional[Union[logging_config.CreateLinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + link: Optional[logging_config.Link] = None, + link_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Asynchronously creates a linked dataset in BigQuery which makes it possible to use BigQuery to read the logs stored in the log bucket. A log bucket may currently @@ -2237,10 +2332,14 @@ async def sample_create_link(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, link, link_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2258,14 +2357,14 @@ async def sample_create_link(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_link] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_link + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2290,14 +2389,15 @@ async def sample_create_link(): # Done; return the response. return response - async def delete_link(self, - request: Optional[Union[logging_config.DeleteLinkRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def delete_link( + self, + request: Optional[Union[logging_config.DeleteLinkRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Deletes a link. This will also delete the corresponding BigQuery linked dataset. @@ -2373,10 +2473,14 @@ async def sample_delete_link(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2390,14 +2494,14 @@ async def sample_delete_link(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_link] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_link + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2422,14 +2526,15 @@ async def sample_delete_link(): # Done; return the response. return response - async def list_links(self, - request: Optional[Union[logging_config.ListLinksRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLinksAsyncPager: + async def list_links( + self, + request: Optional[Union[logging_config.ListLinksRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLinksAsyncPager: r"""Lists links. .. code-block:: python @@ -2495,10 +2600,14 @@ async def sample_list_links(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2512,14 +2621,14 @@ async def sample_list_links(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_links] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_links + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2547,14 +2656,15 @@ async def sample_list_links(): # Done; return the response. return response - async def get_link(self, - request: Optional[Union[logging_config.GetLinkRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.Link: + async def get_link( + self, + request: Optional[Union[logging_config.GetLinkRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Link: r"""Gets a link. .. code-block:: python @@ -2615,10 +2725,14 @@ async def sample_get_link(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2637,9 +2751,7 @@ async def sample_get_link(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2656,14 +2768,15 @@ async def sample_get_link(): # Done; return the response. return response - async def list_exclusions(self, - request: Optional[Union[logging_config.ListExclusionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListExclusionsAsyncPager: + async def list_exclusions( + self, + request: Optional[Union[logging_config.ListExclusionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListExclusionsAsyncPager: r"""Lists all the exclusions on the \_Default sink in a parent resource. @@ -2731,10 +2844,14 @@ async def sample_list_exclusions(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2748,14 +2865,14 @@ async def sample_list_exclusions(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_exclusions] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_exclusions + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2783,14 +2900,15 @@ async def sample_list_exclusions(): # Done; return the response. return response - async def get_exclusion(self, - request: Optional[Union[logging_config.GetExclusionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogExclusion: + async def get_exclusion( + self, + request: Optional[Union[logging_config.GetExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: r"""Gets the description of an exclusion in the \_Default sink. .. code-block:: python @@ -2862,10 +2980,14 @@ async def sample_get_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2879,14 +3001,14 @@ async def sample_get_exclusion(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_exclusion] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_exclusion + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2903,15 +3025,16 @@ async def sample_get_exclusion(): # Done; return the response. return response - async def create_exclusion(self, - request: Optional[Union[logging_config.CreateExclusionRequest, dict]] = None, - *, - parent: Optional[str] = None, - exclusion: Optional[logging_config.LogExclusion] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogExclusion: + async def create_exclusion( + self, + request: Optional[Union[logging_config.CreateExclusionRequest, dict]] = None, + *, + parent: Optional[str] = None, + exclusion: Optional[logging_config.LogExclusion] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: r"""Creates a new exclusion in the \_Default sink in a specified parent resource. Only log entries belonging to that resource can be excluded. You can have up to 10 exclusions in a resource. @@ -3000,10 +3123,14 @@ async def sample_create_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, exclusion] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3019,14 +3146,14 @@ async def sample_create_exclusion(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_exclusion] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_exclusion + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -3043,16 +3170,17 @@ async def sample_create_exclusion(): # Done; return the response. return response - async def update_exclusion(self, - request: Optional[Union[logging_config.UpdateExclusionRequest, dict]] = None, - *, - name: Optional[str] = None, - exclusion: Optional[logging_config.LogExclusion] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogExclusion: + async def update_exclusion( + self, + request: Optional[Union[logging_config.UpdateExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + exclusion: Optional[logging_config.LogExclusion] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: r"""Changes one or more properties of an existing exclusion in the \_Default sink. @@ -3152,10 +3280,14 @@ async def sample_update_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, exclusion, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3173,14 +3305,14 @@ async def sample_update_exclusion(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_exclusion] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_exclusion + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3197,14 +3329,15 @@ async def sample_update_exclusion(): # Done; return the response. return response - async def delete_exclusion(self, - request: Optional[Union[logging_config.DeleteExclusionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def delete_exclusion( + self, + request: Optional[Union[logging_config.DeleteExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes an exclusion in the \_Default sink. .. code-block:: python @@ -3263,10 +3396,14 @@ async def sample_delete_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3280,14 +3417,14 @@ async def sample_delete_exclusion(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_exclusion] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_exclusion + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3301,13 +3438,14 @@ async def sample_delete_exclusion(): metadata=metadata, ) - async def get_cmek_settings(self, - request: Optional[Union[logging_config.GetCmekSettingsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.CmekSettings: + async def get_cmek_settings( + self, + request: Optional[Union[logging_config.GetCmekSettingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.CmekSettings: r"""Gets the Logging CMEK settings for the given resource. Note: CMEK for the Log Router can be configured for Google Cloud @@ -3385,14 +3523,14 @@ async def sample_get_cmek_settings(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_cmek_settings] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_cmek_settings + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3409,13 +3547,14 @@ async def sample_get_cmek_settings(): # Done; return the response. return response - async def update_cmek_settings(self, - request: Optional[Union[logging_config.UpdateCmekSettingsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.CmekSettings: + async def update_cmek_settings( + self, + request: Optional[Union[logging_config.UpdateCmekSettingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.CmekSettings: r"""Updates the Log Router CMEK settings for the given resource. Note: CMEK for the Log Router can currently only be configured @@ -3498,14 +3637,14 @@ async def sample_update_cmek_settings(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_cmek_settings] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_cmek_settings + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3522,14 +3661,15 @@ async def sample_update_cmek_settings(): # Done; return the response. return response - async def get_settings(self, - request: Optional[Union[logging_config.GetSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.Settings: + async def get_settings( + self, + request: Optional[Union[logging_config.GetSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Settings: r"""Gets the Log Router settings for the given resource. Note: Settings for the Log Router can be get for Google Cloud @@ -3619,10 +3759,14 @@ async def sample_get_settings(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3636,14 +3780,14 @@ async def sample_get_settings(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_settings] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_settings + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3660,15 +3804,16 @@ async def sample_get_settings(): # Done; return the response. return response - async def update_settings(self, - request: Optional[Union[logging_config.UpdateSettingsRequest, dict]] = None, - *, - settings: Optional[logging_config.Settings] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.Settings: + async def update_settings( + self, + request: Optional[Union[logging_config.UpdateSettingsRequest, dict]] = None, + *, + settings: Optional[logging_config.Settings] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Settings: r"""Updates the Log Router settings for the given resource. Note: Settings for the Log Router can currently only be @@ -3765,10 +3910,14 @@ async def sample_update_settings(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [settings, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3784,14 +3933,14 @@ async def sample_update_settings(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_settings] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_settings + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3808,13 +3957,14 @@ async def sample_update_settings(): # Done; return the response. return response - async def copy_log_entries(self, - request: Optional[Union[logging_config.CopyLogEntriesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def copy_log_entries( + self, + request: Optional[Union[logging_config.CopyLogEntriesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Copies a set of log entries from a log bucket to a Cloud Storage bucket. @@ -3878,7 +4028,9 @@ async def sample_copy_log_entries(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.copy_log_entries] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.copy_log_entries + ] # Validate the universe domain. self._client._validate_universe_domain() @@ -3944,8 +4096,7 @@ async def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -3953,7 +4104,11 @@ async def list_operations( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -4000,8 +4155,7 @@ async def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -4009,7 +4163,11 @@ async def get_operation( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -4059,15 +4217,19 @@ async def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) async def __aenter__(self) -> "ConfigServiceV2AsyncClient": return self @@ -4075,12 +4237,13 @@ async def __aenter__(self) -> "ConfigServiceV2AsyncClient": async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "ConfigServiceV2AsyncClient", -) +__all__ = ("ConfigServiceV2AsyncClient",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py index 326b710ce067..8e69b4881a55 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py @@ -19,7 +19,19 @@ import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +from typing import ( + Dict, + Callable, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) import warnings from google.cloud.logging_v2 import gapic_version as package_version @@ -28,11 +40,11 @@ from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.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.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 import google.protobuf try: @@ -42,6 +54,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -50,7 +63,7 @@ from google.cloud.logging_v2.services.config_service_v2 import pagers from google.cloud.logging_v2.types import logging_config -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.api_core.operation as operation # type: ignore import google.api_core.operation_async as operation_async # type: ignore import google.protobuf.empty_pb2 as empty_pb2 # type: ignore @@ -68,13 +81,17 @@ class ConfigServiceV2ClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[ConfigServiceV2Transport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[ConfigServiceV2Transport]] _transport_registry["grpc"] = ConfigServiceV2GrpcTransport _transport_registry["grpc_asyncio"] = ConfigServiceV2GrpcAsyncIOTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ConfigServiceV2Transport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[ConfigServiceV2Transport]: """Returns an appropriate transport class. Args: @@ -150,14 +167,16 @@ def _use_client_cert_effective(): bool: whether client certificate should be used for mTLS Raises: ValueError: (If using a version of google-auth without should_use_client_cert and - GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) """ # check if google-auth version supports should_use_client_cert for automatic mTLS enablement if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER return mtls.should_use_client_cert() - else: # pragma: NO COVER + else: # pragma: NO COVER # if unsupported, fallback to reading from env var - use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() if use_client_cert_str not in ("true", "false"): raise ValueError( "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" @@ -196,8 +215,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ConfigServiceV2Client: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -214,139 +232,220 @@ def transport(self) -> ConfigServiceV2Transport: return self._transport @staticmethod - def cmek_settings_path(project: str,) -> str: + def cmek_settings_path( + project: str, + ) -> str: """Returns a fully-qualified cmek_settings string.""" - return "projects/{project}/cmekSettings".format(project=project, ) + return "projects/{project}/cmekSettings".format( + project=project, + ) @staticmethod - def parse_cmek_settings_path(path: str) -> Dict[str,str]: + def parse_cmek_settings_path(path: str) -> Dict[str, str]: """Parses a cmek_settings path into its component segments.""" m = re.match(r"^projects/(?P.+?)/cmekSettings$", path) return m.groupdict() if m else {} @staticmethod - def link_path(project: str,location: str,bucket: str,link: str,) -> str: + def link_path( + project: str, + location: str, + bucket: str, + link: str, + ) -> str: """Returns a fully-qualified link string.""" - return "projects/{project}/locations/{location}/buckets/{bucket}/links/{link}".format(project=project, location=location, bucket=bucket, link=link, ) + return "projects/{project}/locations/{location}/buckets/{bucket}/links/{link}".format( + project=project, + location=location, + bucket=bucket, + link=link, + ) @staticmethod - def parse_link_path(path: str) -> Dict[str,str]: + def parse_link_path(path: str) -> Dict[str, str]: """Parses a link path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)/links/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)/links/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def log_bucket_path(project: str,location: str,bucket: str,) -> str: + def log_bucket_path( + project: str, + location: str, + bucket: str, + ) -> str: """Returns a fully-qualified log_bucket string.""" - return "projects/{project}/locations/{location}/buckets/{bucket}".format(project=project, location=location, bucket=bucket, ) + return "projects/{project}/locations/{location}/buckets/{bucket}".format( + project=project, + location=location, + bucket=bucket, + ) @staticmethod - def parse_log_bucket_path(path: str) -> Dict[str,str]: + def parse_log_bucket_path(path: str) -> Dict[str, str]: """Parses a log_bucket path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def log_exclusion_path(project: str,exclusion: str,) -> str: + def log_exclusion_path( + project: str, + exclusion: str, + ) -> str: """Returns a fully-qualified log_exclusion string.""" - return "projects/{project}/exclusions/{exclusion}".format(project=project, exclusion=exclusion, ) + return "projects/{project}/exclusions/{exclusion}".format( + project=project, + exclusion=exclusion, + ) @staticmethod - def parse_log_exclusion_path(path: str) -> Dict[str,str]: + def parse_log_exclusion_path(path: str) -> Dict[str, str]: """Parses a log_exclusion path into its component segments.""" m = re.match(r"^projects/(?P.+?)/exclusions/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def log_sink_path(project: str,sink: str,) -> str: + def log_sink_path( + project: str, + sink: str, + ) -> str: """Returns a fully-qualified log_sink string.""" - return "projects/{project}/sinks/{sink}".format(project=project, sink=sink, ) + return "projects/{project}/sinks/{sink}".format( + project=project, + sink=sink, + ) @staticmethod - def parse_log_sink_path(path: str) -> Dict[str,str]: + def parse_log_sink_path(path: str) -> Dict[str, str]: """Parses a log_sink path into its component segments.""" m = re.match(r"^projects/(?P.+?)/sinks/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def log_view_path(project: str,location: str,bucket: str,view: str,) -> str: + def log_view_path( + project: str, + location: str, + bucket: str, + view: str, + ) -> str: """Returns a fully-qualified log_view string.""" - return "projects/{project}/locations/{location}/buckets/{bucket}/views/{view}".format(project=project, location=location, bucket=bucket, view=view, ) + return "projects/{project}/locations/{location}/buckets/{bucket}/views/{view}".format( + project=project, + location=location, + bucket=bucket, + view=view, + ) @staticmethod - def parse_log_view_path(path: str) -> Dict[str,str]: + def parse_log_view_path(path: str) -> Dict[str, str]: """Parses a log_view path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)/views/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)/views/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def settings_path(project: str,) -> str: + def settings_path( + project: str, + ) -> str: """Returns a fully-qualified settings string.""" - return "projects/{project}/settings".format(project=project, ) + return "projects/{project}/settings".format( + project=project, + ) @staticmethod - def parse_settings_path(path: str) -> Dict[str,str]: + def parse_settings_path(path: str) -> Dict[str, str]: """Parses a settings path into its component segments.""" m = re.match(r"^projects/(?P.+?)/settings$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + def common_billing_account_path( + billing_account: str, + ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path(folder: str, ) -> str: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path(organization: str, ) -> str: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path(project: str, ) -> str: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path(project: str, location: str, ) -> str: + def common_location_path( + project: str, + location: str, + ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -378,14 +477,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = ConfigServiceV2Client._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Figure out the client cert source to use. client_cert_source = None @@ -398,7 +501,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): api_endpoint = cls.DEFAULT_MTLS_ENDPOINT else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -423,7 +528,9 @@ def _read_environment_variables(): use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod @@ -446,7 +553,9 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: """Return the API endpoint used by the client. Args: @@ -462,17 +571,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): _default_universe = ConfigServiceV2Client._DEFAULT_UNIVERSE if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) api_endpoint = ConfigServiceV2Client.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = ConfigServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = ConfigServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) return api_endpoint @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: """Return the universe domain used by the client. Args: @@ -508,15 +625,18 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError + self, error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: return cred = self._transport._credentials @@ -549,12 +669,18 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ConfigServiceV2Transport, Callable[..., ConfigServiceV2Transport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, ConfigServiceV2Transport, Callable[..., ConfigServiceV2Transport] + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the config service v2 client. Args: @@ -609,13 +735,23 @@ def __init__(self, *, self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ConfigServiceV2Client._read_environment_variables() - self._client_cert_source = ConfigServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = ConfigServiceV2Client._get_universe_domain(universe_domain_opt, self._universe_domain_env) + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = ConfigServiceV2Client._read_environment_variables() + self._client_cert_source = ConfigServiceV2Client._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = ConfigServiceV2Client._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -627,7 +763,9 @@ def __init__(self, *, api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -636,8 +774,10 @@ def __init__(self, *, if transport_provided: # transport is a ConfigServiceV2Transport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if self._client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes " @@ -646,20 +786,29 @@ def __init__(self, *, self._transport = cast(ConfigServiceV2Transport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - ConfigServiceV2Client._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or ConfigServiceV2Client._get_api_endpoint( self._client_options.api_endpoint, self._client_cert_source, self._universe_domain, - self._use_mtls_endpoint)) + self._use_mtls_endpoint, + ) + ) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) - transport_init: Union[Type[ConfigServiceV2Transport], Callable[..., ConfigServiceV2Transport]] = ( + transport_init: Union[ + Type[ConfigServiceV2Transport], Callable[..., ConfigServiceV2Transport] + ] = ( ConfigServiceV2Client.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., ConfigServiceV2Transport], transport) @@ -678,28 +827,37 @@ def __init__(self, *, ) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.logging_v2.ConfigServiceV2Client`.", - extra = { + extra={ "serviceName": "google.logging.v2.ConfigServiceV2", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { "serviceName": "google.logging.v2.ConfigServiceV2", "credentialsType": None, - } + }, ) - def list_buckets(self, - request: Optional[Union[logging_config.ListBucketsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListBucketsPager: + def list_buckets( + self, + request: Optional[Union[logging_config.ListBucketsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBucketsPager: r"""Lists log buckets. .. code-block:: python @@ -771,10 +929,14 @@ def sample_list_buckets(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -792,9 +954,7 @@ def sample_list_buckets(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -822,13 +982,14 @@ def sample_list_buckets(): # Done; return the response. return response - def get_bucket(self, - request: Optional[Union[logging_config.GetBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogBucket: + def get_bucket( + self, + request: Optional[Union[logging_config.GetBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: r"""Gets a log bucket. .. code-block:: python @@ -887,9 +1048,7 @@ def sample_get_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -906,13 +1065,14 @@ def sample_get_bucket(): # Done; return the response. return response - def create_bucket_async(self, - request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_bucket_async( + self, + request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Creates a log bucket asynchronously that can be used to store log entries. After a bucket has been created, the bucket's location @@ -982,9 +1142,7 @@ def sample_create_bucket_async(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1009,13 +1167,14 @@ def sample_create_bucket_async(): # Done; return the response. return response - def update_bucket_async(self, - request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_bucket_async( + self, + request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Updates a log bucket asynchronously. If the bucket has a ``lifecycle_state`` of ``DELETE_REQUESTED``, @@ -1087,9 +1246,7 @@ def sample_update_bucket_async(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1114,13 +1271,14 @@ def sample_update_bucket_async(): # Done; return the response. return response - def create_bucket(self, - request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogBucket: + def create_bucket( + self, + request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: r"""Creates a log bucket that can be used to store log entries. After a bucket has been created, the bucket's location cannot be changed. @@ -1182,9 +1340,7 @@ def sample_create_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1201,13 +1357,14 @@ def sample_create_bucket(): # Done; return the response. return response - def update_bucket(self, - request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogBucket: + def update_bucket( + self, + request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: r"""Updates a log bucket. If the bucket has a ``lifecycle_state`` of ``DELETE_REQUESTED``, @@ -1272,9 +1429,7 @@ def sample_update_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1291,13 +1446,14 @@ def sample_update_bucket(): # Done; return the response. return response - def delete_bucket(self, - request: Optional[Union[logging_config.DeleteBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_bucket( + self, + request: Optional[Union[logging_config.DeleteBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a log bucket. Changes the bucket's ``lifecycle_state`` to the @@ -1352,9 +1508,7 @@ def sample_delete_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1368,13 +1522,14 @@ def sample_delete_bucket(): metadata=metadata, ) - def undelete_bucket(self, - request: Optional[Union[logging_config.UndeleteBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def undelete_bucket( + self, + request: Optional[Union[logging_config.UndeleteBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Undeletes a log bucket. A bucket that has been deleted can be undeleted within the grace period of 7 days. @@ -1426,9 +1581,7 @@ def sample_undelete_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1442,14 +1595,15 @@ def sample_undelete_bucket(): metadata=metadata, ) - def list_views(self, - request: Optional[Union[logging_config.ListViewsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListViewsPager: + def list_views( + self, + request: Optional[Union[logging_config.ListViewsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListViewsPager: r"""Lists views on a log bucket. .. code-block:: python @@ -1513,10 +1667,14 @@ def sample_list_views(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1534,9 +1692,7 @@ def sample_list_views(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1564,13 +1720,14 @@ def sample_list_views(): # Done; return the response. return response - def get_view(self, - request: Optional[Union[logging_config.GetViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogView: + def get_view( + self, + request: Optional[Union[logging_config.GetViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: r"""Gets a view on a log bucket.. .. code-block:: python @@ -1629,9 +1786,7 @@ def sample_get_view(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1648,13 +1803,14 @@ def sample_get_view(): # Done; return the response. return response - def create_view(self, - request: Optional[Union[logging_config.CreateViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogView: + def create_view( + self, + request: Optional[Union[logging_config.CreateViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: r"""Creates a view over log entries in a log bucket. A bucket may contain a maximum of 30 views. @@ -1715,9 +1871,7 @@ def sample_create_view(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1734,13 +1888,14 @@ def sample_create_view(): # Done; return the response. return response - def update_view(self, - request: Optional[Union[logging_config.UpdateViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogView: + def update_view( + self, + request: Optional[Union[logging_config.UpdateViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: r"""Updates a view on a log bucket. This method replaces the following fields in the existing view with values from the new view: ``filter``. If an ``UNAVAILABLE`` error is returned, this @@ -1803,9 +1958,7 @@ def sample_update_view(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1822,13 +1975,14 @@ def sample_update_view(): # Done; return the response. return response - def delete_view(self, - request: Optional[Union[logging_config.DeleteViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_view( + self, + request: Optional[Union[logging_config.DeleteViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a view on a log bucket. If an ``UNAVAILABLE`` error is returned, this indicates that system is not in a state where it can delete the view. If this occurs, please try again in a few @@ -1881,9 +2035,7 @@ def sample_delete_view(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1897,14 +2049,15 @@ def sample_delete_view(): metadata=metadata, ) - def list_sinks(self, - request: Optional[Union[logging_config.ListSinksRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListSinksPager: + def list_sinks( + self, + request: Optional[Union[logging_config.ListSinksRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSinksPager: r"""Lists sinks. .. code-block:: python @@ -1971,10 +2124,14 @@ def sample_list_sinks(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1992,9 +2149,7 @@ def sample_list_sinks(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2022,14 +2177,15 @@ def sample_list_sinks(): # Done; return the response. return response - def get_sink(self, - request: Optional[Union[logging_config.GetSinkRequest, dict]] = None, - *, - sink_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogSink: + def get_sink( + self, + request: Optional[Union[logging_config.GetSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: r"""Gets a sink. .. code-block:: python @@ -2103,10 +2259,14 @@ def sample_get_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [sink_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2124,9 +2284,9 @@ def sample_get_sink(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("sink_name", request.sink_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("sink_name", request.sink_name),) + ), ) # Validate the universe domain. @@ -2143,15 +2303,16 @@ def sample_get_sink(): # Done; return the response. return response - def create_sink(self, - request: Optional[Union[logging_config.CreateSinkRequest, dict]] = None, - *, - parent: Optional[str] = None, - sink: Optional[logging_config.LogSink] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogSink: + def create_sink( + self, + request: Optional[Union[logging_config.CreateSinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + sink: Optional[logging_config.LogSink] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: r"""Creates a sink that exports specified log entries to a destination. The export of newly-ingested log entries begins immediately, unless the sink's ``writer_identity`` is not @@ -2241,10 +2402,14 @@ def sample_create_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, sink] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2264,9 +2429,7 @@ def sample_create_sink(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2283,16 +2446,17 @@ def sample_create_sink(): # Done; return the response. return response - def update_sink(self, - request: Optional[Union[logging_config.UpdateSinkRequest, dict]] = None, - *, - sink_name: Optional[str] = None, - sink: Optional[logging_config.LogSink] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogSink: + def update_sink( + self, + request: Optional[Union[logging_config.UpdateSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + sink: Optional[logging_config.LogSink] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: r"""Updates a sink. This method replaces the following fields in the existing sink with values from the new sink: ``destination``, and ``filter``. @@ -2406,10 +2570,14 @@ def sample_update_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [sink_name, sink, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2431,9 +2599,9 @@ def sample_update_sink(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("sink_name", request.sink_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("sink_name", request.sink_name),) + ), ) # Validate the universe domain. @@ -2450,14 +2618,15 @@ def sample_update_sink(): # Done; return the response. return response - def delete_sink(self, - request: Optional[Union[logging_config.DeleteSinkRequest, dict]] = None, - *, - sink_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_sink( + self, + request: Optional[Union[logging_config.DeleteSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a sink. If the sink has a unique ``writer_identity``, then that service account is also deleted. @@ -2517,10 +2686,14 @@ def sample_delete_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [sink_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2538,9 +2711,9 @@ def sample_delete_sink(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("sink_name", request.sink_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("sink_name", request.sink_name),) + ), ) # Validate the universe domain. @@ -2554,16 +2727,17 @@ def sample_delete_sink(): metadata=metadata, ) - def create_link(self, - request: Optional[Union[logging_config.CreateLinkRequest, dict]] = None, - *, - parent: Optional[str] = None, - link: Optional[logging_config.Link] = None, - link_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_link( + self, + request: Optional[Union[logging_config.CreateLinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + link: Optional[logging_config.Link] = None, + link_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Asynchronously creates a linked dataset in BigQuery which makes it possible to use BigQuery to read the logs stored in the log bucket. A log bucket may currently @@ -2651,10 +2825,14 @@ def sample_create_link(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, link, link_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2676,9 +2854,7 @@ def sample_create_link(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2703,14 +2879,15 @@ def sample_create_link(): # Done; return the response. return response - def delete_link(self, - request: Optional[Union[logging_config.DeleteLinkRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_link( + self, + request: Optional[Union[logging_config.DeleteLinkRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Deletes a link. This will also delete the corresponding BigQuery linked dataset. @@ -2786,10 +2963,14 @@ def sample_delete_link(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2807,9 +2988,7 @@ def sample_delete_link(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2834,14 +3013,15 @@ def sample_delete_link(): # Done; return the response. return response - def list_links(self, - request: Optional[Union[logging_config.ListLinksRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLinksPager: + def list_links( + self, + request: Optional[Union[logging_config.ListLinksRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLinksPager: r"""Lists links. .. code-block:: python @@ -2907,10 +3087,14 @@ def sample_list_links(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2928,9 +3112,7 @@ def sample_list_links(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2958,14 +3140,15 @@ def sample_list_links(): # Done; return the response. return response - def get_link(self, - request: Optional[Union[logging_config.GetLinkRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.Link: + def get_link( + self, + request: Optional[Union[logging_config.GetLinkRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Link: r"""Gets a link. .. code-block:: python @@ -3026,10 +3209,14 @@ def sample_get_link(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3047,9 +3234,7 @@ def sample_get_link(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3066,14 +3251,15 @@ def sample_get_link(): # Done; return the response. return response - def list_exclusions(self, - request: Optional[Union[logging_config.ListExclusionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListExclusionsPager: + def list_exclusions( + self, + request: Optional[Union[logging_config.ListExclusionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListExclusionsPager: r"""Lists all the exclusions on the \_Default sink in a parent resource. @@ -3141,10 +3327,14 @@ def sample_list_exclusions(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3162,9 +3352,7 @@ def sample_list_exclusions(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -3192,14 +3380,15 @@ def sample_list_exclusions(): # Done; return the response. return response - def get_exclusion(self, - request: Optional[Union[logging_config.GetExclusionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogExclusion: + def get_exclusion( + self, + request: Optional[Union[logging_config.GetExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: r"""Gets the description of an exclusion in the \_Default sink. .. code-block:: python @@ -3271,10 +3460,14 @@ def sample_get_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3292,9 +3485,7 @@ def sample_get_exclusion(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3311,15 +3502,16 @@ def sample_get_exclusion(): # Done; return the response. return response - def create_exclusion(self, - request: Optional[Union[logging_config.CreateExclusionRequest, dict]] = None, - *, - parent: Optional[str] = None, - exclusion: Optional[logging_config.LogExclusion] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogExclusion: + def create_exclusion( + self, + request: Optional[Union[logging_config.CreateExclusionRequest, dict]] = None, + *, + parent: Optional[str] = None, + exclusion: Optional[logging_config.LogExclusion] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: r"""Creates a new exclusion in the \_Default sink in a specified parent resource. Only log entries belonging to that resource can be excluded. You can have up to 10 exclusions in a resource. @@ -3408,10 +3600,14 @@ def sample_create_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, exclusion] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3431,9 +3627,7 @@ def sample_create_exclusion(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -3450,16 +3644,17 @@ def sample_create_exclusion(): # Done; return the response. return response - def update_exclusion(self, - request: Optional[Union[logging_config.UpdateExclusionRequest, dict]] = None, - *, - name: Optional[str] = None, - exclusion: Optional[logging_config.LogExclusion] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogExclusion: + def update_exclusion( + self, + request: Optional[Union[logging_config.UpdateExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + exclusion: Optional[logging_config.LogExclusion] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: r"""Changes one or more properties of an existing exclusion in the \_Default sink. @@ -3559,10 +3754,14 @@ def sample_update_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, exclusion, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3584,9 +3783,7 @@ def sample_update_exclusion(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3603,14 +3800,15 @@ def sample_update_exclusion(): # Done; return the response. return response - def delete_exclusion(self, - request: Optional[Union[logging_config.DeleteExclusionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_exclusion( + self, + request: Optional[Union[logging_config.DeleteExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes an exclusion in the \_Default sink. .. code-block:: python @@ -3669,10 +3867,14 @@ def sample_delete_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3690,9 +3892,7 @@ def sample_delete_exclusion(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3706,13 +3906,14 @@ def sample_delete_exclusion(): metadata=metadata, ) - def get_cmek_settings(self, - request: Optional[Union[logging_config.GetCmekSettingsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.CmekSettings: + def get_cmek_settings( + self, + request: Optional[Union[logging_config.GetCmekSettingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.CmekSettings: r"""Gets the Logging CMEK settings for the given resource. Note: CMEK for the Log Router can be configured for Google Cloud @@ -3795,9 +3996,7 @@ def sample_get_cmek_settings(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3814,13 +4013,14 @@ def sample_get_cmek_settings(): # Done; return the response. return response - def update_cmek_settings(self, - request: Optional[Union[logging_config.UpdateCmekSettingsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.CmekSettings: + def update_cmek_settings( + self, + request: Optional[Union[logging_config.UpdateCmekSettingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.CmekSettings: r"""Updates the Log Router CMEK settings for the given resource. Note: CMEK for the Log Router can currently only be configured @@ -3908,9 +4108,7 @@ def sample_update_cmek_settings(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3927,14 +4125,15 @@ def sample_update_cmek_settings(): # Done; return the response. return response - def get_settings(self, - request: Optional[Union[logging_config.GetSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.Settings: + def get_settings( + self, + request: Optional[Union[logging_config.GetSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Settings: r"""Gets the Log Router settings for the given resource. Note: Settings for the Log Router can be get for Google Cloud @@ -4024,10 +4223,14 @@ def sample_get_settings(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4045,9 +4248,7 @@ def sample_get_settings(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -4064,15 +4265,16 @@ def sample_get_settings(): # Done; return the response. return response - def update_settings(self, - request: Optional[Union[logging_config.UpdateSettingsRequest, dict]] = None, - *, - settings: Optional[logging_config.Settings] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.Settings: + def update_settings( + self, + request: Optional[Union[logging_config.UpdateSettingsRequest, dict]] = None, + *, + settings: Optional[logging_config.Settings] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Settings: r"""Updates the Log Router settings for the given resource. Note: Settings for the Log Router can currently only be @@ -4169,10 +4371,14 @@ def sample_update_settings(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [settings, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4192,9 +4398,7 @@ def sample_update_settings(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -4211,13 +4415,14 @@ def sample_update_settings(): # Done; return the response. return response - def copy_log_entries(self, - request: Optional[Union[logging_config.CopyLogEntriesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def copy_log_entries( + self, + request: Optional[Union[logging_config.CopyLogEntriesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Copies a set of log entries from a log bucket to a Cloud Storage bucket. @@ -4360,8 +4565,7 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -4370,7 +4574,11 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -4420,8 +4628,7 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -4430,7 +4637,11 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -4483,27 +4694,26 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - - - - + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "ConfigServiceV2Client", -) +__all__ = ("ConfigServiceV2Client",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/base.py index 3aba43c4b4aa..bdeabc4a074d 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/base.py @@ -25,14 +25,16 @@ from google.api_core import retry as retries from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf from google.cloud.logging_v2.types import logging_config -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ @@ -42,26 +44,27 @@ class ConfigServiceV2Transport(abc.ABC): """Abstract transport class for ConfigServiceV2.""" AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/logging.admin", + "https://www.googleapis.com/auth/logging.read", ) - DEFAULT_HOST: str = 'logging.googleapis.com' + DEFAULT_HOST: str = "logging.googleapis.com" def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -100,31 +103,43 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host self._wrapped_methods: Dict[Callable, Callable] = {} @@ -388,14 +403,14 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -405,291 +420,306 @@ def operations_client(self): raise NotImplementedError() @property - def list_buckets(self) -> Callable[ - [logging_config.ListBucketsRequest], - Union[ - logging_config.ListBucketsResponse, - Awaitable[logging_config.ListBucketsResponse] - ]]: + def list_buckets( + self, + ) -> Callable[ + [logging_config.ListBucketsRequest], + Union[ + logging_config.ListBucketsResponse, + Awaitable[logging_config.ListBucketsResponse], + ], + ]: raise NotImplementedError() @property - def get_bucket(self) -> Callable[ - [logging_config.GetBucketRequest], - Union[ - logging_config.LogBucket, - Awaitable[logging_config.LogBucket] - ]]: + def get_bucket( + self, + ) -> Callable[ + [logging_config.GetBucketRequest], + Union[logging_config.LogBucket, Awaitable[logging_config.LogBucket]], + ]: raise NotImplementedError() @property - def create_bucket_async(self) -> Callable[ - [logging_config.CreateBucketRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_bucket_async( + self, + ) -> Callable[ + [logging_config.CreateBucketRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def update_bucket_async(self) -> Callable[ - [logging_config.UpdateBucketRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def update_bucket_async( + self, + ) -> Callable[ + [logging_config.UpdateBucketRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def create_bucket(self) -> Callable[ - [logging_config.CreateBucketRequest], - Union[ - logging_config.LogBucket, - Awaitable[logging_config.LogBucket] - ]]: + def create_bucket( + self, + ) -> Callable[ + [logging_config.CreateBucketRequest], + Union[logging_config.LogBucket, Awaitable[logging_config.LogBucket]], + ]: raise NotImplementedError() @property - def update_bucket(self) -> Callable[ - [logging_config.UpdateBucketRequest], - Union[ - logging_config.LogBucket, - Awaitable[logging_config.LogBucket] - ]]: + def update_bucket( + self, + ) -> Callable[ + [logging_config.UpdateBucketRequest], + Union[logging_config.LogBucket, Awaitable[logging_config.LogBucket]], + ]: raise NotImplementedError() @property - def delete_bucket(self) -> Callable[ - [logging_config.DeleteBucketRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_bucket( + self, + ) -> Callable[ + [logging_config.DeleteBucketRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property - def undelete_bucket(self) -> Callable[ - [logging_config.UndeleteBucketRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def undelete_bucket( + self, + ) -> Callable[ + [logging_config.UndeleteBucketRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property - def list_views(self) -> Callable[ - [logging_config.ListViewsRequest], - Union[ - logging_config.ListViewsResponse, - Awaitable[logging_config.ListViewsResponse] - ]]: + def list_views( + self, + ) -> Callable[ + [logging_config.ListViewsRequest], + Union[ + logging_config.ListViewsResponse, + Awaitable[logging_config.ListViewsResponse], + ], + ]: raise NotImplementedError() @property - def get_view(self) -> Callable[ - [logging_config.GetViewRequest], - Union[ - logging_config.LogView, - Awaitable[logging_config.LogView] - ]]: + def get_view( + self, + ) -> Callable[ + [logging_config.GetViewRequest], + Union[logging_config.LogView, Awaitable[logging_config.LogView]], + ]: raise NotImplementedError() @property - def create_view(self) -> Callable[ - [logging_config.CreateViewRequest], - Union[ - logging_config.LogView, - Awaitable[logging_config.LogView] - ]]: + def create_view( + self, + ) -> Callable[ + [logging_config.CreateViewRequest], + Union[logging_config.LogView, Awaitable[logging_config.LogView]], + ]: raise NotImplementedError() @property - def update_view(self) -> Callable[ - [logging_config.UpdateViewRequest], - Union[ - logging_config.LogView, - Awaitable[logging_config.LogView] - ]]: + def update_view( + self, + ) -> Callable[ + [logging_config.UpdateViewRequest], + Union[logging_config.LogView, Awaitable[logging_config.LogView]], + ]: raise NotImplementedError() @property - def delete_view(self) -> Callable[ - [logging_config.DeleteViewRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_view( + self, + ) -> Callable[ + [logging_config.DeleteViewRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property - def list_sinks(self) -> Callable[ - [logging_config.ListSinksRequest], - Union[ - logging_config.ListSinksResponse, - Awaitable[logging_config.ListSinksResponse] - ]]: + def list_sinks( + self, + ) -> Callable[ + [logging_config.ListSinksRequest], + Union[ + logging_config.ListSinksResponse, + Awaitable[logging_config.ListSinksResponse], + ], + ]: raise NotImplementedError() @property - def get_sink(self) -> Callable[ - [logging_config.GetSinkRequest], - Union[ - logging_config.LogSink, - Awaitable[logging_config.LogSink] - ]]: + def get_sink( + self, + ) -> Callable[ + [logging_config.GetSinkRequest], + Union[logging_config.LogSink, Awaitable[logging_config.LogSink]], + ]: raise NotImplementedError() @property - def create_sink(self) -> Callable[ - [logging_config.CreateSinkRequest], - Union[ - logging_config.LogSink, - Awaitable[logging_config.LogSink] - ]]: + def create_sink( + self, + ) -> Callable[ + [logging_config.CreateSinkRequest], + Union[logging_config.LogSink, Awaitable[logging_config.LogSink]], + ]: raise NotImplementedError() @property - def update_sink(self) -> Callable[ - [logging_config.UpdateSinkRequest], - Union[ - logging_config.LogSink, - Awaitable[logging_config.LogSink] - ]]: + def update_sink( + self, + ) -> Callable[ + [logging_config.UpdateSinkRequest], + Union[logging_config.LogSink, Awaitable[logging_config.LogSink]], + ]: raise NotImplementedError() @property - def delete_sink(self) -> Callable[ - [logging_config.DeleteSinkRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_sink( + self, + ) -> Callable[ + [logging_config.DeleteSinkRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property - def create_link(self) -> Callable[ - [logging_config.CreateLinkRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_link( + self, + ) -> Callable[ + [logging_config.CreateLinkRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def delete_link(self) -> Callable[ - [logging_config.DeleteLinkRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def delete_link( + self, + ) -> Callable[ + [logging_config.DeleteLinkRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def list_links(self) -> Callable[ - [logging_config.ListLinksRequest], - Union[ - logging_config.ListLinksResponse, - Awaitable[logging_config.ListLinksResponse] - ]]: + def list_links( + self, + ) -> Callable[ + [logging_config.ListLinksRequest], + Union[ + logging_config.ListLinksResponse, + Awaitable[logging_config.ListLinksResponse], + ], + ]: raise NotImplementedError() @property - def get_link(self) -> Callable[ - [logging_config.GetLinkRequest], - Union[ - logging_config.Link, - Awaitable[logging_config.Link] - ]]: + def get_link( + self, + ) -> Callable[ + [logging_config.GetLinkRequest], + Union[logging_config.Link, Awaitable[logging_config.Link]], + ]: raise NotImplementedError() @property - def list_exclusions(self) -> Callable[ - [logging_config.ListExclusionsRequest], - Union[ - logging_config.ListExclusionsResponse, - Awaitable[logging_config.ListExclusionsResponse] - ]]: + def list_exclusions( + self, + ) -> Callable[ + [logging_config.ListExclusionsRequest], + Union[ + logging_config.ListExclusionsResponse, + Awaitable[logging_config.ListExclusionsResponse], + ], + ]: raise NotImplementedError() @property - def get_exclusion(self) -> Callable[ - [logging_config.GetExclusionRequest], - Union[ - logging_config.LogExclusion, - Awaitable[logging_config.LogExclusion] - ]]: + def get_exclusion( + self, + ) -> Callable[ + [logging_config.GetExclusionRequest], + Union[logging_config.LogExclusion, Awaitable[logging_config.LogExclusion]], + ]: raise NotImplementedError() @property - def create_exclusion(self) -> Callable[ - [logging_config.CreateExclusionRequest], - Union[ - logging_config.LogExclusion, - Awaitable[logging_config.LogExclusion] - ]]: + def create_exclusion( + self, + ) -> Callable[ + [logging_config.CreateExclusionRequest], + Union[logging_config.LogExclusion, Awaitable[logging_config.LogExclusion]], + ]: raise NotImplementedError() @property - def update_exclusion(self) -> Callable[ - [logging_config.UpdateExclusionRequest], - Union[ - logging_config.LogExclusion, - Awaitable[logging_config.LogExclusion] - ]]: + def update_exclusion( + self, + ) -> Callable[ + [logging_config.UpdateExclusionRequest], + Union[logging_config.LogExclusion, Awaitable[logging_config.LogExclusion]], + ]: raise NotImplementedError() @property - def delete_exclusion(self) -> Callable[ - [logging_config.DeleteExclusionRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_exclusion( + self, + ) -> Callable[ + [logging_config.DeleteExclusionRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property - def get_cmek_settings(self) -> Callable[ - [logging_config.GetCmekSettingsRequest], - Union[ - logging_config.CmekSettings, - Awaitable[logging_config.CmekSettings] - ]]: + def get_cmek_settings( + self, + ) -> Callable[ + [logging_config.GetCmekSettingsRequest], + Union[logging_config.CmekSettings, Awaitable[logging_config.CmekSettings]], + ]: raise NotImplementedError() @property - def update_cmek_settings(self) -> Callable[ - [logging_config.UpdateCmekSettingsRequest], - Union[ - logging_config.CmekSettings, - Awaitable[logging_config.CmekSettings] - ]]: + def update_cmek_settings( + self, + ) -> Callable[ + [logging_config.UpdateCmekSettingsRequest], + Union[logging_config.CmekSettings, Awaitable[logging_config.CmekSettings]], + ]: raise NotImplementedError() @property - def get_settings(self) -> Callable[ - [logging_config.GetSettingsRequest], - Union[ - logging_config.Settings, - Awaitable[logging_config.Settings] - ]]: + def get_settings( + self, + ) -> Callable[ + [logging_config.GetSettingsRequest], + Union[logging_config.Settings, Awaitable[logging_config.Settings]], + ]: raise NotImplementedError() @property - def update_settings(self) -> Callable[ - [logging_config.UpdateSettingsRequest], - Union[ - logging_config.Settings, - Awaitable[logging_config.Settings] - ]]: + def update_settings( + self, + ) -> Callable[ + [logging_config.UpdateSettingsRequest], + Union[logging_config.Settings, Awaitable[logging_config.Settings]], + ]: raise NotImplementedError() @property - def copy_log_entries(self) -> Callable[ - [logging_config.CopyLogEntriesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def copy_log_entries( + self, + ) -> Callable[ + [logging_config.CopyLogEntriesRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property @@ -697,7 +727,10 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], ]: raise NotImplementedError() @@ -713,10 +746,7 @@ def get_operation( @property def cancel_operation( self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: raise NotImplementedError() @property @@ -724,6 +754,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'ConfigServiceV2Transport', -) +__all__ = ("ConfigServiceV2Transport",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/async_client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/async_client.py index 5e5d98cf31ba..233967cd530d 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/async_client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/async_client.py @@ -16,7 +16,21 @@ import logging as std_logging from collections import OrderedDict import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Type, Union +from typing import ( + Dict, + Callable, + Mapping, + MutableMapping, + MutableSequence, + Optional, + AsyncIterable, + Awaitable, + AsyncIterator, + Sequence, + Tuple, + Type, + Union, +) from google.cloud.logging_v2 import gapic_version as package_version @@ -24,8 +38,8 @@ from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf @@ -37,7 +51,7 @@ from google.cloud.logging_v2.services.logging_service_v2 import pagers from google.cloud.logging_v2.types import log_entry from google.cloud.logging_v2.types import logging -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.api.monitored_resource_pb2 as monitored_resource_pb2 # type: ignore from .transports.base import LoggingServiceV2Transport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import LoggingServiceV2GrpcAsyncIOTransport @@ -45,12 +59,14 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) + class LoggingServiceV2AsyncClient: """Service for ingesting and querying logs.""" @@ -65,16 +81,30 @@ class LoggingServiceV2AsyncClient: log_path = staticmethod(LoggingServiceV2Client.log_path) parse_log_path = staticmethod(LoggingServiceV2Client.parse_log_path) - common_billing_account_path = staticmethod(LoggingServiceV2Client.common_billing_account_path) - parse_common_billing_account_path = staticmethod(LoggingServiceV2Client.parse_common_billing_account_path) + common_billing_account_path = staticmethod( + LoggingServiceV2Client.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + LoggingServiceV2Client.parse_common_billing_account_path + ) common_folder_path = staticmethod(LoggingServiceV2Client.common_folder_path) - parse_common_folder_path = staticmethod(LoggingServiceV2Client.parse_common_folder_path) - common_organization_path = staticmethod(LoggingServiceV2Client.common_organization_path) - parse_common_organization_path = staticmethod(LoggingServiceV2Client.parse_common_organization_path) + parse_common_folder_path = staticmethod( + LoggingServiceV2Client.parse_common_folder_path + ) + common_organization_path = staticmethod( + LoggingServiceV2Client.common_organization_path + ) + parse_common_organization_path = staticmethod( + LoggingServiceV2Client.parse_common_organization_path + ) common_project_path = staticmethod(LoggingServiceV2Client.common_project_path) - parse_common_project_path = staticmethod(LoggingServiceV2Client.parse_common_project_path) + parse_common_project_path = staticmethod( + LoggingServiceV2Client.parse_common_project_path + ) common_location_path = staticmethod(LoggingServiceV2Client.common_location_path) - parse_common_location_path = staticmethod(LoggingServiceV2Client.parse_common_location_path) + parse_common_location_path = staticmethod( + LoggingServiceV2Client.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -116,7 +146,9 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): """Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -179,12 +211,18 @@ def universe_domain(self) -> str: get_transport_class = LoggingServiceV2Client.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, LoggingServiceV2Transport, Callable[..., LoggingServiceV2Transport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, LoggingServiceV2Transport, Callable[..., LoggingServiceV2Transport] + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the logging service v2 async client. Args: @@ -239,31 +277,39 @@ def __init__(self, *, transport=transport, client_options=client_options, client_info=client_info, - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.logging_v2.LoggingServiceV2AsyncClient`.", - extra = { + extra={ "serviceName": "google.logging.v2.LoggingServiceV2", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { "serviceName": "google.logging.v2.LoggingServiceV2", "credentialsType": None, - } + }, ) - async def delete_log(self, - request: Optional[Union[logging.DeleteLogRequest, dict]] = None, - *, - log_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def delete_log( + self, + request: Optional[Union[logging.DeleteLogRequest, dict]] = None, + *, + log_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes all the log entries in a log for the \_Default Log Bucket. The log reappears if it receives new entries. Log entries written shortly before the delete operation might not be @@ -326,10 +372,14 @@ async def sample_delete_log(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [log_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -343,14 +393,14 @@ async def sample_delete_log(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_log] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_log + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("log_name", request.log_name), - )), + gapic_v1.routing_header.to_grpc_metadata((("log_name", request.log_name),)), ) # Validate the universe domain. @@ -364,17 +414,18 @@ async def sample_delete_log(): metadata=metadata, ) - async def write_log_entries(self, - request: Optional[Union[logging.WriteLogEntriesRequest, dict]] = None, - *, - log_name: Optional[str] = None, - resource: Optional[monitored_resource_pb2.MonitoredResource] = None, - labels: Optional[MutableMapping[str, str]] = None, - entries: Optional[MutableSequence[log_entry.LogEntry]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging.WriteLogEntriesResponse: + async def write_log_entries( + self, + request: Optional[Union[logging.WriteLogEntriesRequest, dict]] = None, + *, + log_name: Optional[str] = None, + resource: Optional[monitored_resource_pb2.MonitoredResource] = None, + labels: Optional[MutableMapping[str, str]] = None, + entries: Optional[MutableSequence[log_entry.LogEntry]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging.WriteLogEntriesResponse: r"""Writes log entries to Logging. This API method is the only way to send log entries to Logging. This method is used, directly or indirectly, by the Logging agent @@ -517,10 +568,14 @@ async def sample_write_log_entries(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [log_name, resource, labels, entries] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -541,7 +596,9 @@ async def sample_write_log_entries(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.write_log_entries] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.write_log_entries + ] # Validate the universe domain. self._client._validate_universe_domain() @@ -557,16 +614,17 @@ async def sample_write_log_entries(): # Done; return the response. return response - async def list_log_entries(self, - request: Optional[Union[logging.ListLogEntriesRequest, dict]] = None, - *, - resource_names: Optional[MutableSequence[str]] = None, - filter: Optional[str] = None, - order_by: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLogEntriesAsyncPager: + async def list_log_entries( + self, + request: Optional[Union[logging.ListLogEntriesRequest, dict]] = None, + *, + resource_names: Optional[MutableSequence[str]] = None, + filter: Optional[str] = None, + order_by: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogEntriesAsyncPager: r"""Lists log entries. Use this method to retrieve log entries that originated from a project/folder/organization/billing account. For ways to export log entries, see `Exporting @@ -669,10 +727,14 @@ async def sample_list_log_entries(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [resource_names, filter, order_by] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -690,7 +752,9 @@ async def sample_list_log_entries(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_log_entries] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_log_entries + ] # Validate the universe domain. self._client._validate_universe_domain() @@ -717,13 +781,16 @@ async def sample_list_log_entries(): # Done; return the response. return response - async def list_monitored_resource_descriptors(self, - request: Optional[Union[logging.ListMonitoredResourceDescriptorsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListMonitoredResourceDescriptorsAsyncPager: + async def list_monitored_resource_descriptors( + self, + request: Optional[ + Union[logging.ListMonitoredResourceDescriptorsRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMonitoredResourceDescriptorsAsyncPager: r"""Lists the descriptors for monitored resource types used by Logging. @@ -782,7 +849,9 @@ async def sample_list_monitored_resource_descriptors(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_monitored_resource_descriptors] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_monitored_resource_descriptors + ] # Validate the universe domain. self._client._validate_universe_domain() @@ -809,14 +878,15 @@ async def sample_list_monitored_resource_descriptors(): # Done; return the response. return response - async def list_logs(self, - request: Optional[Union[logging.ListLogsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLogsAsyncPager: + async def list_logs( + self, + request: Optional[Union[logging.ListLogsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogsAsyncPager: r"""Lists the logs in projects, organizations, folders, or billing accounts. Only logs that have entries are listed. @@ -883,10 +953,14 @@ async def sample_list_logs(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -900,14 +974,14 @@ async def sample_list_logs(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_logs] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_logs + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -935,13 +1009,14 @@ async def sample_list_logs(): # Done; return the response. return response - def tail_log_entries(self, - requests: Optional[AsyncIterator[logging.TailLogEntriesRequest]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> Awaitable[AsyncIterable[logging.TailLogEntriesResponse]]: + def tail_log_entries( + self, + requests: Optional[AsyncIterator[logging.TailLogEntriesRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Awaitable[AsyncIterable[logging.TailLogEntriesResponse]]: r"""Streaming read of log entries as they are ingested. Until the stream is terminated, it will continue reading logs. @@ -1001,7 +1076,9 @@ def request_generator(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.tail_log_entries] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.tail_log_entries + ] # Validate the universe domain. self._client._validate_universe_domain() @@ -1059,8 +1136,7 @@ async def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1068,7 +1144,11 @@ async def list_operations( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1115,8 +1195,7 @@ async def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1124,7 +1203,11 @@ async def get_operation( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1174,15 +1257,19 @@ async def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) async def __aenter__(self) -> "LoggingServiceV2AsyncClient": return self @@ -1190,12 +1277,13 @@ async def __aenter__(self) -> "LoggingServiceV2AsyncClient": async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "LoggingServiceV2AsyncClient", -) +__all__ = ("LoggingServiceV2AsyncClient",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py index db711c4593a8..f3758559e92f 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py @@ -19,7 +19,21 @@ import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union, cast +from typing import ( + Dict, + Callable, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Iterable, + Iterator, + Sequence, + Tuple, + Type, + Union, + cast, +) import warnings from google.cloud.logging_v2 import gapic_version as package_version @@ -28,11 +42,11 @@ from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.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.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 import google.protobuf try: @@ -42,6 +56,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -51,7 +66,7 @@ from google.cloud.logging_v2.services.logging_service_v2 import pagers from google.cloud.logging_v2.types import log_entry from google.cloud.logging_v2.types import logging -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.api.monitored_resource_pb2 as monitored_resource_pb2 # type: ignore from .transports.base import LoggingServiceV2Transport, DEFAULT_CLIENT_INFO from .transports.grpc import LoggingServiceV2GrpcTransport @@ -65,13 +80,17 @@ class LoggingServiceV2ClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[LoggingServiceV2Transport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[LoggingServiceV2Transport]] _transport_registry["grpc"] = LoggingServiceV2GrpcTransport _transport_registry["grpc_asyncio"] = LoggingServiceV2GrpcAsyncIOTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[LoggingServiceV2Transport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[LoggingServiceV2Transport]: """Returns an appropriate transport class. Args: @@ -147,14 +166,16 @@ def _use_client_cert_effective(): bool: whether client certificate should be used for mTLS Raises: ValueError: (If using a version of google-auth without should_use_client_cert and - GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) """ # check if google-auth version supports should_use_client_cert for automatic mTLS enablement if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER return mtls.should_use_client_cert() - else: # pragma: NO COVER + else: # pragma: NO COVER # if unsupported, fallback to reading from env var - use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() if use_client_cert_str not in ("true", "false"): raise ValueError( "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" @@ -193,8 +214,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: LoggingServiceV2Client: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -211,73 +231,103 @@ def transport(self) -> LoggingServiceV2Transport: return self._transport @staticmethod - def log_path(project: str,log: str,) -> str: + def log_path( + project: str, + log: str, + ) -> str: """Returns a fully-qualified log string.""" - return "projects/{project}/logs/{log}".format(project=project, log=log, ) + return "projects/{project}/logs/{log}".format( + project=project, + log=log, + ) @staticmethod - def parse_log_path(path: str) -> Dict[str,str]: + def parse_log_path(path: str) -> Dict[str, str]: """Parses a log path into its component segments.""" m = re.match(r"^projects/(?P.+?)/logs/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + def common_billing_account_path( + billing_account: str, + ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path(folder: str, ) -> str: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path(organization: str, ) -> str: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path(project: str, ) -> str: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path(project: str, location: str, ) -> str: + def common_location_path( + project: str, + location: str, + ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -309,14 +359,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = LoggingServiceV2Client._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Figure out the client cert source to use. client_cert_source = None @@ -329,7 +383,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): api_endpoint = cls.DEFAULT_MTLS_ENDPOINT else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -354,7 +410,9 @@ def _read_environment_variables(): use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod @@ -377,7 +435,9 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: """Return the API endpoint used by the client. Args: @@ -393,17 +453,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): _default_universe = LoggingServiceV2Client._DEFAULT_UNIVERSE if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) api_endpoint = LoggingServiceV2Client.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = LoggingServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = LoggingServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) return api_endpoint @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: """Return the universe domain used by the client. Args: @@ -439,15 +507,18 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError + self, error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: return cred = self._transport._credentials @@ -480,12 +551,18 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, LoggingServiceV2Transport, Callable[..., LoggingServiceV2Transport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, LoggingServiceV2Transport, Callable[..., LoggingServiceV2Transport] + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the logging service v2 client. Args: @@ -540,13 +617,23 @@ def __init__(self, *, self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = LoggingServiceV2Client._read_environment_variables() - self._client_cert_source = LoggingServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = LoggingServiceV2Client._get_universe_domain(universe_domain_opt, self._universe_domain_env) + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = LoggingServiceV2Client._read_environment_variables() + self._client_cert_source = LoggingServiceV2Client._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = LoggingServiceV2Client._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -558,7 +645,9 @@ def __init__(self, *, api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -567,8 +656,10 @@ def __init__(self, *, if transport_provided: # transport is a LoggingServiceV2Transport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if self._client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes " @@ -577,20 +668,30 @@ def __init__(self, *, self._transport = cast(LoggingServiceV2Transport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - LoggingServiceV2Client._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or LoggingServiceV2Client._get_api_endpoint( self._client_options.api_endpoint, self._client_cert_source, self._universe_domain, - self._use_mtls_endpoint)) + self._use_mtls_endpoint, + ) + ) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) - transport_init: Union[Type[LoggingServiceV2Transport], Callable[..., LoggingServiceV2Transport]] = ( + transport_init: Union[ + Type[LoggingServiceV2Transport], + Callable[..., LoggingServiceV2Transport], + ] = ( LoggingServiceV2Client.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., LoggingServiceV2Transport], transport) @@ -609,28 +710,37 @@ def __init__(self, *, ) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.logging_v2.LoggingServiceV2Client`.", - extra = { + extra={ "serviceName": "google.logging.v2.LoggingServiceV2", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { "serviceName": "google.logging.v2.LoggingServiceV2", "credentialsType": None, - } + }, ) - def delete_log(self, - request: Optional[Union[logging.DeleteLogRequest, dict]] = None, - *, - log_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_log( + self, + request: Optional[Union[logging.DeleteLogRequest, dict]] = None, + *, + log_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes all the log entries in a log for the \_Default Log Bucket. The log reappears if it receives new entries. Log entries written shortly before the delete operation might not be @@ -693,10 +803,14 @@ def sample_delete_log(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [log_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -714,9 +828,7 @@ def sample_delete_log(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("log_name", request.log_name), - )), + gapic_v1.routing_header.to_grpc_metadata((("log_name", request.log_name),)), ) # Validate the universe domain. @@ -730,17 +842,18 @@ def sample_delete_log(): metadata=metadata, ) - def write_log_entries(self, - request: Optional[Union[logging.WriteLogEntriesRequest, dict]] = None, - *, - log_name: Optional[str] = None, - resource: Optional[monitored_resource_pb2.MonitoredResource] = None, - labels: Optional[MutableMapping[str, str]] = None, - entries: Optional[MutableSequence[log_entry.LogEntry]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging.WriteLogEntriesResponse: + def write_log_entries( + self, + request: Optional[Union[logging.WriteLogEntriesRequest, dict]] = None, + *, + log_name: Optional[str] = None, + resource: Optional[monitored_resource_pb2.MonitoredResource] = None, + labels: Optional[MutableMapping[str, str]] = None, + entries: Optional[MutableSequence[log_entry.LogEntry]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging.WriteLogEntriesResponse: r"""Writes log entries to Logging. This API method is the only way to send log entries to Logging. This method is used, directly or indirectly, by the Logging agent @@ -883,10 +996,14 @@ def sample_write_log_entries(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [log_name, resource, labels, entries] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -921,16 +1038,17 @@ def sample_write_log_entries(): # Done; return the response. return response - def list_log_entries(self, - request: Optional[Union[logging.ListLogEntriesRequest, dict]] = None, - *, - resource_names: Optional[MutableSequence[str]] = None, - filter: Optional[str] = None, - order_by: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLogEntriesPager: + def list_log_entries( + self, + request: Optional[Union[logging.ListLogEntriesRequest, dict]] = None, + *, + resource_names: Optional[MutableSequence[str]] = None, + filter: Optional[str] = None, + order_by: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogEntriesPager: r"""Lists log entries. Use this method to retrieve log entries that originated from a project/folder/organization/billing account. For ways to export log entries, see `Exporting @@ -1033,10 +1151,14 @@ def sample_list_log_entries(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [resource_names, filter, order_by] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1080,13 +1202,16 @@ def sample_list_log_entries(): # Done; return the response. return response - def list_monitored_resource_descriptors(self, - request: Optional[Union[logging.ListMonitoredResourceDescriptorsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListMonitoredResourceDescriptorsPager: + def list_monitored_resource_descriptors( + self, + request: Optional[ + Union[logging.ListMonitoredResourceDescriptorsRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMonitoredResourceDescriptorsPager: r"""Lists the descriptors for monitored resource types used by Logging. @@ -1145,7 +1270,9 @@ def sample_list_monitored_resource_descriptors(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_monitored_resource_descriptors] + rpc = self._transport._wrapped_methods[ + self._transport.list_monitored_resource_descriptors + ] # Validate the universe domain. self._validate_universe_domain() @@ -1172,14 +1299,15 @@ def sample_list_monitored_resource_descriptors(): # Done; return the response. return response - def list_logs(self, - request: Optional[Union[logging.ListLogsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLogsPager: + def list_logs( + self, + request: Optional[Union[logging.ListLogsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogsPager: r"""Lists the logs in projects, organizations, folders, or billing accounts. Only logs that have entries are listed. @@ -1246,10 +1374,14 @@ def sample_list_logs(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1267,9 +1399,7 @@ def sample_list_logs(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1297,13 +1427,14 @@ def sample_list_logs(): # Done; return the response. return response - def tail_log_entries(self, - requests: Optional[Iterator[logging.TailLogEntriesRequest]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> Iterable[logging.TailLogEntriesResponse]: + def tail_log_entries( + self, + requests: Optional[Iterator[logging.TailLogEntriesRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Iterable[logging.TailLogEntriesResponse]: r"""Streaming read of log entries as they are ingested. Until the stream is terminated, it will continue reading logs. @@ -1434,8 +1565,7 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1444,7 +1574,11 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1494,8 +1628,7 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1504,7 +1637,11 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1557,27 +1694,26 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - - - - + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "LoggingServiceV2Client", -) +__all__ = ("LoggingServiceV2Client",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/base.py index 4a1e028497d8..fccfc2c3f06a 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/base.py @@ -24,14 +24,16 @@ from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf from google.cloud.logging_v2.types import logging -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ @@ -41,27 +43,28 @@ class LoggingServiceV2Transport(abc.ABC): """Abstract transport class for LoggingServiceV2.""" AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write', + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/logging.admin", + "https://www.googleapis.com/auth/logging.read", + "https://www.googleapis.com/auth/logging.write", ) - DEFAULT_HOST: str = 'logging.googleapis.com' + DEFAULT_HOST: str = "logging.googleapis.com" def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -100,31 +103,43 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host self._wrapped_methods: Dict[Callable, Callable] = {} @@ -247,69 +262,77 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @property - def delete_log(self) -> Callable[ - [logging.DeleteLogRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_log( + self, + ) -> Callable[ + [logging.DeleteLogRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] + ]: raise NotImplementedError() @property - def write_log_entries(self) -> Callable[ - [logging.WriteLogEntriesRequest], - Union[ - logging.WriteLogEntriesResponse, - Awaitable[logging.WriteLogEntriesResponse] - ]]: + def write_log_entries( + self, + ) -> Callable[ + [logging.WriteLogEntriesRequest], + Union[ + logging.WriteLogEntriesResponse, Awaitable[logging.WriteLogEntriesResponse] + ], + ]: raise NotImplementedError() @property - def list_log_entries(self) -> Callable[ - [logging.ListLogEntriesRequest], - Union[ - logging.ListLogEntriesResponse, - Awaitable[logging.ListLogEntriesResponse] - ]]: + def list_log_entries( + self, + ) -> Callable[ + [logging.ListLogEntriesRequest], + Union[ + logging.ListLogEntriesResponse, Awaitable[logging.ListLogEntriesResponse] + ], + ]: raise NotImplementedError() @property - def list_monitored_resource_descriptors(self) -> Callable[ - [logging.ListMonitoredResourceDescriptorsRequest], - Union[ - logging.ListMonitoredResourceDescriptorsResponse, - Awaitable[logging.ListMonitoredResourceDescriptorsResponse] - ]]: + def list_monitored_resource_descriptors( + self, + ) -> Callable[ + [logging.ListMonitoredResourceDescriptorsRequest], + Union[ + logging.ListMonitoredResourceDescriptorsResponse, + Awaitable[logging.ListMonitoredResourceDescriptorsResponse], + ], + ]: raise NotImplementedError() @property - def list_logs(self) -> Callable[ - [logging.ListLogsRequest], - Union[ - logging.ListLogsResponse, - Awaitable[logging.ListLogsResponse] - ]]: + def list_logs( + self, + ) -> Callable[ + [logging.ListLogsRequest], + Union[logging.ListLogsResponse, Awaitable[logging.ListLogsResponse]], + ]: raise NotImplementedError() @property - def tail_log_entries(self) -> Callable[ - [logging.TailLogEntriesRequest], - Union[ - logging.TailLogEntriesResponse, - Awaitable[logging.TailLogEntriesResponse] - ]]: + def tail_log_entries( + self, + ) -> Callable[ + [logging.TailLogEntriesRequest], + Union[ + logging.TailLogEntriesResponse, Awaitable[logging.TailLogEntriesResponse] + ], + ]: raise NotImplementedError() @property @@ -317,7 +340,10 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], ]: raise NotImplementedError() @@ -333,10 +359,7 @@ def get_operation( @property def cancel_operation( self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: raise NotImplementedError() @property @@ -344,6 +367,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'LoggingServiceV2Transport', -) +__all__ = ("LoggingServiceV2Transport",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/async_client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/async_client.py index 1830e048ed7e..e4aa5270483f 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/async_client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/async_client.py @@ -16,7 +16,18 @@ import logging as std_logging from collections import OrderedDict import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union +from typing import ( + Dict, + Callable, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) from google.cloud.logging_v2 import gapic_version as package_version @@ -24,8 +35,8 @@ from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf @@ -36,7 +47,7 @@ from google.cloud.logging_v2.services.metrics_service_v2 import pagers from google.cloud.logging_v2.types import logging_metrics -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.api.distribution_pb2 as distribution_pb2 # type: ignore import google.api.metric_pb2 as metric_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore @@ -46,12 +57,14 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) + class MetricsServiceV2AsyncClient: """Service for configuring logs-based metrics.""" @@ -66,16 +79,30 @@ class MetricsServiceV2AsyncClient: log_metric_path = staticmethod(MetricsServiceV2Client.log_metric_path) parse_log_metric_path = staticmethod(MetricsServiceV2Client.parse_log_metric_path) - common_billing_account_path = staticmethod(MetricsServiceV2Client.common_billing_account_path) - parse_common_billing_account_path = staticmethod(MetricsServiceV2Client.parse_common_billing_account_path) + common_billing_account_path = staticmethod( + MetricsServiceV2Client.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + MetricsServiceV2Client.parse_common_billing_account_path + ) common_folder_path = staticmethod(MetricsServiceV2Client.common_folder_path) - parse_common_folder_path = staticmethod(MetricsServiceV2Client.parse_common_folder_path) - common_organization_path = staticmethod(MetricsServiceV2Client.common_organization_path) - parse_common_organization_path = staticmethod(MetricsServiceV2Client.parse_common_organization_path) + parse_common_folder_path = staticmethod( + MetricsServiceV2Client.parse_common_folder_path + ) + common_organization_path = staticmethod( + MetricsServiceV2Client.common_organization_path + ) + parse_common_organization_path = staticmethod( + MetricsServiceV2Client.parse_common_organization_path + ) common_project_path = staticmethod(MetricsServiceV2Client.common_project_path) - parse_common_project_path = staticmethod(MetricsServiceV2Client.parse_common_project_path) + parse_common_project_path = staticmethod( + MetricsServiceV2Client.parse_common_project_path + ) common_location_path = staticmethod(MetricsServiceV2Client.common_location_path) - parse_common_location_path = staticmethod(MetricsServiceV2Client.parse_common_location_path) + parse_common_location_path = staticmethod( + MetricsServiceV2Client.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -117,7 +144,9 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): """Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -180,12 +209,18 @@ def universe_domain(self) -> str: get_transport_class = MetricsServiceV2Client.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, MetricsServiceV2Transport, Callable[..., MetricsServiceV2Transport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, MetricsServiceV2Transport, Callable[..., MetricsServiceV2Transport] + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the metrics service v2 async client. Args: @@ -240,31 +275,39 @@ def __init__(self, *, transport=transport, client_options=client_options, client_info=client_info, - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.logging_v2.MetricsServiceV2AsyncClient`.", - extra = { + extra={ "serviceName": "google.logging.v2.MetricsServiceV2", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { "serviceName": "google.logging.v2.MetricsServiceV2", "credentialsType": None, - } + }, ) - async def list_log_metrics(self, - request: Optional[Union[logging_metrics.ListLogMetricsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLogMetricsAsyncPager: + async def list_log_metrics( + self, + request: Optional[Union[logging_metrics.ListLogMetricsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogMetricsAsyncPager: r"""Lists logs-based metrics. .. code-block:: python @@ -329,10 +372,14 @@ async def sample_list_log_metrics(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -346,14 +393,14 @@ async def sample_list_log_metrics(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_log_metrics] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_log_metrics + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -381,14 +428,15 @@ async def sample_list_log_metrics(): # Done; return the response. return response - async def get_log_metric(self, - request: Optional[Union[logging_metrics.GetLogMetricRequest, dict]] = None, - *, - metric_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_metrics.LogMetric: + async def get_log_metric( + self, + request: Optional[Union[logging_metrics.GetLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: r"""Gets a logs-based metric. .. code-block:: python @@ -458,10 +506,14 @@ async def sample_get_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [metric_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -475,14 +527,16 @@ async def sample_get_log_metric(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_log_metric] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_log_metric + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("metric_name", request.metric_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("metric_name", request.metric_name),) + ), ) # Validate the universe domain. @@ -499,15 +553,16 @@ async def sample_get_log_metric(): # Done; return the response. return response - async def create_log_metric(self, - request: Optional[Union[logging_metrics.CreateLogMetricRequest, dict]] = None, - *, - parent: Optional[str] = None, - metric: Optional[logging_metrics.LogMetric] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_metrics.LogMetric: + async def create_log_metric( + self, + request: Optional[Union[logging_metrics.CreateLogMetricRequest, dict]] = None, + *, + parent: Optional[str] = None, + metric: Optional[logging_metrics.LogMetric] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: r"""Creates a logs-based metric. .. code-block:: python @@ -593,10 +648,14 @@ async def sample_create_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, metric] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -612,14 +671,14 @@ async def sample_create_log_metric(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_log_metric] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_log_metric + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -636,15 +695,16 @@ async def sample_create_log_metric(): # Done; return the response. return response - async def update_log_metric(self, - request: Optional[Union[logging_metrics.UpdateLogMetricRequest, dict]] = None, - *, - metric_name: Optional[str] = None, - metric: Optional[logging_metrics.LogMetric] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_metrics.LogMetric: + async def update_log_metric( + self, + request: Optional[Union[logging_metrics.UpdateLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + metric: Optional[logging_metrics.LogMetric] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: r"""Creates or updates a logs-based metric. .. code-block:: python @@ -729,10 +789,14 @@ async def sample_update_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [metric_name, metric] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -748,14 +812,16 @@ async def sample_update_log_metric(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_log_metric] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_log_metric + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("metric_name", request.metric_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("metric_name", request.metric_name),) + ), ) # Validate the universe domain. @@ -772,14 +838,15 @@ async def sample_update_log_metric(): # Done; return the response. return response - async def delete_log_metric(self, - request: Optional[Union[logging_metrics.DeleteLogMetricRequest, dict]] = None, - *, - metric_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def delete_log_metric( + self, + request: Optional[Union[logging_metrics.DeleteLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a logs-based metric. .. code-block:: python @@ -830,10 +897,14 @@ async def sample_delete_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [metric_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -847,14 +918,16 @@ async def sample_delete_log_metric(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_log_metric] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_log_metric + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("metric_name", request.metric_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("metric_name", request.metric_name),) + ), ) # Validate the universe domain. @@ -910,8 +983,7 @@ async def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -919,7 +991,11 @@ async def list_operations( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -966,8 +1042,7 @@ async def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -975,7 +1050,11 @@ async def get_operation( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1025,15 +1104,19 @@ async def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) async def __aenter__(self) -> "MetricsServiceV2AsyncClient": return self @@ -1041,12 +1124,13 @@ async def __aenter__(self) -> "MetricsServiceV2AsyncClient": async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "MetricsServiceV2AsyncClient", -) +__all__ = ("MetricsServiceV2AsyncClient",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py index c8c9ec4677e7..ea8ffde28e11 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py @@ -19,7 +19,19 @@ import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +from typing import ( + Dict, + Callable, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) import warnings from google.cloud.logging_v2 import gapic_version as package_version @@ -28,11 +40,11 @@ from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.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.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 import google.protobuf try: @@ -42,6 +54,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -50,7 +63,7 @@ from google.cloud.logging_v2.services.metrics_service_v2 import pagers from google.cloud.logging_v2.types import logging_metrics -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.api.distribution_pb2 as distribution_pb2 # type: ignore import google.api.metric_pb2 as metric_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore @@ -66,13 +79,17 @@ class MetricsServiceV2ClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[MetricsServiceV2Transport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[MetricsServiceV2Transport]] _transport_registry["grpc"] = MetricsServiceV2GrpcTransport _transport_registry["grpc_asyncio"] = MetricsServiceV2GrpcAsyncIOTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[MetricsServiceV2Transport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[MetricsServiceV2Transport]: """Returns an appropriate transport class. Args: @@ -148,14 +165,16 @@ def _use_client_cert_effective(): bool: whether client certificate should be used for mTLS Raises: ValueError: (If using a version of google-auth without should_use_client_cert and - GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) """ # check if google-auth version supports should_use_client_cert for automatic mTLS enablement if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER return mtls.should_use_client_cert() - else: # pragma: NO COVER + else: # pragma: NO COVER # if unsupported, fallback to reading from env var - use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() if use_client_cert_str not in ("true", "false"): raise ValueError( "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" @@ -194,8 +213,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: MetricsServiceV2Client: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -212,73 +230,103 @@ def transport(self) -> MetricsServiceV2Transport: return self._transport @staticmethod - def log_metric_path(project: str,metric: str,) -> str: + def log_metric_path( + project: str, + metric: str, + ) -> str: """Returns a fully-qualified log_metric string.""" - return "projects/{project}/metrics/{metric}".format(project=project, metric=metric, ) + return "projects/{project}/metrics/{metric}".format( + project=project, + metric=metric, + ) @staticmethod - def parse_log_metric_path(path: str) -> Dict[str,str]: + def parse_log_metric_path(path: str) -> Dict[str, str]: """Parses a log_metric path into its component segments.""" m = re.match(r"^projects/(?P.+?)/metrics/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + def common_billing_account_path( + billing_account: str, + ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path(folder: str, ) -> str: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path(organization: str, ) -> str: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path(project: str, ) -> str: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path(project: str, location: str, ) -> str: + def common_location_path( + project: str, + location: str, + ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -310,14 +358,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = MetricsServiceV2Client._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Figure out the client cert source to use. client_cert_source = None @@ -330,7 +382,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): api_endpoint = cls.DEFAULT_MTLS_ENDPOINT else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -355,7 +409,9 @@ def _read_environment_variables(): use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod @@ -378,7 +434,9 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: """Return the API endpoint used by the client. Args: @@ -394,17 +452,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): _default_universe = MetricsServiceV2Client._DEFAULT_UNIVERSE if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) api_endpoint = MetricsServiceV2Client.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = MetricsServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = MetricsServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) return api_endpoint @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: """Return the universe domain used by the client. Args: @@ -440,15 +506,18 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError + self, error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: return cred = self._transport._credentials @@ -481,12 +550,18 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, MetricsServiceV2Transport, Callable[..., MetricsServiceV2Transport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, MetricsServiceV2Transport, Callable[..., MetricsServiceV2Transport] + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the metrics service v2 client. Args: @@ -541,13 +616,23 @@ def __init__(self, *, self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = MetricsServiceV2Client._read_environment_variables() - self._client_cert_source = MetricsServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = MetricsServiceV2Client._get_universe_domain(universe_domain_opt, self._universe_domain_env) + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = MetricsServiceV2Client._read_environment_variables() + self._client_cert_source = MetricsServiceV2Client._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = MetricsServiceV2Client._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -559,7 +644,9 @@ def __init__(self, *, api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -568,8 +655,10 @@ def __init__(self, *, if transport_provided: # transport is a MetricsServiceV2Transport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if self._client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes " @@ -578,20 +667,30 @@ def __init__(self, *, self._transport = cast(MetricsServiceV2Transport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - MetricsServiceV2Client._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or MetricsServiceV2Client._get_api_endpoint( self._client_options.api_endpoint, self._client_cert_source, self._universe_domain, - self._use_mtls_endpoint)) + self._use_mtls_endpoint, + ) + ) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) - transport_init: Union[Type[MetricsServiceV2Transport], Callable[..., MetricsServiceV2Transport]] = ( + transport_init: Union[ + Type[MetricsServiceV2Transport], + Callable[..., MetricsServiceV2Transport], + ] = ( MetricsServiceV2Client.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., MetricsServiceV2Transport], transport) @@ -610,28 +709,37 @@ def __init__(self, *, ) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.logging_v2.MetricsServiceV2Client`.", - extra = { + extra={ "serviceName": "google.logging.v2.MetricsServiceV2", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { "serviceName": "google.logging.v2.MetricsServiceV2", "credentialsType": None, - } + }, ) - def list_log_metrics(self, - request: Optional[Union[logging_metrics.ListLogMetricsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLogMetricsPager: + def list_log_metrics( + self, + request: Optional[Union[logging_metrics.ListLogMetricsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogMetricsPager: r"""Lists logs-based metrics. .. code-block:: python @@ -696,10 +804,14 @@ def sample_list_log_metrics(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -717,9 +829,7 @@ def sample_list_log_metrics(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -747,14 +857,15 @@ def sample_list_log_metrics(): # Done; return the response. return response - def get_log_metric(self, - request: Optional[Union[logging_metrics.GetLogMetricRequest, dict]] = None, - *, - metric_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_metrics.LogMetric: + def get_log_metric( + self, + request: Optional[Union[logging_metrics.GetLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: r"""Gets a logs-based metric. .. code-block:: python @@ -824,10 +935,14 @@ def sample_get_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [metric_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -845,9 +960,9 @@ def sample_get_log_metric(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("metric_name", request.metric_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("metric_name", request.metric_name),) + ), ) # Validate the universe domain. @@ -864,15 +979,16 @@ def sample_get_log_metric(): # Done; return the response. return response - def create_log_metric(self, - request: Optional[Union[logging_metrics.CreateLogMetricRequest, dict]] = None, - *, - parent: Optional[str] = None, - metric: Optional[logging_metrics.LogMetric] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_metrics.LogMetric: + def create_log_metric( + self, + request: Optional[Union[logging_metrics.CreateLogMetricRequest, dict]] = None, + *, + parent: Optional[str] = None, + metric: Optional[logging_metrics.LogMetric] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: r"""Creates a logs-based metric. .. code-block:: python @@ -958,10 +1074,14 @@ def sample_create_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, metric] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -981,9 +1101,7 @@ def sample_create_log_metric(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1000,15 +1118,16 @@ def sample_create_log_metric(): # Done; return the response. return response - def update_log_metric(self, - request: Optional[Union[logging_metrics.UpdateLogMetricRequest, dict]] = None, - *, - metric_name: Optional[str] = None, - metric: Optional[logging_metrics.LogMetric] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_metrics.LogMetric: + def update_log_metric( + self, + request: Optional[Union[logging_metrics.UpdateLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + metric: Optional[logging_metrics.LogMetric] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: r"""Creates or updates a logs-based metric. .. code-block:: python @@ -1093,10 +1212,14 @@ def sample_update_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [metric_name, metric] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1116,9 +1239,9 @@ def sample_update_log_metric(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("metric_name", request.metric_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("metric_name", request.metric_name),) + ), ) # Validate the universe domain. @@ -1135,14 +1258,15 @@ def sample_update_log_metric(): # Done; return the response. return response - def delete_log_metric(self, - request: Optional[Union[logging_metrics.DeleteLogMetricRequest, dict]] = None, - *, - metric_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_log_metric( + self, + request: Optional[Union[logging_metrics.DeleteLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a logs-based metric. .. code-block:: python @@ -1193,10 +1317,14 @@ def sample_delete_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [metric_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1214,9 +1342,9 @@ def sample_delete_log_metric(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("metric_name", request.metric_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("metric_name", request.metric_name),) + ), ) # Validate the universe domain. @@ -1285,8 +1413,7 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1295,7 +1422,11 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1345,8 +1476,7 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1355,7 +1485,11 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1408,27 +1542,26 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - - - - + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "MetricsServiceV2Client", -) +__all__ = ("MetricsServiceV2Client",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py index 61d6698cc33a..285fcc1f7017 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py @@ -24,14 +24,16 @@ from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf from google.cloud.logging_v2.types import logging_metrics -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ @@ -41,27 +43,28 @@ class MetricsServiceV2Transport(abc.ABC): """Abstract transport class for MetricsServiceV2.""" AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write', + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/logging.admin", + "https://www.googleapis.com/auth/logging.read", + "https://www.googleapis.com/auth/logging.write", ) - DEFAULT_HOST: str = 'logging.googleapis.com' + DEFAULT_HOST: str = "logging.googleapis.com" def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -100,31 +103,43 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host self._wrapped_methods: Dict[Callable, Callable] = {} @@ -220,60 +235,63 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @property - def list_log_metrics(self) -> Callable[ - [logging_metrics.ListLogMetricsRequest], - Union[ - logging_metrics.ListLogMetricsResponse, - Awaitable[logging_metrics.ListLogMetricsResponse] - ]]: + def list_log_metrics( + self, + ) -> Callable[ + [logging_metrics.ListLogMetricsRequest], + Union[ + logging_metrics.ListLogMetricsResponse, + Awaitable[logging_metrics.ListLogMetricsResponse], + ], + ]: raise NotImplementedError() @property - def get_log_metric(self) -> Callable[ - [logging_metrics.GetLogMetricRequest], - Union[ - logging_metrics.LogMetric, - Awaitable[logging_metrics.LogMetric] - ]]: + def get_log_metric( + self, + ) -> Callable[ + [logging_metrics.GetLogMetricRequest], + Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]], + ]: raise NotImplementedError() @property - def create_log_metric(self) -> Callable[ - [logging_metrics.CreateLogMetricRequest], - Union[ - logging_metrics.LogMetric, - Awaitable[logging_metrics.LogMetric] - ]]: + def create_log_metric( + self, + ) -> Callable[ + [logging_metrics.CreateLogMetricRequest], + Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]], + ]: raise NotImplementedError() @property - def update_log_metric(self) -> Callable[ - [logging_metrics.UpdateLogMetricRequest], - Union[ - logging_metrics.LogMetric, - Awaitable[logging_metrics.LogMetric] - ]]: + def update_log_metric( + self, + ) -> Callable[ + [logging_metrics.UpdateLogMetricRequest], + Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]], + ]: raise NotImplementedError() @property - def delete_log_metric(self) -> Callable[ - [logging_metrics.DeleteLogMetricRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_log_metric( + self, + ) -> Callable[ + [logging_metrics.DeleteLogMetricRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property @@ -281,7 +299,10 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], ]: raise NotImplementedError() @@ -297,10 +318,7 @@ def get_operation( @property def cancel_operation( self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: raise NotImplementedError() @property @@ -308,6 +326,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'MetricsServiceV2Transport', -) +__all__ = ("MetricsServiceV2Transport",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/setup.py b/packages/gapic-generator/tests/integration/goldens/logging/setup.py index 0c230d719cdd..b2cf12496bc3 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/setup.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/setup.py @@ -17,23 +17,23 @@ import os import re -import setuptools # type: ignore +import setuptools # type: ignore package_root = os.path.abspath(os.path.dirname(__file__)) -name = 'google-cloud-logging' +name = "google-cloud-logging" description = "Google Cloud Logging API client library" version = None -with open(os.path.join(package_root, 'google/cloud/logging/gapic_version.py')) as fp: +with open(os.path.join(package_root, "google/cloud/logging/gapic_version.py")) as fp: version_candidates = re.findall( r"(?<=\")\d+\.\d+\.\d+[^\"\s]*(?=\")", fp.read(), ) - assert (len(version_candidates) == 1) + assert len(version_candidates) == 1 version = version_candidates[0] if version[0] == "0": @@ -51,8 +51,7 @@ "proto-plus >= 1.26.1, <2.0.0", "protobuf >= 6.33.5, < 8.0.0", ] -extras = { -} +extras = {} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-logging" package_root = os.path.abspath(os.path.dirname(__file__)) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/__init__.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/__init__.py index 0469de869617..99324c541da2 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/__init__.py @@ -107,10 +107,12 @@ from .types.logging_metrics import LogMetric from .types.logging_metrics import UpdateLogMetricRequest -if hasattr(api_core, "check_python_version") and hasattr(api_core, "check_dependency_versions"): # pragma: NO COVER - api_core.check_python_version("google.cloud.logging_v2") # type: ignore - api_core.check_dependency_versions("google.cloud.logging_v2") # type: ignore -else: # pragma: NO COVER +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.cloud.logging_v2") # type: ignore + api_core.check_dependency_versions("google.cloud.logging_v2") # type: ignore +else: # pragma: NO COVER # An older version of api_core is installed which does not define the # functions above. We do equivalent checks manually. try: @@ -119,12 +121,14 @@ _py_version_str = sys.version.split()[0] _package_label = "google.cloud.logging_v2" if sys.version_info < (3, 10): - warnings.warn("You are using a non-supported Python version " + - f"({_py_version_str}). Google will not post any further " + - f"updates to {_package_label} supporting this Python version. " + - "Please upgrade to the latest Python version, or at " + - f"least to Python 3.10, and then update {_package_label}.", - FutureWarning) + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.10, and then update {_package_label}.", + FutureWarning, + ) def parse_version_to_tuple(version_string: str): """Safely converts a semantic version string to a comparable tuple of integers. @@ -162,107 +166,111 @@ def _get_version(dependency_name): _recommendation = " (we recommend 7.x)" (_version_used, _version_used_string) = _get_version(_dependency_package) if _version_used and _version_used < _next_supported_version_tuple: - warnings.warn(f"Package {_package_label} depends on " + - f"{_dependency_package}, currently installed at version " + - f"{_version_used_string}. Future updates to " + - f"{_package_label} will require {_dependency_package} at " + - f"version {_next_supported_version} or higher{_recommendation}." + - " Please ensure " + - "that either (a) your Python environment doesn't pin the " + - f"version of {_dependency_package}, so that updates to " + - f"{_package_label} can require the higher version, or " + - "(b) you manually update your Python environment to use at " + - f"least version {_next_supported_version} of " + - f"{_dependency_package}.", - FutureWarning) + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) except Exception: - warnings.warn("Could not determine the version of Python " + - "currently being used. To continue receiving " + - "updates for {_package_label}, ensure you are " + - "using a supported version of Python; see " + - "https://devguide.python.org/versions/") + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) __all__ = ( - 'BaseConfigServiceV2AsyncClient', - 'BaseMetricsServiceV2AsyncClient', - 'LoggingServiceV2AsyncClient', -'BaseConfigServiceV2Client', -'BaseMetricsServiceV2Client', -'BigQueryDataset', -'BigQueryOptions', -'BucketMetadata', -'CmekSettings', -'CopyLogEntriesMetadata', -'CopyLogEntriesRequest', -'CopyLogEntriesResponse', -'CreateBucketRequest', -'CreateExclusionRequest', -'CreateLinkRequest', -'CreateLogMetricRequest', -'CreateSinkRequest', -'CreateViewRequest', -'DeleteBucketRequest', -'DeleteExclusionRequest', -'DeleteLinkRequest', -'DeleteLogMetricRequest', -'DeleteLogRequest', -'DeleteSinkRequest', -'DeleteViewRequest', -'GetBucketRequest', -'GetCmekSettingsRequest', -'GetExclusionRequest', -'GetLinkRequest', -'GetLogMetricRequest', -'GetSettingsRequest', -'GetSinkRequest', -'GetViewRequest', -'IndexConfig', -'IndexType', -'LifecycleState', -'Link', -'LinkMetadata', -'ListBucketsRequest', -'ListBucketsResponse', -'ListExclusionsRequest', -'ListExclusionsResponse', -'ListLinksRequest', -'ListLinksResponse', -'ListLogEntriesRequest', -'ListLogEntriesResponse', -'ListLogMetricsRequest', -'ListLogMetricsResponse', -'ListLogsRequest', -'ListLogsResponse', -'ListMonitoredResourceDescriptorsRequest', -'ListMonitoredResourceDescriptorsResponse', -'ListSinksRequest', -'ListSinksResponse', -'ListViewsRequest', -'ListViewsResponse', -'LocationMetadata', -'LogBucket', -'LogEntry', -'LogEntryOperation', -'LogEntrySourceLocation', -'LogExclusion', -'LogMetric', -'LogSink', -'LogSplit', -'LogView', -'LoggingServiceV2Client', -'OperationState', -'Settings', -'TailLogEntriesRequest', -'TailLogEntriesResponse', -'UndeleteBucketRequest', -'UpdateBucketRequest', -'UpdateCmekSettingsRequest', -'UpdateExclusionRequest', -'UpdateLogMetricRequest', -'UpdateSettingsRequest', -'UpdateSinkRequest', -'UpdateViewRequest', -'WriteLogEntriesPartialErrors', -'WriteLogEntriesRequest', -'WriteLogEntriesResponse', + "BaseConfigServiceV2AsyncClient", + "BaseMetricsServiceV2AsyncClient", + "LoggingServiceV2AsyncClient", + "BaseConfigServiceV2Client", + "BaseMetricsServiceV2Client", + "BigQueryDataset", + "BigQueryOptions", + "BucketMetadata", + "CmekSettings", + "CopyLogEntriesMetadata", + "CopyLogEntriesRequest", + "CopyLogEntriesResponse", + "CreateBucketRequest", + "CreateExclusionRequest", + "CreateLinkRequest", + "CreateLogMetricRequest", + "CreateSinkRequest", + "CreateViewRequest", + "DeleteBucketRequest", + "DeleteExclusionRequest", + "DeleteLinkRequest", + "DeleteLogMetricRequest", + "DeleteLogRequest", + "DeleteSinkRequest", + "DeleteViewRequest", + "GetBucketRequest", + "GetCmekSettingsRequest", + "GetExclusionRequest", + "GetLinkRequest", + "GetLogMetricRequest", + "GetSettingsRequest", + "GetSinkRequest", + "GetViewRequest", + "IndexConfig", + "IndexType", + "LifecycleState", + "Link", + "LinkMetadata", + "ListBucketsRequest", + "ListBucketsResponse", + "ListExclusionsRequest", + "ListExclusionsResponse", + "ListLinksRequest", + "ListLinksResponse", + "ListLogEntriesRequest", + "ListLogEntriesResponse", + "ListLogMetricsRequest", + "ListLogMetricsResponse", + "ListLogsRequest", + "ListLogsResponse", + "ListMonitoredResourceDescriptorsRequest", + "ListMonitoredResourceDescriptorsResponse", + "ListSinksRequest", + "ListSinksResponse", + "ListViewsRequest", + "ListViewsResponse", + "LocationMetadata", + "LogBucket", + "LogEntry", + "LogEntryOperation", + "LogEntrySourceLocation", + "LogExclusion", + "LogMetric", + "LogSink", + "LogSplit", + "LogView", + "LoggingServiceV2Client", + "OperationState", + "Settings", + "TailLogEntriesRequest", + "TailLogEntriesResponse", + "UndeleteBucketRequest", + "UpdateBucketRequest", + "UpdateCmekSettingsRequest", + "UpdateExclusionRequest", + "UpdateLogMetricRequest", + "UpdateSettingsRequest", + "UpdateSinkRequest", + "UpdateViewRequest", + "WriteLogEntriesPartialErrors", + "WriteLogEntriesRequest", + "WriteLogEntriesResponse", ) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/async_client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/async_client.py index ac2b59369b2d..ef9930922946 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/async_client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/async_client.py @@ -16,7 +16,18 @@ import logging as std_logging from collections import OrderedDict import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union +from typing import ( + Dict, + Callable, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) from google.cloud.logging_v2 import gapic_version as package_version @@ -24,8 +35,8 @@ from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf @@ -36,7 +47,7 @@ from google.cloud.logging_v2.services.config_service_v2 import pagers from google.cloud.logging_v2.types import logging_config -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.api_core.operation as operation # type: ignore import google.api_core.operation_async as operation_async # type: ignore import google.protobuf.empty_pb2 as empty_pb2 # type: ignore @@ -48,12 +59,14 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) + class BaseConfigServiceV2AsyncClient: """Service for configuring sinks used to route log entries.""" @@ -67,29 +80,49 @@ class BaseConfigServiceV2AsyncClient: _DEFAULT_UNIVERSE = BaseConfigServiceV2Client._DEFAULT_UNIVERSE cmek_settings_path = staticmethod(BaseConfigServiceV2Client.cmek_settings_path) - parse_cmek_settings_path = staticmethod(BaseConfigServiceV2Client.parse_cmek_settings_path) + parse_cmek_settings_path = staticmethod( + BaseConfigServiceV2Client.parse_cmek_settings_path + ) link_path = staticmethod(BaseConfigServiceV2Client.link_path) parse_link_path = staticmethod(BaseConfigServiceV2Client.parse_link_path) log_bucket_path = staticmethod(BaseConfigServiceV2Client.log_bucket_path) - parse_log_bucket_path = staticmethod(BaseConfigServiceV2Client.parse_log_bucket_path) + parse_log_bucket_path = staticmethod( + BaseConfigServiceV2Client.parse_log_bucket_path + ) log_exclusion_path = staticmethod(BaseConfigServiceV2Client.log_exclusion_path) - parse_log_exclusion_path = staticmethod(BaseConfigServiceV2Client.parse_log_exclusion_path) + parse_log_exclusion_path = staticmethod( + BaseConfigServiceV2Client.parse_log_exclusion_path + ) log_sink_path = staticmethod(BaseConfigServiceV2Client.log_sink_path) parse_log_sink_path = staticmethod(BaseConfigServiceV2Client.parse_log_sink_path) log_view_path = staticmethod(BaseConfigServiceV2Client.log_view_path) parse_log_view_path = staticmethod(BaseConfigServiceV2Client.parse_log_view_path) settings_path = staticmethod(BaseConfigServiceV2Client.settings_path) parse_settings_path = staticmethod(BaseConfigServiceV2Client.parse_settings_path) - common_billing_account_path = staticmethod(BaseConfigServiceV2Client.common_billing_account_path) - parse_common_billing_account_path = staticmethod(BaseConfigServiceV2Client.parse_common_billing_account_path) + common_billing_account_path = staticmethod( + BaseConfigServiceV2Client.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + BaseConfigServiceV2Client.parse_common_billing_account_path + ) common_folder_path = staticmethod(BaseConfigServiceV2Client.common_folder_path) - parse_common_folder_path = staticmethod(BaseConfigServiceV2Client.parse_common_folder_path) - common_organization_path = staticmethod(BaseConfigServiceV2Client.common_organization_path) - parse_common_organization_path = staticmethod(BaseConfigServiceV2Client.parse_common_organization_path) + parse_common_folder_path = staticmethod( + BaseConfigServiceV2Client.parse_common_folder_path + ) + common_organization_path = staticmethod( + BaseConfigServiceV2Client.common_organization_path + ) + parse_common_organization_path = staticmethod( + BaseConfigServiceV2Client.parse_common_organization_path + ) common_project_path = staticmethod(BaseConfigServiceV2Client.common_project_path) - parse_common_project_path = staticmethod(BaseConfigServiceV2Client.parse_common_project_path) + parse_common_project_path = staticmethod( + BaseConfigServiceV2Client.parse_common_project_path + ) common_location_path = staticmethod(BaseConfigServiceV2Client.common_location_path) - parse_common_location_path = staticmethod(BaseConfigServiceV2Client.parse_common_location_path) + parse_common_location_path = staticmethod( + BaseConfigServiceV2Client.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -131,7 +164,9 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): """Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -194,12 +229,18 @@ def universe_domain(self) -> str: get_transport_class = BaseConfigServiceV2Client.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ConfigServiceV2Transport, Callable[..., ConfigServiceV2Transport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, ConfigServiceV2Transport, Callable[..., ConfigServiceV2Transport] + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the base config service v2 async client. Args: @@ -254,31 +295,39 @@ def __init__(self, *, transport=transport, client_options=client_options, client_info=client_info, - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.logging_v2.BaseConfigServiceV2AsyncClient`.", - extra = { + extra={ "serviceName": "google.logging.v2.ConfigServiceV2", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { "serviceName": "google.logging.v2.ConfigServiceV2", "credentialsType": None, - } + }, ) - async def list_buckets(self, - request: Optional[Union[logging_config.ListBucketsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListBucketsAsyncPager: + async def list_buckets( + self, + request: Optional[Union[logging_config.ListBucketsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBucketsAsyncPager: r"""Lists log buckets. .. code-block:: python @@ -350,10 +399,14 @@ async def sample_list_buckets(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -367,14 +420,14 @@ async def sample_list_buckets(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_buckets] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_buckets + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -402,13 +455,14 @@ async def sample_list_buckets(): # Done; return the response. return response - async def get_bucket(self, - request: Optional[Union[logging_config.GetBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogBucket: + async def get_bucket( + self, + request: Optional[Union[logging_config.GetBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: r"""Gets a log bucket. .. code-block:: python @@ -462,14 +516,14 @@ async def sample_get_bucket(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_bucket] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_bucket + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -486,13 +540,14 @@ async def sample_get_bucket(): # Done; return the response. return response - async def create_bucket_async(self, - request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def create_bucket_async( + self, + request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Creates a log bucket asynchronously that can be used to store log entries. After a bucket has been created, the bucket's location @@ -557,14 +612,14 @@ async def sample_create_bucket_async(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_bucket_async] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_bucket_async + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -589,13 +644,14 @@ async def sample_create_bucket_async(): # Done; return the response. return response - async def update_bucket_async(self, - request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def update_bucket_async( + self, + request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Updates a log bucket asynchronously. If the bucket has a ``lifecycle_state`` of ``DELETE_REQUESTED``, @@ -662,14 +718,14 @@ async def sample_update_bucket_async(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_bucket_async] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_bucket_async + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -694,13 +750,14 @@ async def sample_update_bucket_async(): # Done; return the response. return response - async def create_bucket(self, - request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogBucket: + async def create_bucket( + self, + request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: r"""Creates a log bucket that can be used to store log entries. After a bucket has been created, the bucket's location cannot be changed. @@ -757,14 +814,14 @@ async def sample_create_bucket(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_bucket] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_bucket + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -781,13 +838,14 @@ async def sample_create_bucket(): # Done; return the response. return response - async def update_bucket(self, - request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogBucket: + async def update_bucket( + self, + request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: r"""Updates a log bucket. If the bucket has a ``lifecycle_state`` of ``DELETE_REQUESTED``, @@ -847,14 +905,14 @@ async def sample_update_bucket(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_bucket] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_bucket + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -871,13 +929,14 @@ async def sample_update_bucket(): # Done; return the response. return response - async def delete_bucket(self, - request: Optional[Union[logging_config.DeleteBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def delete_bucket( + self, + request: Optional[Union[logging_config.DeleteBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a log bucket. Changes the bucket's ``lifecycle_state`` to the @@ -927,14 +986,14 @@ async def sample_delete_bucket(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_bucket] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_bucket + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -948,13 +1007,14 @@ async def sample_delete_bucket(): metadata=metadata, ) - async def undelete_bucket(self, - request: Optional[Union[logging_config.UndeleteBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def undelete_bucket( + self, + request: Optional[Union[logging_config.UndeleteBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Undeletes a log bucket. A bucket that has been deleted can be undeleted within the grace period of 7 days. @@ -1001,14 +1061,14 @@ async def sample_undelete_bucket(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.undelete_bucket] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.undelete_bucket + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1022,14 +1082,15 @@ async def sample_undelete_bucket(): metadata=metadata, ) - async def _list_views(self, - request: Optional[Union[logging_config.ListViewsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListViewsAsyncPager: + async def _list_views( + self, + request: Optional[Union[logging_config.ListViewsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListViewsAsyncPager: r"""Lists views on a log bucket. .. code-block:: python @@ -1093,10 +1154,14 @@ async def sample_list_views(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1110,14 +1175,14 @@ async def sample_list_views(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_views] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_views + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1145,13 +1210,14 @@ async def sample_list_views(): # Done; return the response. return response - async def _get_view(self, - request: Optional[Union[logging_config.GetViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogView: + async def _get_view( + self, + request: Optional[Union[logging_config.GetViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: r"""Gets a view on a log bucket.. .. code-block:: python @@ -1210,9 +1276,7 @@ async def sample_get_view(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1229,13 +1293,14 @@ async def sample_get_view(): # Done; return the response. return response - async def _create_view(self, - request: Optional[Union[logging_config.CreateViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogView: + async def _create_view( + self, + request: Optional[Union[logging_config.CreateViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: r"""Creates a view over log entries in a log bucket. A bucket may contain a maximum of 30 views. @@ -1291,14 +1356,14 @@ async def sample_create_view(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_view] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_view + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1315,13 +1380,14 @@ async def sample_create_view(): # Done; return the response. return response - async def _update_view(self, - request: Optional[Union[logging_config.UpdateViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogView: + async def _update_view( + self, + request: Optional[Union[logging_config.UpdateViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: r"""Updates a view on a log bucket. This method replaces the following fields in the existing view with values from the new view: ``filter``. If an ``UNAVAILABLE`` error is returned, this @@ -1379,14 +1445,14 @@ async def sample_update_view(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_view] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_view + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1403,13 +1469,14 @@ async def sample_update_view(): # Done; return the response. return response - async def _delete_view(self, - request: Optional[Union[logging_config.DeleteViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def _delete_view( + self, + request: Optional[Union[logging_config.DeleteViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a view on a log bucket. If an ``UNAVAILABLE`` error is returned, this indicates that system is not in a state where it can delete the view. If this occurs, please try again in a few @@ -1457,14 +1524,14 @@ async def sample_delete_view(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_view] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_view + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1478,14 +1545,15 @@ async def sample_delete_view(): metadata=metadata, ) - async def _list_sinks(self, - request: Optional[Union[logging_config.ListSinksRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListSinksAsyncPager: + async def _list_sinks( + self, + request: Optional[Union[logging_config.ListSinksRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSinksAsyncPager: r"""Lists sinks. .. code-block:: python @@ -1552,10 +1620,14 @@ async def sample_list_sinks(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1569,14 +1641,14 @@ async def sample_list_sinks(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_sinks] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_sinks + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1604,14 +1676,15 @@ async def sample_list_sinks(): # Done; return the response. return response - async def _get_sink(self, - request: Optional[Union[logging_config.GetSinkRequest, dict]] = None, - *, - sink_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogSink: + async def _get_sink( + self, + request: Optional[Union[logging_config.GetSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: r"""Gets a sink. .. code-block:: python @@ -1685,10 +1758,14 @@ async def sample_get_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [sink_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1707,9 +1784,9 @@ async def sample_get_sink(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("sink_name", request.sink_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("sink_name", request.sink_name),) + ), ) # Validate the universe domain. @@ -1726,15 +1803,16 @@ async def sample_get_sink(): # Done; return the response. return response - async def _create_sink(self, - request: Optional[Union[logging_config.CreateSinkRequest, dict]] = None, - *, - parent: Optional[str] = None, - sink: Optional[logging_config.LogSink] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogSink: + async def _create_sink( + self, + request: Optional[Union[logging_config.CreateSinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + sink: Optional[logging_config.LogSink] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: r"""Creates a sink that exports specified log entries to a destination. The export of newly-ingested log entries begins immediately, unless the sink's ``writer_identity`` is not @@ -1824,10 +1902,14 @@ async def sample_create_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, sink] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1843,14 +1925,14 @@ async def sample_create_sink(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_sink] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_sink + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1867,16 +1949,17 @@ async def sample_create_sink(): # Done; return the response. return response - async def _update_sink(self, - request: Optional[Union[logging_config.UpdateSinkRequest, dict]] = None, - *, - sink_name: Optional[str] = None, - sink: Optional[logging_config.LogSink] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogSink: + async def _update_sink( + self, + request: Optional[Union[logging_config.UpdateSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + sink: Optional[logging_config.LogSink] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: r"""Updates a sink. This method replaces the following fields in the existing sink with values from the new sink: ``destination``, and ``filter``. @@ -1990,10 +2073,14 @@ async def sample_update_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [sink_name, sink, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2011,14 +2098,16 @@ async def sample_update_sink(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_sink] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_sink + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("sink_name", request.sink_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("sink_name", request.sink_name),) + ), ) # Validate the universe domain. @@ -2035,14 +2124,15 @@ async def sample_update_sink(): # Done; return the response. return response - async def _delete_sink(self, - request: Optional[Union[logging_config.DeleteSinkRequest, dict]] = None, - *, - sink_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def _delete_sink( + self, + request: Optional[Union[logging_config.DeleteSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a sink. If the sink has a unique ``writer_identity``, then that service account is also deleted. @@ -2102,10 +2192,14 @@ async def sample_delete_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [sink_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2119,14 +2213,16 @@ async def sample_delete_sink(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_sink] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_sink + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("sink_name", request.sink_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("sink_name", request.sink_name),) + ), ) # Validate the universe domain. @@ -2140,16 +2236,17 @@ async def sample_delete_sink(): metadata=metadata, ) - async def _create_link(self, - request: Optional[Union[logging_config.CreateLinkRequest, dict]] = None, - *, - parent: Optional[str] = None, - link: Optional[logging_config.Link] = None, - link_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def _create_link( + self, + request: Optional[Union[logging_config.CreateLinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + link: Optional[logging_config.Link] = None, + link_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Asynchronously creates a linked dataset in BigQuery which makes it possible to use BigQuery to read the logs stored in the log bucket. A log bucket may currently @@ -2237,10 +2334,14 @@ async def sample_create_link(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, link, link_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2258,14 +2359,14 @@ async def sample_create_link(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_link] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_link + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2290,14 +2391,15 @@ async def sample_create_link(): # Done; return the response. return response - async def _delete_link(self, - request: Optional[Union[logging_config.DeleteLinkRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def _delete_link( + self, + request: Optional[Union[logging_config.DeleteLinkRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Deletes a link. This will also delete the corresponding BigQuery linked dataset. @@ -2373,10 +2475,14 @@ async def sample_delete_link(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2390,14 +2496,14 @@ async def sample_delete_link(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_link] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_link + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2422,14 +2528,15 @@ async def sample_delete_link(): # Done; return the response. return response - async def _list_links(self, - request: Optional[Union[logging_config.ListLinksRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLinksAsyncPager: + async def _list_links( + self, + request: Optional[Union[logging_config.ListLinksRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLinksAsyncPager: r"""Lists links. .. code-block:: python @@ -2495,10 +2602,14 @@ async def sample_list_links(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2512,14 +2623,14 @@ async def sample_list_links(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_links] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_links + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2547,14 +2658,15 @@ async def sample_list_links(): # Done; return the response. return response - async def _get_link(self, - request: Optional[Union[logging_config.GetLinkRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.Link: + async def _get_link( + self, + request: Optional[Union[logging_config.GetLinkRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Link: r"""Gets a link. .. code-block:: python @@ -2615,10 +2727,14 @@ async def sample_get_link(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2637,9 +2753,7 @@ async def sample_get_link(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2656,14 +2770,15 @@ async def sample_get_link(): # Done; return the response. return response - async def _list_exclusions(self, - request: Optional[Union[logging_config.ListExclusionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListExclusionsAsyncPager: + async def _list_exclusions( + self, + request: Optional[Union[logging_config.ListExclusionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListExclusionsAsyncPager: r"""Lists all the exclusions on the \_Default sink in a parent resource. @@ -2731,10 +2846,14 @@ async def sample_list_exclusions(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2748,14 +2867,14 @@ async def sample_list_exclusions(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_exclusions] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_exclusions + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2783,14 +2902,15 @@ async def sample_list_exclusions(): # Done; return the response. return response - async def _get_exclusion(self, - request: Optional[Union[logging_config.GetExclusionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogExclusion: + async def _get_exclusion( + self, + request: Optional[Union[logging_config.GetExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: r"""Gets the description of an exclusion in the \_Default sink. .. code-block:: python @@ -2862,10 +2982,14 @@ async def sample_get_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2879,14 +3003,14 @@ async def sample_get_exclusion(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_exclusion] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_exclusion + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2903,15 +3027,16 @@ async def sample_get_exclusion(): # Done; return the response. return response - async def _create_exclusion(self, - request: Optional[Union[logging_config.CreateExclusionRequest, dict]] = None, - *, - parent: Optional[str] = None, - exclusion: Optional[logging_config.LogExclusion] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogExclusion: + async def _create_exclusion( + self, + request: Optional[Union[logging_config.CreateExclusionRequest, dict]] = None, + *, + parent: Optional[str] = None, + exclusion: Optional[logging_config.LogExclusion] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: r"""Creates a new exclusion in the \_Default sink in a specified parent resource. Only log entries belonging to that resource can be excluded. You can have up to 10 exclusions in a resource. @@ -3000,10 +3125,14 @@ async def sample_create_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, exclusion] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3019,14 +3148,14 @@ async def sample_create_exclusion(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_exclusion] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_exclusion + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -3043,16 +3172,17 @@ async def sample_create_exclusion(): # Done; return the response. return response - async def _update_exclusion(self, - request: Optional[Union[logging_config.UpdateExclusionRequest, dict]] = None, - *, - name: Optional[str] = None, - exclusion: Optional[logging_config.LogExclusion] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogExclusion: + async def _update_exclusion( + self, + request: Optional[Union[logging_config.UpdateExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + exclusion: Optional[logging_config.LogExclusion] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: r"""Changes one or more properties of an existing exclusion in the \_Default sink. @@ -3152,10 +3282,14 @@ async def sample_update_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, exclusion, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3173,14 +3307,14 @@ async def sample_update_exclusion(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_exclusion] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_exclusion + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3197,14 +3331,15 @@ async def sample_update_exclusion(): # Done; return the response. return response - async def _delete_exclusion(self, - request: Optional[Union[logging_config.DeleteExclusionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def _delete_exclusion( + self, + request: Optional[Union[logging_config.DeleteExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes an exclusion in the \_Default sink. .. code-block:: python @@ -3263,10 +3398,14 @@ async def sample_delete_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3280,14 +3419,14 @@ async def sample_delete_exclusion(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_exclusion] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_exclusion + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3301,13 +3440,14 @@ async def sample_delete_exclusion(): metadata=metadata, ) - async def _get_cmek_settings(self, - request: Optional[Union[logging_config.GetCmekSettingsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.CmekSettings: + async def _get_cmek_settings( + self, + request: Optional[Union[logging_config.GetCmekSettingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.CmekSettings: r"""Gets the Logging CMEK settings for the given resource. Note: CMEK for the Log Router can be configured for Google Cloud @@ -3385,14 +3525,14 @@ async def sample_get_cmek_settings(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_cmek_settings] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_cmek_settings + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3409,13 +3549,14 @@ async def sample_get_cmek_settings(): # Done; return the response. return response - async def _update_cmek_settings(self, - request: Optional[Union[logging_config.UpdateCmekSettingsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.CmekSettings: + async def _update_cmek_settings( + self, + request: Optional[Union[logging_config.UpdateCmekSettingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.CmekSettings: r"""Updates the Log Router CMEK settings for the given resource. Note: CMEK for the Log Router can currently only be configured @@ -3498,14 +3639,14 @@ async def sample_update_cmek_settings(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_cmek_settings] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_cmek_settings + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3522,14 +3663,15 @@ async def sample_update_cmek_settings(): # Done; return the response. return response - async def _get_settings(self, - request: Optional[Union[logging_config.GetSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.Settings: + async def _get_settings( + self, + request: Optional[Union[logging_config.GetSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Settings: r"""Gets the Log Router settings for the given resource. Note: Settings for the Log Router can be get for Google Cloud @@ -3619,10 +3761,14 @@ async def sample_get_settings(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3636,14 +3782,14 @@ async def sample_get_settings(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_settings] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_settings + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3660,15 +3806,16 @@ async def sample_get_settings(): # Done; return the response. return response - async def _update_settings(self, - request: Optional[Union[logging_config.UpdateSettingsRequest, dict]] = None, - *, - settings: Optional[logging_config.Settings] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.Settings: + async def _update_settings( + self, + request: Optional[Union[logging_config.UpdateSettingsRequest, dict]] = None, + *, + settings: Optional[logging_config.Settings] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Settings: r"""Updates the Log Router settings for the given resource. Note: Settings for the Log Router can currently only be @@ -3765,10 +3912,14 @@ async def sample_update_settings(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [settings, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3784,14 +3935,14 @@ async def sample_update_settings(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_settings] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_settings + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3808,13 +3959,14 @@ async def sample_update_settings(): # Done; return the response. return response - async def _copy_log_entries(self, - request: Optional[Union[logging_config.CopyLogEntriesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def _copy_log_entries( + self, + request: Optional[Union[logging_config.CopyLogEntriesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Copies a set of log entries from a log bucket to a Cloud Storage bucket. @@ -3878,7 +4030,9 @@ async def sample_copy_log_entries(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.copy_log_entries] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.copy_log_entries + ] # Validate the universe domain. self._client._validate_universe_domain() @@ -3944,8 +4098,7 @@ async def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -3953,7 +4106,11 @@ async def list_operations( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -4000,8 +4157,7 @@ async def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -4009,7 +4165,11 @@ async def get_operation( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -4059,15 +4219,19 @@ async def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) async def __aenter__(self) -> "BaseConfigServiceV2AsyncClient": return self @@ -4075,12 +4239,13 @@ async def __aenter__(self) -> "BaseConfigServiceV2AsyncClient": async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "BaseConfigServiceV2AsyncClient", -) +__all__ = ("BaseConfigServiceV2AsyncClient",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py index dfa65cd87fe7..dd30515ded7c 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py @@ -19,7 +19,19 @@ import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +from typing import ( + Dict, + Callable, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) import warnings from google.cloud.logging_v2 import gapic_version as package_version @@ -28,11 +40,11 @@ from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.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.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 import google.protobuf try: @@ -42,6 +54,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -50,7 +63,7 @@ from google.cloud.logging_v2.services.config_service_v2 import pagers from google.cloud.logging_v2.types import logging_config -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.api_core.operation as operation # type: ignore import google.api_core.operation_async as operation_async # type: ignore import google.protobuf.empty_pb2 as empty_pb2 # type: ignore @@ -68,13 +81,17 @@ class BaseConfigServiceV2ClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[ConfigServiceV2Transport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[ConfigServiceV2Transport]] _transport_registry["grpc"] = ConfigServiceV2GrpcTransport _transport_registry["grpc_asyncio"] = ConfigServiceV2GrpcAsyncIOTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ConfigServiceV2Transport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[ConfigServiceV2Transport]: """Returns an appropriate transport class. Args: @@ -150,14 +167,16 @@ def _use_client_cert_effective(): bool: whether client certificate should be used for mTLS Raises: ValueError: (If using a version of google-auth without should_use_client_cert and - GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) """ # check if google-auth version supports should_use_client_cert for automatic mTLS enablement if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER return mtls.should_use_client_cert() - else: # pragma: NO COVER + else: # pragma: NO COVER # if unsupported, fallback to reading from env var - use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() if use_client_cert_str not in ("true", "false"): raise ValueError( "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" @@ -196,8 +215,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: BaseConfigServiceV2Client: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -214,139 +232,220 @@ def transport(self) -> ConfigServiceV2Transport: return self._transport @staticmethod - def cmek_settings_path(project: str,) -> str: + def cmek_settings_path( + project: str, + ) -> str: """Returns a fully-qualified cmek_settings string.""" - return "projects/{project}/cmekSettings".format(project=project, ) + return "projects/{project}/cmekSettings".format( + project=project, + ) @staticmethod - def parse_cmek_settings_path(path: str) -> Dict[str,str]: + def parse_cmek_settings_path(path: str) -> Dict[str, str]: """Parses a cmek_settings path into its component segments.""" m = re.match(r"^projects/(?P.+?)/cmekSettings$", path) return m.groupdict() if m else {} @staticmethod - def link_path(project: str,location: str,bucket: str,link: str,) -> str: + def link_path( + project: str, + location: str, + bucket: str, + link: str, + ) -> str: """Returns a fully-qualified link string.""" - return "projects/{project}/locations/{location}/buckets/{bucket}/links/{link}".format(project=project, location=location, bucket=bucket, link=link, ) + return "projects/{project}/locations/{location}/buckets/{bucket}/links/{link}".format( + project=project, + location=location, + bucket=bucket, + link=link, + ) @staticmethod - def parse_link_path(path: str) -> Dict[str,str]: + def parse_link_path(path: str) -> Dict[str, str]: """Parses a link path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)/links/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)/links/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def log_bucket_path(project: str,location: str,bucket: str,) -> str: + def log_bucket_path( + project: str, + location: str, + bucket: str, + ) -> str: """Returns a fully-qualified log_bucket string.""" - return "projects/{project}/locations/{location}/buckets/{bucket}".format(project=project, location=location, bucket=bucket, ) + return "projects/{project}/locations/{location}/buckets/{bucket}".format( + project=project, + location=location, + bucket=bucket, + ) @staticmethod - def parse_log_bucket_path(path: str) -> Dict[str,str]: + def parse_log_bucket_path(path: str) -> Dict[str, str]: """Parses a log_bucket path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def log_exclusion_path(project: str,exclusion: str,) -> str: + def log_exclusion_path( + project: str, + exclusion: str, + ) -> str: """Returns a fully-qualified log_exclusion string.""" - return "projects/{project}/exclusions/{exclusion}".format(project=project, exclusion=exclusion, ) + return "projects/{project}/exclusions/{exclusion}".format( + project=project, + exclusion=exclusion, + ) @staticmethod - def parse_log_exclusion_path(path: str) -> Dict[str,str]: + def parse_log_exclusion_path(path: str) -> Dict[str, str]: """Parses a log_exclusion path into its component segments.""" m = re.match(r"^projects/(?P.+?)/exclusions/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def log_sink_path(project: str,sink: str,) -> str: + def log_sink_path( + project: str, + sink: str, + ) -> str: """Returns a fully-qualified log_sink string.""" - return "projects/{project}/sinks/{sink}".format(project=project, sink=sink, ) + return "projects/{project}/sinks/{sink}".format( + project=project, + sink=sink, + ) @staticmethod - def parse_log_sink_path(path: str) -> Dict[str,str]: + def parse_log_sink_path(path: str) -> Dict[str, str]: """Parses a log_sink path into its component segments.""" m = re.match(r"^projects/(?P.+?)/sinks/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def log_view_path(project: str,location: str,bucket: str,view: str,) -> str: + def log_view_path( + project: str, + location: str, + bucket: str, + view: str, + ) -> str: """Returns a fully-qualified log_view string.""" - return "projects/{project}/locations/{location}/buckets/{bucket}/views/{view}".format(project=project, location=location, bucket=bucket, view=view, ) + return "projects/{project}/locations/{location}/buckets/{bucket}/views/{view}".format( + project=project, + location=location, + bucket=bucket, + view=view, + ) @staticmethod - def parse_log_view_path(path: str) -> Dict[str,str]: + def parse_log_view_path(path: str) -> Dict[str, str]: """Parses a log_view path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)/views/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)/views/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def settings_path(project: str,) -> str: + def settings_path( + project: str, + ) -> str: """Returns a fully-qualified settings string.""" - return "projects/{project}/settings".format(project=project, ) + return "projects/{project}/settings".format( + project=project, + ) @staticmethod - def parse_settings_path(path: str) -> Dict[str,str]: + def parse_settings_path(path: str) -> Dict[str, str]: """Parses a settings path into its component segments.""" m = re.match(r"^projects/(?P.+?)/settings$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + def common_billing_account_path( + billing_account: str, + ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path(folder: str, ) -> str: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path(organization: str, ) -> str: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path(project: str, ) -> str: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path(project: str, location: str, ) -> str: + def common_location_path( + project: str, + location: str, + ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -378,14 +477,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = BaseConfigServiceV2Client._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Figure out the client cert source to use. client_cert_source = None @@ -398,7 +501,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): api_endpoint = cls.DEFAULT_MTLS_ENDPOINT else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -423,7 +528,9 @@ def _read_environment_variables(): use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod @@ -446,7 +553,9 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: """Return the API endpoint used by the client. Args: @@ -462,17 +571,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): _default_universe = BaseConfigServiceV2Client._DEFAULT_UNIVERSE if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) api_endpoint = BaseConfigServiceV2Client.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = BaseConfigServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = BaseConfigServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) return api_endpoint @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: """Return the universe domain used by the client. Args: @@ -508,15 +625,18 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError + self, error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: return cred = self._transport._credentials @@ -549,12 +669,18 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ConfigServiceV2Transport, Callable[..., ConfigServiceV2Transport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, ConfigServiceV2Transport, Callable[..., ConfigServiceV2Transport] + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the base config service v2 client. Args: @@ -609,13 +735,23 @@ def __init__(self, *, self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = BaseConfigServiceV2Client._read_environment_variables() - self._client_cert_source = BaseConfigServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = BaseConfigServiceV2Client._get_universe_domain(universe_domain_opt, self._universe_domain_env) + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = BaseConfigServiceV2Client._read_environment_variables() + self._client_cert_source = BaseConfigServiceV2Client._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = BaseConfigServiceV2Client._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -627,7 +763,9 @@ def __init__(self, *, api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -636,8 +774,10 @@ def __init__(self, *, if transport_provided: # transport is a ConfigServiceV2Transport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if self._client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes " @@ -646,20 +786,29 @@ def __init__(self, *, self._transport = cast(ConfigServiceV2Transport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - BaseConfigServiceV2Client._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or BaseConfigServiceV2Client._get_api_endpoint( self._client_options.api_endpoint, self._client_cert_source, self._universe_domain, - self._use_mtls_endpoint)) + self._use_mtls_endpoint, + ) + ) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) - transport_init: Union[Type[ConfigServiceV2Transport], Callable[..., ConfigServiceV2Transport]] = ( + transport_init: Union[ + Type[ConfigServiceV2Transport], Callable[..., ConfigServiceV2Transport] + ] = ( BaseConfigServiceV2Client.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., ConfigServiceV2Transport], transport) @@ -678,28 +827,37 @@ def __init__(self, *, ) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.logging_v2.BaseConfigServiceV2Client`.", - extra = { + extra={ "serviceName": "google.logging.v2.ConfigServiceV2", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { "serviceName": "google.logging.v2.ConfigServiceV2", "credentialsType": None, - } + }, ) - def list_buckets(self, - request: Optional[Union[logging_config.ListBucketsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListBucketsPager: + def list_buckets( + self, + request: Optional[Union[logging_config.ListBucketsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBucketsPager: r"""Lists log buckets. .. code-block:: python @@ -771,10 +929,14 @@ def sample_list_buckets(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -792,9 +954,7 @@ def sample_list_buckets(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -822,13 +982,14 @@ def sample_list_buckets(): # Done; return the response. return response - def get_bucket(self, - request: Optional[Union[logging_config.GetBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogBucket: + def get_bucket( + self, + request: Optional[Union[logging_config.GetBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: r"""Gets a log bucket. .. code-block:: python @@ -887,9 +1048,7 @@ def sample_get_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -906,13 +1065,14 @@ def sample_get_bucket(): # Done; return the response. return response - def create_bucket_async(self, - request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_bucket_async( + self, + request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Creates a log bucket asynchronously that can be used to store log entries. After a bucket has been created, the bucket's location @@ -982,9 +1142,7 @@ def sample_create_bucket_async(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1009,13 +1167,14 @@ def sample_create_bucket_async(): # Done; return the response. return response - def update_bucket_async(self, - request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_bucket_async( + self, + request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Updates a log bucket asynchronously. If the bucket has a ``lifecycle_state`` of ``DELETE_REQUESTED``, @@ -1087,9 +1246,7 @@ def sample_update_bucket_async(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1114,13 +1271,14 @@ def sample_update_bucket_async(): # Done; return the response. return response - def create_bucket(self, - request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogBucket: + def create_bucket( + self, + request: Optional[Union[logging_config.CreateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: r"""Creates a log bucket that can be used to store log entries. After a bucket has been created, the bucket's location cannot be changed. @@ -1182,9 +1340,7 @@ def sample_create_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1201,13 +1357,14 @@ def sample_create_bucket(): # Done; return the response. return response - def update_bucket(self, - request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogBucket: + def update_bucket( + self, + request: Optional[Union[logging_config.UpdateBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogBucket: r"""Updates a log bucket. If the bucket has a ``lifecycle_state`` of ``DELETE_REQUESTED``, @@ -1272,9 +1429,7 @@ def sample_update_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1291,13 +1446,14 @@ def sample_update_bucket(): # Done; return the response. return response - def delete_bucket(self, - request: Optional[Union[logging_config.DeleteBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_bucket( + self, + request: Optional[Union[logging_config.DeleteBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a log bucket. Changes the bucket's ``lifecycle_state`` to the @@ -1352,9 +1508,7 @@ def sample_delete_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1368,13 +1522,14 @@ def sample_delete_bucket(): metadata=metadata, ) - def undelete_bucket(self, - request: Optional[Union[logging_config.UndeleteBucketRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def undelete_bucket( + self, + request: Optional[Union[logging_config.UndeleteBucketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Undeletes a log bucket. A bucket that has been deleted can be undeleted within the grace period of 7 days. @@ -1426,9 +1581,7 @@ def sample_undelete_bucket(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1442,14 +1595,15 @@ def sample_undelete_bucket(): metadata=metadata, ) - def _list_views(self, - request: Optional[Union[logging_config.ListViewsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListViewsPager: + def _list_views( + self, + request: Optional[Union[logging_config.ListViewsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListViewsPager: r"""Lists views on a log bucket. .. code-block:: python @@ -1513,10 +1667,14 @@ def sample_list_views(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1534,9 +1692,7 @@ def sample_list_views(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1564,13 +1720,14 @@ def sample_list_views(): # Done; return the response. return response - def _get_view(self, - request: Optional[Union[logging_config.GetViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogView: + def _get_view( + self, + request: Optional[Union[logging_config.GetViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: r"""Gets a view on a log bucket.. .. code-block:: python @@ -1629,9 +1786,7 @@ def sample_get_view(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1648,13 +1803,14 @@ def sample_get_view(): # Done; return the response. return response - def _create_view(self, - request: Optional[Union[logging_config.CreateViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogView: + def _create_view( + self, + request: Optional[Union[logging_config.CreateViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: r"""Creates a view over log entries in a log bucket. A bucket may contain a maximum of 30 views. @@ -1715,9 +1871,7 @@ def sample_create_view(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1734,13 +1888,14 @@ def sample_create_view(): # Done; return the response. return response - def _update_view(self, - request: Optional[Union[logging_config.UpdateViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogView: + def _update_view( + self, + request: Optional[Union[logging_config.UpdateViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogView: r"""Updates a view on a log bucket. This method replaces the following fields in the existing view with values from the new view: ``filter``. If an ``UNAVAILABLE`` error is returned, this @@ -1803,9 +1958,7 @@ def sample_update_view(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1822,13 +1975,14 @@ def sample_update_view(): # Done; return the response. return response - def _delete_view(self, - request: Optional[Union[logging_config.DeleteViewRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def _delete_view( + self, + request: Optional[Union[logging_config.DeleteViewRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a view on a log bucket. If an ``UNAVAILABLE`` error is returned, this indicates that system is not in a state where it can delete the view. If this occurs, please try again in a few @@ -1881,9 +2035,7 @@ def sample_delete_view(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1897,14 +2049,15 @@ def sample_delete_view(): metadata=metadata, ) - def _list_sinks(self, - request: Optional[Union[logging_config.ListSinksRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListSinksPager: + def _list_sinks( + self, + request: Optional[Union[logging_config.ListSinksRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSinksPager: r"""Lists sinks. .. code-block:: python @@ -1971,10 +2124,14 @@ def sample_list_sinks(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1992,9 +2149,7 @@ def sample_list_sinks(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2022,14 +2177,15 @@ def sample_list_sinks(): # Done; return the response. return response - def _get_sink(self, - request: Optional[Union[logging_config.GetSinkRequest, dict]] = None, - *, - sink_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogSink: + def _get_sink( + self, + request: Optional[Union[logging_config.GetSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: r"""Gets a sink. .. code-block:: python @@ -2103,10 +2259,14 @@ def sample_get_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [sink_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2124,9 +2284,9 @@ def sample_get_sink(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("sink_name", request.sink_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("sink_name", request.sink_name),) + ), ) # Validate the universe domain. @@ -2143,15 +2303,16 @@ def sample_get_sink(): # Done; return the response. return response - def _create_sink(self, - request: Optional[Union[logging_config.CreateSinkRequest, dict]] = None, - *, - parent: Optional[str] = None, - sink: Optional[logging_config.LogSink] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogSink: + def _create_sink( + self, + request: Optional[Union[logging_config.CreateSinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + sink: Optional[logging_config.LogSink] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: r"""Creates a sink that exports specified log entries to a destination. The export of newly-ingested log entries begins immediately, unless the sink's ``writer_identity`` is not @@ -2241,10 +2402,14 @@ def sample_create_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, sink] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2264,9 +2429,7 @@ def sample_create_sink(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2283,16 +2446,17 @@ def sample_create_sink(): # Done; return the response. return response - def _update_sink(self, - request: Optional[Union[logging_config.UpdateSinkRequest, dict]] = None, - *, - sink_name: Optional[str] = None, - sink: Optional[logging_config.LogSink] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogSink: + def _update_sink( + self, + request: Optional[Union[logging_config.UpdateSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + sink: Optional[logging_config.LogSink] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogSink: r"""Updates a sink. This method replaces the following fields in the existing sink with values from the new sink: ``destination``, and ``filter``. @@ -2406,10 +2570,14 @@ def sample_update_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [sink_name, sink, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2431,9 +2599,9 @@ def sample_update_sink(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("sink_name", request.sink_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("sink_name", request.sink_name),) + ), ) # Validate the universe domain. @@ -2450,14 +2618,15 @@ def sample_update_sink(): # Done; return the response. return response - def _delete_sink(self, - request: Optional[Union[logging_config.DeleteSinkRequest, dict]] = None, - *, - sink_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def _delete_sink( + self, + request: Optional[Union[logging_config.DeleteSinkRequest, dict]] = None, + *, + sink_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a sink. If the sink has a unique ``writer_identity``, then that service account is also deleted. @@ -2517,10 +2686,14 @@ def sample_delete_sink(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [sink_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2538,9 +2711,9 @@ def sample_delete_sink(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("sink_name", request.sink_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("sink_name", request.sink_name),) + ), ) # Validate the universe domain. @@ -2554,16 +2727,17 @@ def sample_delete_sink(): metadata=metadata, ) - def _create_link(self, - request: Optional[Union[logging_config.CreateLinkRequest, dict]] = None, - *, - parent: Optional[str] = None, - link: Optional[logging_config.Link] = None, - link_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def _create_link( + self, + request: Optional[Union[logging_config.CreateLinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + link: Optional[logging_config.Link] = None, + link_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Asynchronously creates a linked dataset in BigQuery which makes it possible to use BigQuery to read the logs stored in the log bucket. A log bucket may currently @@ -2651,10 +2825,14 @@ def sample_create_link(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, link, link_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2676,9 +2854,7 @@ def sample_create_link(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2703,14 +2879,15 @@ def sample_create_link(): # Done; return the response. return response - def _delete_link(self, - request: Optional[Union[logging_config.DeleteLinkRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def _delete_link( + self, + request: Optional[Union[logging_config.DeleteLinkRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Deletes a link. This will also delete the corresponding BigQuery linked dataset. @@ -2786,10 +2963,14 @@ def sample_delete_link(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2807,9 +2988,7 @@ def sample_delete_link(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2834,14 +3013,15 @@ def sample_delete_link(): # Done; return the response. return response - def _list_links(self, - request: Optional[Union[logging_config.ListLinksRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLinksPager: + def _list_links( + self, + request: Optional[Union[logging_config.ListLinksRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLinksPager: r"""Lists links. .. code-block:: python @@ -2907,10 +3087,14 @@ def sample_list_links(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2928,9 +3112,7 @@ def sample_list_links(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -2958,14 +3140,15 @@ def sample_list_links(): # Done; return the response. return response - def _get_link(self, - request: Optional[Union[logging_config.GetLinkRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.Link: + def _get_link( + self, + request: Optional[Union[logging_config.GetLinkRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Link: r"""Gets a link. .. code-block:: python @@ -3026,10 +3209,14 @@ def sample_get_link(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3047,9 +3234,7 @@ def sample_get_link(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3066,14 +3251,15 @@ def sample_get_link(): # Done; return the response. return response - def _list_exclusions(self, - request: Optional[Union[logging_config.ListExclusionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListExclusionsPager: + def _list_exclusions( + self, + request: Optional[Union[logging_config.ListExclusionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListExclusionsPager: r"""Lists all the exclusions on the \_Default sink in a parent resource. @@ -3141,10 +3327,14 @@ def sample_list_exclusions(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3162,9 +3352,7 @@ def sample_list_exclusions(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -3192,14 +3380,15 @@ def sample_list_exclusions(): # Done; return the response. return response - def _get_exclusion(self, - request: Optional[Union[logging_config.GetExclusionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogExclusion: + def _get_exclusion( + self, + request: Optional[Union[logging_config.GetExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: r"""Gets the description of an exclusion in the \_Default sink. .. code-block:: python @@ -3271,10 +3460,14 @@ def sample_get_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3292,9 +3485,7 @@ def sample_get_exclusion(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3311,15 +3502,16 @@ def sample_get_exclusion(): # Done; return the response. return response - def _create_exclusion(self, - request: Optional[Union[logging_config.CreateExclusionRequest, dict]] = None, - *, - parent: Optional[str] = None, - exclusion: Optional[logging_config.LogExclusion] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogExclusion: + def _create_exclusion( + self, + request: Optional[Union[logging_config.CreateExclusionRequest, dict]] = None, + *, + parent: Optional[str] = None, + exclusion: Optional[logging_config.LogExclusion] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: r"""Creates a new exclusion in the \_Default sink in a specified parent resource. Only log entries belonging to that resource can be excluded. You can have up to 10 exclusions in a resource. @@ -3408,10 +3600,14 @@ def sample_create_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, exclusion] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3431,9 +3627,7 @@ def sample_create_exclusion(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -3450,16 +3644,17 @@ def sample_create_exclusion(): # Done; return the response. return response - def _update_exclusion(self, - request: Optional[Union[logging_config.UpdateExclusionRequest, dict]] = None, - *, - name: Optional[str] = None, - exclusion: Optional[logging_config.LogExclusion] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.LogExclusion: + def _update_exclusion( + self, + request: Optional[Union[logging_config.UpdateExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + exclusion: Optional[logging_config.LogExclusion] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.LogExclusion: r"""Changes one or more properties of an existing exclusion in the \_Default sink. @@ -3559,10 +3754,14 @@ def sample_update_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, exclusion, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3584,9 +3783,7 @@ def sample_update_exclusion(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3603,14 +3800,15 @@ def sample_update_exclusion(): # Done; return the response. return response - def _delete_exclusion(self, - request: Optional[Union[logging_config.DeleteExclusionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def _delete_exclusion( + self, + request: Optional[Union[logging_config.DeleteExclusionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes an exclusion in the \_Default sink. .. code-block:: python @@ -3669,10 +3867,14 @@ def sample_delete_exclusion(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -3690,9 +3892,7 @@ def sample_delete_exclusion(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3706,13 +3906,14 @@ def sample_delete_exclusion(): metadata=metadata, ) - def _get_cmek_settings(self, - request: Optional[Union[logging_config.GetCmekSettingsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.CmekSettings: + def _get_cmek_settings( + self, + request: Optional[Union[logging_config.GetCmekSettingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.CmekSettings: r"""Gets the Logging CMEK settings for the given resource. Note: CMEK for the Log Router can be configured for Google Cloud @@ -3795,9 +3996,7 @@ def sample_get_cmek_settings(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3814,13 +4013,14 @@ def sample_get_cmek_settings(): # Done; return the response. return response - def _update_cmek_settings(self, - request: Optional[Union[logging_config.UpdateCmekSettingsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.CmekSettings: + def _update_cmek_settings( + self, + request: Optional[Union[logging_config.UpdateCmekSettingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.CmekSettings: r"""Updates the Log Router CMEK settings for the given resource. Note: CMEK for the Log Router can currently only be configured @@ -3908,9 +4108,7 @@ def sample_update_cmek_settings(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -3927,14 +4125,15 @@ def sample_update_cmek_settings(): # Done; return the response. return response - def _get_settings(self, - request: Optional[Union[logging_config.GetSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.Settings: + def _get_settings( + self, + request: Optional[Union[logging_config.GetSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Settings: r"""Gets the Log Router settings for the given resource. Note: Settings for the Log Router can be get for Google Cloud @@ -4024,10 +4223,14 @@ def sample_get_settings(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4045,9 +4248,7 @@ def sample_get_settings(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -4064,15 +4265,16 @@ def sample_get_settings(): # Done; return the response. return response - def _update_settings(self, - request: Optional[Union[logging_config.UpdateSettingsRequest, dict]] = None, - *, - settings: Optional[logging_config.Settings] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_config.Settings: + def _update_settings( + self, + request: Optional[Union[logging_config.UpdateSettingsRequest, dict]] = None, + *, + settings: Optional[logging_config.Settings] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_config.Settings: r"""Updates the Log Router settings for the given resource. Note: Settings for the Log Router can currently only be @@ -4169,10 +4371,14 @@ def sample_update_settings(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [settings, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -4192,9 +4398,7 @@ def sample_update_settings(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -4211,13 +4415,14 @@ def sample_update_settings(): # Done; return the response. return response - def _copy_log_entries(self, - request: Optional[Union[logging_config.CopyLogEntriesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def _copy_log_entries( + self, + request: Optional[Union[logging_config.CopyLogEntriesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Copies a set of log entries from a log bucket to a Cloud Storage bucket. @@ -4360,8 +4565,7 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -4370,7 +4574,11 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -4420,8 +4628,7 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -4430,7 +4637,11 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -4483,27 +4694,26 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - - - - + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "BaseConfigServiceV2Client", -) +__all__ = ("BaseConfigServiceV2Client",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/base.py index 3aba43c4b4aa..bdeabc4a074d 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/base.py @@ -25,14 +25,16 @@ from google.api_core import retry as retries from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf from google.cloud.logging_v2.types import logging_config -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ @@ -42,26 +44,27 @@ class ConfigServiceV2Transport(abc.ABC): """Abstract transport class for ConfigServiceV2.""" AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/logging.admin", + "https://www.googleapis.com/auth/logging.read", ) - DEFAULT_HOST: str = 'logging.googleapis.com' + DEFAULT_HOST: str = "logging.googleapis.com" def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -100,31 +103,43 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host self._wrapped_methods: Dict[Callable, Callable] = {} @@ -388,14 +403,14 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -405,291 +420,306 @@ def operations_client(self): raise NotImplementedError() @property - def list_buckets(self) -> Callable[ - [logging_config.ListBucketsRequest], - Union[ - logging_config.ListBucketsResponse, - Awaitable[logging_config.ListBucketsResponse] - ]]: + def list_buckets( + self, + ) -> Callable[ + [logging_config.ListBucketsRequest], + Union[ + logging_config.ListBucketsResponse, + Awaitable[logging_config.ListBucketsResponse], + ], + ]: raise NotImplementedError() @property - def get_bucket(self) -> Callable[ - [logging_config.GetBucketRequest], - Union[ - logging_config.LogBucket, - Awaitable[logging_config.LogBucket] - ]]: + def get_bucket( + self, + ) -> Callable[ + [logging_config.GetBucketRequest], + Union[logging_config.LogBucket, Awaitable[logging_config.LogBucket]], + ]: raise NotImplementedError() @property - def create_bucket_async(self) -> Callable[ - [logging_config.CreateBucketRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_bucket_async( + self, + ) -> Callable[ + [logging_config.CreateBucketRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def update_bucket_async(self) -> Callable[ - [logging_config.UpdateBucketRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def update_bucket_async( + self, + ) -> Callable[ + [logging_config.UpdateBucketRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def create_bucket(self) -> Callable[ - [logging_config.CreateBucketRequest], - Union[ - logging_config.LogBucket, - Awaitable[logging_config.LogBucket] - ]]: + def create_bucket( + self, + ) -> Callable[ + [logging_config.CreateBucketRequest], + Union[logging_config.LogBucket, Awaitable[logging_config.LogBucket]], + ]: raise NotImplementedError() @property - def update_bucket(self) -> Callable[ - [logging_config.UpdateBucketRequest], - Union[ - logging_config.LogBucket, - Awaitable[logging_config.LogBucket] - ]]: + def update_bucket( + self, + ) -> Callable[ + [logging_config.UpdateBucketRequest], + Union[logging_config.LogBucket, Awaitable[logging_config.LogBucket]], + ]: raise NotImplementedError() @property - def delete_bucket(self) -> Callable[ - [logging_config.DeleteBucketRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_bucket( + self, + ) -> Callable[ + [logging_config.DeleteBucketRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property - def undelete_bucket(self) -> Callable[ - [logging_config.UndeleteBucketRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def undelete_bucket( + self, + ) -> Callable[ + [logging_config.UndeleteBucketRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property - def list_views(self) -> Callable[ - [logging_config.ListViewsRequest], - Union[ - logging_config.ListViewsResponse, - Awaitable[logging_config.ListViewsResponse] - ]]: + def list_views( + self, + ) -> Callable[ + [logging_config.ListViewsRequest], + Union[ + logging_config.ListViewsResponse, + Awaitable[logging_config.ListViewsResponse], + ], + ]: raise NotImplementedError() @property - def get_view(self) -> Callable[ - [logging_config.GetViewRequest], - Union[ - logging_config.LogView, - Awaitable[logging_config.LogView] - ]]: + def get_view( + self, + ) -> Callable[ + [logging_config.GetViewRequest], + Union[logging_config.LogView, Awaitable[logging_config.LogView]], + ]: raise NotImplementedError() @property - def create_view(self) -> Callable[ - [logging_config.CreateViewRequest], - Union[ - logging_config.LogView, - Awaitable[logging_config.LogView] - ]]: + def create_view( + self, + ) -> Callable[ + [logging_config.CreateViewRequest], + Union[logging_config.LogView, Awaitable[logging_config.LogView]], + ]: raise NotImplementedError() @property - def update_view(self) -> Callable[ - [logging_config.UpdateViewRequest], - Union[ - logging_config.LogView, - Awaitable[logging_config.LogView] - ]]: + def update_view( + self, + ) -> Callable[ + [logging_config.UpdateViewRequest], + Union[logging_config.LogView, Awaitable[logging_config.LogView]], + ]: raise NotImplementedError() @property - def delete_view(self) -> Callable[ - [logging_config.DeleteViewRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_view( + self, + ) -> Callable[ + [logging_config.DeleteViewRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property - def list_sinks(self) -> Callable[ - [logging_config.ListSinksRequest], - Union[ - logging_config.ListSinksResponse, - Awaitable[logging_config.ListSinksResponse] - ]]: + def list_sinks( + self, + ) -> Callable[ + [logging_config.ListSinksRequest], + Union[ + logging_config.ListSinksResponse, + Awaitable[logging_config.ListSinksResponse], + ], + ]: raise NotImplementedError() @property - def get_sink(self) -> Callable[ - [logging_config.GetSinkRequest], - Union[ - logging_config.LogSink, - Awaitable[logging_config.LogSink] - ]]: + def get_sink( + self, + ) -> Callable[ + [logging_config.GetSinkRequest], + Union[logging_config.LogSink, Awaitable[logging_config.LogSink]], + ]: raise NotImplementedError() @property - def create_sink(self) -> Callable[ - [logging_config.CreateSinkRequest], - Union[ - logging_config.LogSink, - Awaitable[logging_config.LogSink] - ]]: + def create_sink( + self, + ) -> Callable[ + [logging_config.CreateSinkRequest], + Union[logging_config.LogSink, Awaitable[logging_config.LogSink]], + ]: raise NotImplementedError() @property - def update_sink(self) -> Callable[ - [logging_config.UpdateSinkRequest], - Union[ - logging_config.LogSink, - Awaitable[logging_config.LogSink] - ]]: + def update_sink( + self, + ) -> Callable[ + [logging_config.UpdateSinkRequest], + Union[logging_config.LogSink, Awaitable[logging_config.LogSink]], + ]: raise NotImplementedError() @property - def delete_sink(self) -> Callable[ - [logging_config.DeleteSinkRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_sink( + self, + ) -> Callable[ + [logging_config.DeleteSinkRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property - def create_link(self) -> Callable[ - [logging_config.CreateLinkRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_link( + self, + ) -> Callable[ + [logging_config.CreateLinkRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def delete_link(self) -> Callable[ - [logging_config.DeleteLinkRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def delete_link( + self, + ) -> Callable[ + [logging_config.DeleteLinkRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def list_links(self) -> Callable[ - [logging_config.ListLinksRequest], - Union[ - logging_config.ListLinksResponse, - Awaitable[logging_config.ListLinksResponse] - ]]: + def list_links( + self, + ) -> Callable[ + [logging_config.ListLinksRequest], + Union[ + logging_config.ListLinksResponse, + Awaitable[logging_config.ListLinksResponse], + ], + ]: raise NotImplementedError() @property - def get_link(self) -> Callable[ - [logging_config.GetLinkRequest], - Union[ - logging_config.Link, - Awaitable[logging_config.Link] - ]]: + def get_link( + self, + ) -> Callable[ + [logging_config.GetLinkRequest], + Union[logging_config.Link, Awaitable[logging_config.Link]], + ]: raise NotImplementedError() @property - def list_exclusions(self) -> Callable[ - [logging_config.ListExclusionsRequest], - Union[ - logging_config.ListExclusionsResponse, - Awaitable[logging_config.ListExclusionsResponse] - ]]: + def list_exclusions( + self, + ) -> Callable[ + [logging_config.ListExclusionsRequest], + Union[ + logging_config.ListExclusionsResponse, + Awaitable[logging_config.ListExclusionsResponse], + ], + ]: raise NotImplementedError() @property - def get_exclusion(self) -> Callable[ - [logging_config.GetExclusionRequest], - Union[ - logging_config.LogExclusion, - Awaitable[logging_config.LogExclusion] - ]]: + def get_exclusion( + self, + ) -> Callable[ + [logging_config.GetExclusionRequest], + Union[logging_config.LogExclusion, Awaitable[logging_config.LogExclusion]], + ]: raise NotImplementedError() @property - def create_exclusion(self) -> Callable[ - [logging_config.CreateExclusionRequest], - Union[ - logging_config.LogExclusion, - Awaitable[logging_config.LogExclusion] - ]]: + def create_exclusion( + self, + ) -> Callable[ + [logging_config.CreateExclusionRequest], + Union[logging_config.LogExclusion, Awaitable[logging_config.LogExclusion]], + ]: raise NotImplementedError() @property - def update_exclusion(self) -> Callable[ - [logging_config.UpdateExclusionRequest], - Union[ - logging_config.LogExclusion, - Awaitable[logging_config.LogExclusion] - ]]: + def update_exclusion( + self, + ) -> Callable[ + [logging_config.UpdateExclusionRequest], + Union[logging_config.LogExclusion, Awaitable[logging_config.LogExclusion]], + ]: raise NotImplementedError() @property - def delete_exclusion(self) -> Callable[ - [logging_config.DeleteExclusionRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_exclusion( + self, + ) -> Callable[ + [logging_config.DeleteExclusionRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property - def get_cmek_settings(self) -> Callable[ - [logging_config.GetCmekSettingsRequest], - Union[ - logging_config.CmekSettings, - Awaitable[logging_config.CmekSettings] - ]]: + def get_cmek_settings( + self, + ) -> Callable[ + [logging_config.GetCmekSettingsRequest], + Union[logging_config.CmekSettings, Awaitable[logging_config.CmekSettings]], + ]: raise NotImplementedError() @property - def update_cmek_settings(self) -> Callable[ - [logging_config.UpdateCmekSettingsRequest], - Union[ - logging_config.CmekSettings, - Awaitable[logging_config.CmekSettings] - ]]: + def update_cmek_settings( + self, + ) -> Callable[ + [logging_config.UpdateCmekSettingsRequest], + Union[logging_config.CmekSettings, Awaitable[logging_config.CmekSettings]], + ]: raise NotImplementedError() @property - def get_settings(self) -> Callable[ - [logging_config.GetSettingsRequest], - Union[ - logging_config.Settings, - Awaitable[logging_config.Settings] - ]]: + def get_settings( + self, + ) -> Callable[ + [logging_config.GetSettingsRequest], + Union[logging_config.Settings, Awaitable[logging_config.Settings]], + ]: raise NotImplementedError() @property - def update_settings(self) -> Callable[ - [logging_config.UpdateSettingsRequest], - Union[ - logging_config.Settings, - Awaitable[logging_config.Settings] - ]]: + def update_settings( + self, + ) -> Callable[ + [logging_config.UpdateSettingsRequest], + Union[logging_config.Settings, Awaitable[logging_config.Settings]], + ]: raise NotImplementedError() @property - def copy_log_entries(self) -> Callable[ - [logging_config.CopyLogEntriesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def copy_log_entries( + self, + ) -> Callable[ + [logging_config.CopyLogEntriesRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property @@ -697,7 +727,10 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], ]: raise NotImplementedError() @@ -713,10 +746,7 @@ def get_operation( @property def cancel_operation( self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: raise NotImplementedError() @property @@ -724,6 +754,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'ConfigServiceV2Transport', -) +__all__ = ("ConfigServiceV2Transport",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/async_client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/async_client.py index 5e5d98cf31ba..233967cd530d 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/async_client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/async_client.py @@ -16,7 +16,21 @@ import logging as std_logging from collections import OrderedDict import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Type, Union +from typing import ( + Dict, + Callable, + Mapping, + MutableMapping, + MutableSequence, + Optional, + AsyncIterable, + Awaitable, + AsyncIterator, + Sequence, + Tuple, + Type, + Union, +) from google.cloud.logging_v2 import gapic_version as package_version @@ -24,8 +38,8 @@ from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf @@ -37,7 +51,7 @@ from google.cloud.logging_v2.services.logging_service_v2 import pagers from google.cloud.logging_v2.types import log_entry from google.cloud.logging_v2.types import logging -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.api.monitored_resource_pb2 as monitored_resource_pb2 # type: ignore from .transports.base import LoggingServiceV2Transport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import LoggingServiceV2GrpcAsyncIOTransport @@ -45,12 +59,14 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) + class LoggingServiceV2AsyncClient: """Service for ingesting and querying logs.""" @@ -65,16 +81,30 @@ class LoggingServiceV2AsyncClient: log_path = staticmethod(LoggingServiceV2Client.log_path) parse_log_path = staticmethod(LoggingServiceV2Client.parse_log_path) - common_billing_account_path = staticmethod(LoggingServiceV2Client.common_billing_account_path) - parse_common_billing_account_path = staticmethod(LoggingServiceV2Client.parse_common_billing_account_path) + common_billing_account_path = staticmethod( + LoggingServiceV2Client.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + LoggingServiceV2Client.parse_common_billing_account_path + ) common_folder_path = staticmethod(LoggingServiceV2Client.common_folder_path) - parse_common_folder_path = staticmethod(LoggingServiceV2Client.parse_common_folder_path) - common_organization_path = staticmethod(LoggingServiceV2Client.common_organization_path) - parse_common_organization_path = staticmethod(LoggingServiceV2Client.parse_common_organization_path) + parse_common_folder_path = staticmethod( + LoggingServiceV2Client.parse_common_folder_path + ) + common_organization_path = staticmethod( + LoggingServiceV2Client.common_organization_path + ) + parse_common_organization_path = staticmethod( + LoggingServiceV2Client.parse_common_organization_path + ) common_project_path = staticmethod(LoggingServiceV2Client.common_project_path) - parse_common_project_path = staticmethod(LoggingServiceV2Client.parse_common_project_path) + parse_common_project_path = staticmethod( + LoggingServiceV2Client.parse_common_project_path + ) common_location_path = staticmethod(LoggingServiceV2Client.common_location_path) - parse_common_location_path = staticmethod(LoggingServiceV2Client.parse_common_location_path) + parse_common_location_path = staticmethod( + LoggingServiceV2Client.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -116,7 +146,9 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): """Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -179,12 +211,18 @@ def universe_domain(self) -> str: get_transport_class = LoggingServiceV2Client.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, LoggingServiceV2Transport, Callable[..., LoggingServiceV2Transport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, LoggingServiceV2Transport, Callable[..., LoggingServiceV2Transport] + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the logging service v2 async client. Args: @@ -239,31 +277,39 @@ def __init__(self, *, transport=transport, client_options=client_options, client_info=client_info, - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.logging_v2.LoggingServiceV2AsyncClient`.", - extra = { + extra={ "serviceName": "google.logging.v2.LoggingServiceV2", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { "serviceName": "google.logging.v2.LoggingServiceV2", "credentialsType": None, - } + }, ) - async def delete_log(self, - request: Optional[Union[logging.DeleteLogRequest, dict]] = None, - *, - log_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def delete_log( + self, + request: Optional[Union[logging.DeleteLogRequest, dict]] = None, + *, + log_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes all the log entries in a log for the \_Default Log Bucket. The log reappears if it receives new entries. Log entries written shortly before the delete operation might not be @@ -326,10 +372,14 @@ async def sample_delete_log(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [log_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -343,14 +393,14 @@ async def sample_delete_log(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_log] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_log + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("log_name", request.log_name), - )), + gapic_v1.routing_header.to_grpc_metadata((("log_name", request.log_name),)), ) # Validate the universe domain. @@ -364,17 +414,18 @@ async def sample_delete_log(): metadata=metadata, ) - async def write_log_entries(self, - request: Optional[Union[logging.WriteLogEntriesRequest, dict]] = None, - *, - log_name: Optional[str] = None, - resource: Optional[monitored_resource_pb2.MonitoredResource] = None, - labels: Optional[MutableMapping[str, str]] = None, - entries: Optional[MutableSequence[log_entry.LogEntry]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging.WriteLogEntriesResponse: + async def write_log_entries( + self, + request: Optional[Union[logging.WriteLogEntriesRequest, dict]] = None, + *, + log_name: Optional[str] = None, + resource: Optional[monitored_resource_pb2.MonitoredResource] = None, + labels: Optional[MutableMapping[str, str]] = None, + entries: Optional[MutableSequence[log_entry.LogEntry]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging.WriteLogEntriesResponse: r"""Writes log entries to Logging. This API method is the only way to send log entries to Logging. This method is used, directly or indirectly, by the Logging agent @@ -517,10 +568,14 @@ async def sample_write_log_entries(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [log_name, resource, labels, entries] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -541,7 +596,9 @@ async def sample_write_log_entries(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.write_log_entries] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.write_log_entries + ] # Validate the universe domain. self._client._validate_universe_domain() @@ -557,16 +614,17 @@ async def sample_write_log_entries(): # Done; return the response. return response - async def list_log_entries(self, - request: Optional[Union[logging.ListLogEntriesRequest, dict]] = None, - *, - resource_names: Optional[MutableSequence[str]] = None, - filter: Optional[str] = None, - order_by: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLogEntriesAsyncPager: + async def list_log_entries( + self, + request: Optional[Union[logging.ListLogEntriesRequest, dict]] = None, + *, + resource_names: Optional[MutableSequence[str]] = None, + filter: Optional[str] = None, + order_by: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogEntriesAsyncPager: r"""Lists log entries. Use this method to retrieve log entries that originated from a project/folder/organization/billing account. For ways to export log entries, see `Exporting @@ -669,10 +727,14 @@ async def sample_list_log_entries(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [resource_names, filter, order_by] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -690,7 +752,9 @@ async def sample_list_log_entries(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_log_entries] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_log_entries + ] # Validate the universe domain. self._client._validate_universe_domain() @@ -717,13 +781,16 @@ async def sample_list_log_entries(): # Done; return the response. return response - async def list_monitored_resource_descriptors(self, - request: Optional[Union[logging.ListMonitoredResourceDescriptorsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListMonitoredResourceDescriptorsAsyncPager: + async def list_monitored_resource_descriptors( + self, + request: Optional[ + Union[logging.ListMonitoredResourceDescriptorsRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMonitoredResourceDescriptorsAsyncPager: r"""Lists the descriptors for monitored resource types used by Logging. @@ -782,7 +849,9 @@ async def sample_list_monitored_resource_descriptors(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_monitored_resource_descriptors] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_monitored_resource_descriptors + ] # Validate the universe domain. self._client._validate_universe_domain() @@ -809,14 +878,15 @@ async def sample_list_monitored_resource_descriptors(): # Done; return the response. return response - async def list_logs(self, - request: Optional[Union[logging.ListLogsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLogsAsyncPager: + async def list_logs( + self, + request: Optional[Union[logging.ListLogsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogsAsyncPager: r"""Lists the logs in projects, organizations, folders, or billing accounts. Only logs that have entries are listed. @@ -883,10 +953,14 @@ async def sample_list_logs(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -900,14 +974,14 @@ async def sample_list_logs(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_logs] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_logs + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -935,13 +1009,14 @@ async def sample_list_logs(): # Done; return the response. return response - def tail_log_entries(self, - requests: Optional[AsyncIterator[logging.TailLogEntriesRequest]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> Awaitable[AsyncIterable[logging.TailLogEntriesResponse]]: + def tail_log_entries( + self, + requests: Optional[AsyncIterator[logging.TailLogEntriesRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Awaitable[AsyncIterable[logging.TailLogEntriesResponse]]: r"""Streaming read of log entries as they are ingested. Until the stream is terminated, it will continue reading logs. @@ -1001,7 +1076,9 @@ def request_generator(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.tail_log_entries] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.tail_log_entries + ] # Validate the universe domain. self._client._validate_universe_domain() @@ -1059,8 +1136,7 @@ async def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1068,7 +1144,11 @@ async def list_operations( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1115,8 +1195,7 @@ async def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1124,7 +1203,11 @@ async def get_operation( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1174,15 +1257,19 @@ async def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) async def __aenter__(self) -> "LoggingServiceV2AsyncClient": return self @@ -1190,12 +1277,13 @@ async def __aenter__(self) -> "LoggingServiceV2AsyncClient": async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "LoggingServiceV2AsyncClient", -) +__all__ = ("LoggingServiceV2AsyncClient",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py index db711c4593a8..f3758559e92f 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py @@ -19,7 +19,21 @@ import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union, cast +from typing import ( + Dict, + Callable, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Iterable, + Iterator, + Sequence, + Tuple, + Type, + Union, + cast, +) import warnings from google.cloud.logging_v2 import gapic_version as package_version @@ -28,11 +42,11 @@ from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.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.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 import google.protobuf try: @@ -42,6 +56,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -51,7 +66,7 @@ from google.cloud.logging_v2.services.logging_service_v2 import pagers from google.cloud.logging_v2.types import log_entry from google.cloud.logging_v2.types import logging -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.api.monitored_resource_pb2 as monitored_resource_pb2 # type: ignore from .transports.base import LoggingServiceV2Transport, DEFAULT_CLIENT_INFO from .transports.grpc import LoggingServiceV2GrpcTransport @@ -65,13 +80,17 @@ class LoggingServiceV2ClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[LoggingServiceV2Transport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[LoggingServiceV2Transport]] _transport_registry["grpc"] = LoggingServiceV2GrpcTransport _transport_registry["grpc_asyncio"] = LoggingServiceV2GrpcAsyncIOTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[LoggingServiceV2Transport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[LoggingServiceV2Transport]: """Returns an appropriate transport class. Args: @@ -147,14 +166,16 @@ def _use_client_cert_effective(): bool: whether client certificate should be used for mTLS Raises: ValueError: (If using a version of google-auth without should_use_client_cert and - GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) """ # check if google-auth version supports should_use_client_cert for automatic mTLS enablement if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER return mtls.should_use_client_cert() - else: # pragma: NO COVER + else: # pragma: NO COVER # if unsupported, fallback to reading from env var - use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() if use_client_cert_str not in ("true", "false"): raise ValueError( "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" @@ -193,8 +214,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: LoggingServiceV2Client: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -211,73 +231,103 @@ def transport(self) -> LoggingServiceV2Transport: return self._transport @staticmethod - def log_path(project: str,log: str,) -> str: + def log_path( + project: str, + log: str, + ) -> str: """Returns a fully-qualified log string.""" - return "projects/{project}/logs/{log}".format(project=project, log=log, ) + return "projects/{project}/logs/{log}".format( + project=project, + log=log, + ) @staticmethod - def parse_log_path(path: str) -> Dict[str,str]: + def parse_log_path(path: str) -> Dict[str, str]: """Parses a log path into its component segments.""" m = re.match(r"^projects/(?P.+?)/logs/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + def common_billing_account_path( + billing_account: str, + ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path(folder: str, ) -> str: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path(organization: str, ) -> str: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path(project: str, ) -> str: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path(project: str, location: str, ) -> str: + def common_location_path( + project: str, + location: str, + ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -309,14 +359,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = LoggingServiceV2Client._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Figure out the client cert source to use. client_cert_source = None @@ -329,7 +383,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): api_endpoint = cls.DEFAULT_MTLS_ENDPOINT else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -354,7 +410,9 @@ def _read_environment_variables(): use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod @@ -377,7 +435,9 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: """Return the API endpoint used by the client. Args: @@ -393,17 +453,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): _default_universe = LoggingServiceV2Client._DEFAULT_UNIVERSE if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) api_endpoint = LoggingServiceV2Client.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = LoggingServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = LoggingServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) return api_endpoint @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: """Return the universe domain used by the client. Args: @@ -439,15 +507,18 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError + self, error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: return cred = self._transport._credentials @@ -480,12 +551,18 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, LoggingServiceV2Transport, Callable[..., LoggingServiceV2Transport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, LoggingServiceV2Transport, Callable[..., LoggingServiceV2Transport] + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the logging service v2 client. Args: @@ -540,13 +617,23 @@ def __init__(self, *, self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = LoggingServiceV2Client._read_environment_variables() - self._client_cert_source = LoggingServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = LoggingServiceV2Client._get_universe_domain(universe_domain_opt, self._universe_domain_env) + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = LoggingServiceV2Client._read_environment_variables() + self._client_cert_source = LoggingServiceV2Client._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = LoggingServiceV2Client._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -558,7 +645,9 @@ def __init__(self, *, api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -567,8 +656,10 @@ def __init__(self, *, if transport_provided: # transport is a LoggingServiceV2Transport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if self._client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes " @@ -577,20 +668,30 @@ def __init__(self, *, self._transport = cast(LoggingServiceV2Transport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - LoggingServiceV2Client._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or LoggingServiceV2Client._get_api_endpoint( self._client_options.api_endpoint, self._client_cert_source, self._universe_domain, - self._use_mtls_endpoint)) + self._use_mtls_endpoint, + ) + ) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) - transport_init: Union[Type[LoggingServiceV2Transport], Callable[..., LoggingServiceV2Transport]] = ( + transport_init: Union[ + Type[LoggingServiceV2Transport], + Callable[..., LoggingServiceV2Transport], + ] = ( LoggingServiceV2Client.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., LoggingServiceV2Transport], transport) @@ -609,28 +710,37 @@ def __init__(self, *, ) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.logging_v2.LoggingServiceV2Client`.", - extra = { + extra={ "serviceName": "google.logging.v2.LoggingServiceV2", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { "serviceName": "google.logging.v2.LoggingServiceV2", "credentialsType": None, - } + }, ) - def delete_log(self, - request: Optional[Union[logging.DeleteLogRequest, dict]] = None, - *, - log_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_log( + self, + request: Optional[Union[logging.DeleteLogRequest, dict]] = None, + *, + log_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes all the log entries in a log for the \_Default Log Bucket. The log reappears if it receives new entries. Log entries written shortly before the delete operation might not be @@ -693,10 +803,14 @@ def sample_delete_log(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [log_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -714,9 +828,7 @@ def sample_delete_log(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("log_name", request.log_name), - )), + gapic_v1.routing_header.to_grpc_metadata((("log_name", request.log_name),)), ) # Validate the universe domain. @@ -730,17 +842,18 @@ def sample_delete_log(): metadata=metadata, ) - def write_log_entries(self, - request: Optional[Union[logging.WriteLogEntriesRequest, dict]] = None, - *, - log_name: Optional[str] = None, - resource: Optional[monitored_resource_pb2.MonitoredResource] = None, - labels: Optional[MutableMapping[str, str]] = None, - entries: Optional[MutableSequence[log_entry.LogEntry]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging.WriteLogEntriesResponse: + def write_log_entries( + self, + request: Optional[Union[logging.WriteLogEntriesRequest, dict]] = None, + *, + log_name: Optional[str] = None, + resource: Optional[monitored_resource_pb2.MonitoredResource] = None, + labels: Optional[MutableMapping[str, str]] = None, + entries: Optional[MutableSequence[log_entry.LogEntry]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging.WriteLogEntriesResponse: r"""Writes log entries to Logging. This API method is the only way to send log entries to Logging. This method is used, directly or indirectly, by the Logging agent @@ -883,10 +996,14 @@ def sample_write_log_entries(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [log_name, resource, labels, entries] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -921,16 +1038,17 @@ def sample_write_log_entries(): # Done; return the response. return response - def list_log_entries(self, - request: Optional[Union[logging.ListLogEntriesRequest, dict]] = None, - *, - resource_names: Optional[MutableSequence[str]] = None, - filter: Optional[str] = None, - order_by: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLogEntriesPager: + def list_log_entries( + self, + request: Optional[Union[logging.ListLogEntriesRequest, dict]] = None, + *, + resource_names: Optional[MutableSequence[str]] = None, + filter: Optional[str] = None, + order_by: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogEntriesPager: r"""Lists log entries. Use this method to retrieve log entries that originated from a project/folder/organization/billing account. For ways to export log entries, see `Exporting @@ -1033,10 +1151,14 @@ def sample_list_log_entries(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [resource_names, filter, order_by] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1080,13 +1202,16 @@ def sample_list_log_entries(): # Done; return the response. return response - def list_monitored_resource_descriptors(self, - request: Optional[Union[logging.ListMonitoredResourceDescriptorsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListMonitoredResourceDescriptorsPager: + def list_monitored_resource_descriptors( + self, + request: Optional[ + Union[logging.ListMonitoredResourceDescriptorsRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMonitoredResourceDescriptorsPager: r"""Lists the descriptors for monitored resource types used by Logging. @@ -1145,7 +1270,9 @@ def sample_list_monitored_resource_descriptors(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_monitored_resource_descriptors] + rpc = self._transport._wrapped_methods[ + self._transport.list_monitored_resource_descriptors + ] # Validate the universe domain. self._validate_universe_domain() @@ -1172,14 +1299,15 @@ def sample_list_monitored_resource_descriptors(): # Done; return the response. return response - def list_logs(self, - request: Optional[Union[logging.ListLogsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLogsPager: + def list_logs( + self, + request: Optional[Union[logging.ListLogsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogsPager: r"""Lists the logs in projects, organizations, folders, or billing accounts. Only logs that have entries are listed. @@ -1246,10 +1374,14 @@ def sample_list_logs(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1267,9 +1399,7 @@ def sample_list_logs(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1297,13 +1427,14 @@ def sample_list_logs(): # Done; return the response. return response - def tail_log_entries(self, - requests: Optional[Iterator[logging.TailLogEntriesRequest]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> Iterable[logging.TailLogEntriesResponse]: + def tail_log_entries( + self, + requests: Optional[Iterator[logging.TailLogEntriesRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Iterable[logging.TailLogEntriesResponse]: r"""Streaming read of log entries as they are ingested. Until the stream is terminated, it will continue reading logs. @@ -1434,8 +1565,7 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1444,7 +1574,11 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1494,8 +1628,7 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1504,7 +1637,11 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1557,27 +1694,26 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - - - - + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "LoggingServiceV2Client", -) +__all__ = ("LoggingServiceV2Client",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/base.py index 4a1e028497d8..fccfc2c3f06a 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/base.py @@ -24,14 +24,16 @@ from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf from google.cloud.logging_v2.types import logging -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ @@ -41,27 +43,28 @@ class LoggingServiceV2Transport(abc.ABC): """Abstract transport class for LoggingServiceV2.""" AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write', + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/logging.admin", + "https://www.googleapis.com/auth/logging.read", + "https://www.googleapis.com/auth/logging.write", ) - DEFAULT_HOST: str = 'logging.googleapis.com' + DEFAULT_HOST: str = "logging.googleapis.com" def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -100,31 +103,43 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host self._wrapped_methods: Dict[Callable, Callable] = {} @@ -247,69 +262,77 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @property - def delete_log(self) -> Callable[ - [logging.DeleteLogRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_log( + self, + ) -> Callable[ + [logging.DeleteLogRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] + ]: raise NotImplementedError() @property - def write_log_entries(self) -> Callable[ - [logging.WriteLogEntriesRequest], - Union[ - logging.WriteLogEntriesResponse, - Awaitable[logging.WriteLogEntriesResponse] - ]]: + def write_log_entries( + self, + ) -> Callable[ + [logging.WriteLogEntriesRequest], + Union[ + logging.WriteLogEntriesResponse, Awaitable[logging.WriteLogEntriesResponse] + ], + ]: raise NotImplementedError() @property - def list_log_entries(self) -> Callable[ - [logging.ListLogEntriesRequest], - Union[ - logging.ListLogEntriesResponse, - Awaitable[logging.ListLogEntriesResponse] - ]]: + def list_log_entries( + self, + ) -> Callable[ + [logging.ListLogEntriesRequest], + Union[ + logging.ListLogEntriesResponse, Awaitable[logging.ListLogEntriesResponse] + ], + ]: raise NotImplementedError() @property - def list_monitored_resource_descriptors(self) -> Callable[ - [logging.ListMonitoredResourceDescriptorsRequest], - Union[ - logging.ListMonitoredResourceDescriptorsResponse, - Awaitable[logging.ListMonitoredResourceDescriptorsResponse] - ]]: + def list_monitored_resource_descriptors( + self, + ) -> Callable[ + [logging.ListMonitoredResourceDescriptorsRequest], + Union[ + logging.ListMonitoredResourceDescriptorsResponse, + Awaitable[logging.ListMonitoredResourceDescriptorsResponse], + ], + ]: raise NotImplementedError() @property - def list_logs(self) -> Callable[ - [logging.ListLogsRequest], - Union[ - logging.ListLogsResponse, - Awaitable[logging.ListLogsResponse] - ]]: + def list_logs( + self, + ) -> Callable[ + [logging.ListLogsRequest], + Union[logging.ListLogsResponse, Awaitable[logging.ListLogsResponse]], + ]: raise NotImplementedError() @property - def tail_log_entries(self) -> Callable[ - [logging.TailLogEntriesRequest], - Union[ - logging.TailLogEntriesResponse, - Awaitable[logging.TailLogEntriesResponse] - ]]: + def tail_log_entries( + self, + ) -> Callable[ + [logging.TailLogEntriesRequest], + Union[ + logging.TailLogEntriesResponse, Awaitable[logging.TailLogEntriesResponse] + ], + ]: raise NotImplementedError() @property @@ -317,7 +340,10 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], ]: raise NotImplementedError() @@ -333,10 +359,7 @@ def get_operation( @property def cancel_operation( self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: raise NotImplementedError() @property @@ -344,6 +367,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'LoggingServiceV2Transport', -) +__all__ = ("LoggingServiceV2Transport",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/async_client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/async_client.py index 2fc21ae0f3ab..8f505636fe72 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/async_client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/async_client.py @@ -16,7 +16,18 @@ import logging as std_logging from collections import OrderedDict import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union +from typing import ( + Dict, + Callable, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) from google.cloud.logging_v2 import gapic_version as package_version @@ -24,8 +35,8 @@ from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf @@ -36,7 +47,7 @@ from google.cloud.logging_v2.services.metrics_service_v2 import pagers from google.cloud.logging_v2.types import logging_metrics -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.api.distribution_pb2 as distribution_pb2 # type: ignore import google.api.metric_pb2 as metric_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore @@ -46,12 +57,14 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) + class BaseMetricsServiceV2AsyncClient: """Service for configuring logs-based metrics.""" @@ -65,17 +78,33 @@ class BaseMetricsServiceV2AsyncClient: _DEFAULT_UNIVERSE = BaseMetricsServiceV2Client._DEFAULT_UNIVERSE log_metric_path = staticmethod(BaseMetricsServiceV2Client.log_metric_path) - parse_log_metric_path = staticmethod(BaseMetricsServiceV2Client.parse_log_metric_path) - common_billing_account_path = staticmethod(BaseMetricsServiceV2Client.common_billing_account_path) - parse_common_billing_account_path = staticmethod(BaseMetricsServiceV2Client.parse_common_billing_account_path) + parse_log_metric_path = staticmethod( + BaseMetricsServiceV2Client.parse_log_metric_path + ) + common_billing_account_path = staticmethod( + BaseMetricsServiceV2Client.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + BaseMetricsServiceV2Client.parse_common_billing_account_path + ) common_folder_path = staticmethod(BaseMetricsServiceV2Client.common_folder_path) - parse_common_folder_path = staticmethod(BaseMetricsServiceV2Client.parse_common_folder_path) - common_organization_path = staticmethod(BaseMetricsServiceV2Client.common_organization_path) - parse_common_organization_path = staticmethod(BaseMetricsServiceV2Client.parse_common_organization_path) + parse_common_folder_path = staticmethod( + BaseMetricsServiceV2Client.parse_common_folder_path + ) + common_organization_path = staticmethod( + BaseMetricsServiceV2Client.common_organization_path + ) + parse_common_organization_path = staticmethod( + BaseMetricsServiceV2Client.parse_common_organization_path + ) common_project_path = staticmethod(BaseMetricsServiceV2Client.common_project_path) - parse_common_project_path = staticmethod(BaseMetricsServiceV2Client.parse_common_project_path) + parse_common_project_path = staticmethod( + BaseMetricsServiceV2Client.parse_common_project_path + ) common_location_path = staticmethod(BaseMetricsServiceV2Client.common_location_path) - parse_common_location_path = staticmethod(BaseMetricsServiceV2Client.parse_common_location_path) + parse_common_location_path = staticmethod( + BaseMetricsServiceV2Client.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -117,7 +146,9 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): """Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -180,12 +211,18 @@ def universe_domain(self) -> str: get_transport_class = BaseMetricsServiceV2Client.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, MetricsServiceV2Transport, Callable[..., MetricsServiceV2Transport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, MetricsServiceV2Transport, Callable[..., MetricsServiceV2Transport] + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the base metrics service v2 async client. Args: @@ -240,31 +277,39 @@ def __init__(self, *, transport=transport, client_options=client_options, client_info=client_info, - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.logging_v2.BaseMetricsServiceV2AsyncClient`.", - extra = { + extra={ "serviceName": "google.logging.v2.MetricsServiceV2", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { "serviceName": "google.logging.v2.MetricsServiceV2", "credentialsType": None, - } + }, ) - async def _list_log_metrics(self, - request: Optional[Union[logging_metrics.ListLogMetricsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLogMetricsAsyncPager: + async def _list_log_metrics( + self, + request: Optional[Union[logging_metrics.ListLogMetricsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogMetricsAsyncPager: r"""Lists logs-based metrics. .. code-block:: python @@ -329,10 +374,14 @@ async def sample_list_log_metrics(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -346,14 +395,14 @@ async def sample_list_log_metrics(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_log_metrics] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_log_metrics + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -381,14 +430,15 @@ async def sample_list_log_metrics(): # Done; return the response. return response - async def _get_log_metric(self, - request: Optional[Union[logging_metrics.GetLogMetricRequest, dict]] = None, - *, - metric_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_metrics.LogMetric: + async def _get_log_metric( + self, + request: Optional[Union[logging_metrics.GetLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: r"""Gets a logs-based metric. .. code-block:: python @@ -458,10 +508,14 @@ async def sample_get_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [metric_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -475,14 +529,16 @@ async def sample_get_log_metric(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_log_metric] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_log_metric + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("metric_name", request.metric_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("metric_name", request.metric_name),) + ), ) # Validate the universe domain. @@ -499,15 +555,16 @@ async def sample_get_log_metric(): # Done; return the response. return response - async def _create_log_metric(self, - request: Optional[Union[logging_metrics.CreateLogMetricRequest, dict]] = None, - *, - parent: Optional[str] = None, - metric: Optional[logging_metrics.LogMetric] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_metrics.LogMetric: + async def _create_log_metric( + self, + request: Optional[Union[logging_metrics.CreateLogMetricRequest, dict]] = None, + *, + parent: Optional[str] = None, + metric: Optional[logging_metrics.LogMetric] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: r"""Creates a logs-based metric. .. code-block:: python @@ -593,10 +650,14 @@ async def sample_create_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, metric] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -612,14 +673,14 @@ async def sample_create_log_metric(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_log_metric] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_log_metric + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -636,15 +697,16 @@ async def sample_create_log_metric(): # Done; return the response. return response - async def _update_log_metric(self, - request: Optional[Union[logging_metrics.UpdateLogMetricRequest, dict]] = None, - *, - metric_name: Optional[str] = None, - metric: Optional[logging_metrics.LogMetric] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_metrics.LogMetric: + async def _update_log_metric( + self, + request: Optional[Union[logging_metrics.UpdateLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + metric: Optional[logging_metrics.LogMetric] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: r"""Creates or updates a logs-based metric. .. code-block:: python @@ -729,10 +791,14 @@ async def sample_update_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [metric_name, metric] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -748,14 +814,16 @@ async def sample_update_log_metric(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_log_metric] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_log_metric + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("metric_name", request.metric_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("metric_name", request.metric_name),) + ), ) # Validate the universe domain. @@ -772,14 +840,15 @@ async def sample_update_log_metric(): # Done; return the response. return response - async def _delete_log_metric(self, - request: Optional[Union[logging_metrics.DeleteLogMetricRequest, dict]] = None, - *, - metric_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def _delete_log_metric( + self, + request: Optional[Union[logging_metrics.DeleteLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a logs-based metric. .. code-block:: python @@ -830,10 +899,14 @@ async def sample_delete_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [metric_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -847,14 +920,16 @@ async def sample_delete_log_metric(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_log_metric] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_log_metric + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("metric_name", request.metric_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("metric_name", request.metric_name),) + ), ) # Validate the universe domain. @@ -910,8 +985,7 @@ async def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -919,7 +993,11 @@ async def list_operations( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -966,8 +1044,7 @@ async def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -975,7 +1052,11 @@ async def get_operation( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1025,15 +1106,19 @@ async def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) async def __aenter__(self) -> "BaseMetricsServiceV2AsyncClient": return self @@ -1041,12 +1126,13 @@ async def __aenter__(self) -> "BaseMetricsServiceV2AsyncClient": async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "BaseMetricsServiceV2AsyncClient", -) +__all__ = ("BaseMetricsServiceV2AsyncClient",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py index 8858b82cf772..51009084c54c 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py @@ -19,7 +19,19 @@ import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +from typing import ( + Dict, + Callable, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) import warnings from google.cloud.logging_v2 import gapic_version as package_version @@ -28,11 +40,11 @@ from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.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.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 import google.protobuf try: @@ -42,6 +54,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -50,7 +63,7 @@ from google.cloud.logging_v2.services.metrics_service_v2 import pagers from google.cloud.logging_v2.types import logging_metrics -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.api.distribution_pb2 as distribution_pb2 # type: ignore import google.api.metric_pb2 as metric_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore @@ -66,13 +79,17 @@ class BaseMetricsServiceV2ClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[MetricsServiceV2Transport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[MetricsServiceV2Transport]] _transport_registry["grpc"] = MetricsServiceV2GrpcTransport _transport_registry["grpc_asyncio"] = MetricsServiceV2GrpcAsyncIOTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[MetricsServiceV2Transport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[MetricsServiceV2Transport]: """Returns an appropriate transport class. Args: @@ -148,14 +165,16 @@ def _use_client_cert_effective(): bool: whether client certificate should be used for mTLS Raises: ValueError: (If using a version of google-auth without should_use_client_cert and - GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) """ # check if google-auth version supports should_use_client_cert for automatic mTLS enablement if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER return mtls.should_use_client_cert() - else: # pragma: NO COVER + else: # pragma: NO COVER # if unsupported, fallback to reading from env var - use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() if use_client_cert_str not in ("true", "false"): raise ValueError( "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" @@ -194,8 +213,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: BaseMetricsServiceV2Client: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -212,73 +230,103 @@ def transport(self) -> MetricsServiceV2Transport: return self._transport @staticmethod - def log_metric_path(project: str,metric: str,) -> str: + def log_metric_path( + project: str, + metric: str, + ) -> str: """Returns a fully-qualified log_metric string.""" - return "projects/{project}/metrics/{metric}".format(project=project, metric=metric, ) + return "projects/{project}/metrics/{metric}".format( + project=project, + metric=metric, + ) @staticmethod - def parse_log_metric_path(path: str) -> Dict[str,str]: + def parse_log_metric_path(path: str) -> Dict[str, str]: """Parses a log_metric path into its component segments.""" m = re.match(r"^projects/(?P.+?)/metrics/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + def common_billing_account_path( + billing_account: str, + ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path(folder: str, ) -> str: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path(organization: str, ) -> str: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path(project: str, ) -> str: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path(project: str, location: str, ) -> str: + def common_location_path( + project: str, + location: str, + ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -310,14 +358,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = BaseMetricsServiceV2Client._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Figure out the client cert source to use. client_cert_source = None @@ -330,7 +382,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): api_endpoint = cls.DEFAULT_MTLS_ENDPOINT else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -355,7 +409,9 @@ def _read_environment_variables(): use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod @@ -378,7 +434,9 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: """Return the API endpoint used by the client. Args: @@ -394,17 +452,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): _default_universe = BaseMetricsServiceV2Client._DEFAULT_UNIVERSE if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) api_endpoint = BaseMetricsServiceV2Client.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = BaseMetricsServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = BaseMetricsServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) return api_endpoint @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: """Return the universe domain used by the client. Args: @@ -440,15 +506,18 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError + self, error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: return cred = self._transport._credentials @@ -481,12 +550,18 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, MetricsServiceV2Transport, Callable[..., MetricsServiceV2Transport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, MetricsServiceV2Transport, Callable[..., MetricsServiceV2Transport] + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the base metrics service v2 client. Args: @@ -541,13 +616,23 @@ def __init__(self, *, self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = BaseMetricsServiceV2Client._read_environment_variables() - self._client_cert_source = BaseMetricsServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = BaseMetricsServiceV2Client._get_universe_domain(universe_domain_opt, self._universe_domain_env) + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = BaseMetricsServiceV2Client._read_environment_variables() + self._client_cert_source = BaseMetricsServiceV2Client._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = BaseMetricsServiceV2Client._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -559,7 +644,9 @@ def __init__(self, *, api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -568,8 +655,10 @@ def __init__(self, *, if transport_provided: # transport is a MetricsServiceV2Transport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if self._client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes " @@ -578,20 +667,30 @@ def __init__(self, *, self._transport = cast(MetricsServiceV2Transport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - BaseMetricsServiceV2Client._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or BaseMetricsServiceV2Client._get_api_endpoint( self._client_options.api_endpoint, self._client_cert_source, self._universe_domain, - self._use_mtls_endpoint)) + self._use_mtls_endpoint, + ) + ) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) - transport_init: Union[Type[MetricsServiceV2Transport], Callable[..., MetricsServiceV2Transport]] = ( + transport_init: Union[ + Type[MetricsServiceV2Transport], + Callable[..., MetricsServiceV2Transport], + ] = ( BaseMetricsServiceV2Client.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., MetricsServiceV2Transport], transport) @@ -610,28 +709,37 @@ def __init__(self, *, ) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.logging_v2.BaseMetricsServiceV2Client`.", - extra = { + extra={ "serviceName": "google.logging.v2.MetricsServiceV2", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { "serviceName": "google.logging.v2.MetricsServiceV2", "credentialsType": None, - } + }, ) - def _list_log_metrics(self, - request: Optional[Union[logging_metrics.ListLogMetricsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListLogMetricsPager: + def _list_log_metrics( + self, + request: Optional[Union[logging_metrics.ListLogMetricsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListLogMetricsPager: r"""Lists logs-based metrics. .. code-block:: python @@ -696,10 +804,14 @@ def sample_list_log_metrics(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -717,9 +829,7 @@ def sample_list_log_metrics(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -747,14 +857,15 @@ def sample_list_log_metrics(): # Done; return the response. return response - def _get_log_metric(self, - request: Optional[Union[logging_metrics.GetLogMetricRequest, dict]] = None, - *, - metric_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_metrics.LogMetric: + def _get_log_metric( + self, + request: Optional[Union[logging_metrics.GetLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: r"""Gets a logs-based metric. .. code-block:: python @@ -824,10 +935,14 @@ def sample_get_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [metric_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -845,9 +960,9 @@ def sample_get_log_metric(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("metric_name", request.metric_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("metric_name", request.metric_name),) + ), ) # Validate the universe domain. @@ -864,15 +979,16 @@ def sample_get_log_metric(): # Done; return the response. return response - def _create_log_metric(self, - request: Optional[Union[logging_metrics.CreateLogMetricRequest, dict]] = None, - *, - parent: Optional[str] = None, - metric: Optional[logging_metrics.LogMetric] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_metrics.LogMetric: + def _create_log_metric( + self, + request: Optional[Union[logging_metrics.CreateLogMetricRequest, dict]] = None, + *, + parent: Optional[str] = None, + metric: Optional[logging_metrics.LogMetric] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: r"""Creates a logs-based metric. .. code-block:: python @@ -958,10 +1074,14 @@ def sample_create_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, metric] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -981,9 +1101,7 @@ def sample_create_log_metric(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1000,15 +1118,16 @@ def sample_create_log_metric(): # Done; return the response. return response - def _update_log_metric(self, - request: Optional[Union[logging_metrics.UpdateLogMetricRequest, dict]] = None, - *, - metric_name: Optional[str] = None, - metric: Optional[logging_metrics.LogMetric] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> logging_metrics.LogMetric: + def _update_log_metric( + self, + request: Optional[Union[logging_metrics.UpdateLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + metric: Optional[logging_metrics.LogMetric] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> logging_metrics.LogMetric: r"""Creates or updates a logs-based metric. .. code-block:: python @@ -1093,10 +1212,14 @@ def sample_update_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [metric_name, metric] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1116,9 +1239,9 @@ def sample_update_log_metric(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("metric_name", request.metric_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("metric_name", request.metric_name),) + ), ) # Validate the universe domain. @@ -1135,14 +1258,15 @@ def sample_update_log_metric(): # Done; return the response. return response - def _delete_log_metric(self, - request: Optional[Union[logging_metrics.DeleteLogMetricRequest, dict]] = None, - *, - metric_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def _delete_log_metric( + self, + request: Optional[Union[logging_metrics.DeleteLogMetricRequest, dict]] = None, + *, + metric_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a logs-based metric. .. code-block:: python @@ -1193,10 +1317,14 @@ def sample_delete_log_metric(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [metric_name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1214,9 +1342,9 @@ def sample_delete_log_metric(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("metric_name", request.metric_name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("metric_name", request.metric_name),) + ), ) # Validate the universe domain. @@ -1285,8 +1413,7 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1295,7 +1422,11 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1345,8 +1476,7 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1355,7 +1485,11 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1408,27 +1542,26 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) - - - - - + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "BaseMetricsServiceV2Client", -) +__all__ = ("BaseMetricsServiceV2Client",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py index 61d6698cc33a..285fcc1f7017 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py @@ -24,14 +24,16 @@ from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf from google.cloud.logging_v2.types import logging_metrics -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ @@ -41,27 +43,28 @@ class MetricsServiceV2Transport(abc.ABC): """Abstract transport class for MetricsServiceV2.""" AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write', + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/logging.admin", + "https://www.googleapis.com/auth/logging.read", + "https://www.googleapis.com/auth/logging.write", ) - DEFAULT_HOST: str = 'logging.googleapis.com' + DEFAULT_HOST: str = "logging.googleapis.com" def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -100,31 +103,43 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host self._wrapped_methods: Dict[Callable, Callable] = {} @@ -220,60 +235,63 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @property - def list_log_metrics(self) -> Callable[ - [logging_metrics.ListLogMetricsRequest], - Union[ - logging_metrics.ListLogMetricsResponse, - Awaitable[logging_metrics.ListLogMetricsResponse] - ]]: + def list_log_metrics( + self, + ) -> Callable[ + [logging_metrics.ListLogMetricsRequest], + Union[ + logging_metrics.ListLogMetricsResponse, + Awaitable[logging_metrics.ListLogMetricsResponse], + ], + ]: raise NotImplementedError() @property - def get_log_metric(self) -> Callable[ - [logging_metrics.GetLogMetricRequest], - Union[ - logging_metrics.LogMetric, - Awaitable[logging_metrics.LogMetric] - ]]: + def get_log_metric( + self, + ) -> Callable[ + [logging_metrics.GetLogMetricRequest], + Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]], + ]: raise NotImplementedError() @property - def create_log_metric(self) -> Callable[ - [logging_metrics.CreateLogMetricRequest], - Union[ - logging_metrics.LogMetric, - Awaitable[logging_metrics.LogMetric] - ]]: + def create_log_metric( + self, + ) -> Callable[ + [logging_metrics.CreateLogMetricRequest], + Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]], + ]: raise NotImplementedError() @property - def update_log_metric(self) -> Callable[ - [logging_metrics.UpdateLogMetricRequest], - Union[ - logging_metrics.LogMetric, - Awaitable[logging_metrics.LogMetric] - ]]: + def update_log_metric( + self, + ) -> Callable[ + [logging_metrics.UpdateLogMetricRequest], + Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]], + ]: raise NotImplementedError() @property - def delete_log_metric(self) -> Callable[ - [logging_metrics.DeleteLogMetricRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_log_metric( + self, + ) -> Callable[ + [logging_metrics.DeleteLogMetricRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property @@ -281,7 +299,10 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], ]: raise NotImplementedError() @@ -297,10 +318,7 @@ def get_operation( @property def cancel_operation( self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: raise NotImplementedError() @property @@ -308,6 +326,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'MetricsServiceV2Transport', -) +__all__ = ("MetricsServiceV2Transport",) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/setup.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/setup.py index 0c230d719cdd..b2cf12496bc3 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/setup.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/setup.py @@ -17,23 +17,23 @@ import os import re -import setuptools # type: ignore +import setuptools # type: ignore package_root = os.path.abspath(os.path.dirname(__file__)) -name = 'google-cloud-logging' +name = "google-cloud-logging" description = "Google Cloud Logging API client library" version = None -with open(os.path.join(package_root, 'google/cloud/logging/gapic_version.py')) as fp: +with open(os.path.join(package_root, "google/cloud/logging/gapic_version.py")) as fp: version_candidates = re.findall( r"(?<=\")\d+\.\d+\.\d+[^\"\s]*(?=\")", fp.read(), ) - assert (len(version_candidates) == 1) + assert len(version_candidates) == 1 version = version_candidates[0] if version[0] == "0": @@ -51,8 +51,7 @@ "proto-plus >= 1.26.1, <2.0.0", "protobuf >= 6.33.5, < 8.0.0", ] -extras = { -} +extras = {} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-logging" package_root = os.path.abspath(os.path.dirname(__file__)) diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/__init__.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/__init__.py index c2897c61e9d7..acc5d339b6ca 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/__init__.py @@ -54,10 +54,12 @@ from .types.cloud_redis import WeeklyMaintenanceWindow from .types.cloud_redis import ZoneMetadata -if hasattr(api_core, "check_python_version") and hasattr(api_core, "check_dependency_versions"): # pragma: NO COVER - api_core.check_python_version("google.cloud.redis_v1") # type: ignore - api_core.check_dependency_versions("google.cloud.redis_v1") # type: ignore -else: # pragma: NO COVER +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.cloud.redis_v1") # type: ignore + api_core.check_dependency_versions("google.cloud.redis_v1") # type: ignore +else: # pragma: NO COVER # An older version of api_core is installed which does not define the # functions above. We do equivalent checks manually. try: @@ -66,12 +68,14 @@ _py_version_str = sys.version.split()[0] _package_label = "google.cloud.redis_v1" if sys.version_info < (3, 10): - warnings.warn("You are using a non-supported Python version " + - f"({_py_version_str}). Google will not post any further " + - f"updates to {_package_label} supporting this Python version. " + - "Please upgrade to the latest Python version, or at " + - f"least to Python 3.10, and then update {_package_label}.", - FutureWarning) + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.10, and then update {_package_label}.", + FutureWarning, + ) def parse_version_to_tuple(version_string: str): """Safely converts a semantic version string to a comparable tuple of integers. @@ -109,54 +113,58 @@ def _get_version(dependency_name): _recommendation = " (we recommend 7.x)" (_version_used, _version_used_string) = _get_version(_dependency_package) if _version_used and _version_used < _next_supported_version_tuple: - warnings.warn(f"Package {_package_label} depends on " + - f"{_dependency_package}, currently installed at version " + - f"{_version_used_string}. Future updates to " + - f"{_package_label} will require {_dependency_package} at " + - f"version {_next_supported_version} or higher{_recommendation}." + - " Please ensure " + - "that either (a) your Python environment doesn't pin the " + - f"version of {_dependency_package}, so that updates to " + - f"{_package_label} can require the higher version, or " + - "(b) you manually update your Python environment to use at " + - f"least version {_next_supported_version} of " + - f"{_dependency_package}.", - FutureWarning) + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) except Exception: - warnings.warn("Could not determine the version of Python " + - "currently being used. To continue receiving " + - "updates for {_package_label}, ensure you are " + - "using a supported version of Python; see " + - "https://devguide.python.org/versions/") + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) __all__ = ( - 'CloudRedisAsyncClient', -'CloudRedisClient', -'CreateInstanceRequest', -'DeleteInstanceRequest', -'ExportInstanceRequest', -'FailoverInstanceRequest', -'GcsDestination', -'GcsSource', -'GetInstanceAuthStringRequest', -'GetInstanceRequest', -'ImportInstanceRequest', -'InputConfig', -'Instance', -'InstanceAuthString', -'ListInstancesRequest', -'ListInstancesResponse', -'LocationMetadata', -'MaintenancePolicy', -'MaintenanceSchedule', -'NodeInfo', -'OperationMetadata', -'OutputConfig', -'PersistenceConfig', -'RescheduleMaintenanceRequest', -'TlsCertificate', -'UpdateInstanceRequest', -'UpgradeInstanceRequest', -'WeeklyMaintenanceWindow', -'ZoneMetadata', + "CloudRedisAsyncClient", + "CloudRedisClient", + "CreateInstanceRequest", + "DeleteInstanceRequest", + "ExportInstanceRequest", + "FailoverInstanceRequest", + "GcsDestination", + "GcsSource", + "GetInstanceAuthStringRequest", + "GetInstanceRequest", + "ImportInstanceRequest", + "InputConfig", + "Instance", + "InstanceAuthString", + "ListInstancesRequest", + "ListInstancesResponse", + "LocationMetadata", + "MaintenancePolicy", + "MaintenanceSchedule", + "NodeInfo", + "OperationMetadata", + "OutputConfig", + "PersistenceConfig", + "RescheduleMaintenanceRequest", + "TlsCertificate", + "UpdateInstanceRequest", + "UpgradeInstanceRequest", + "WeeklyMaintenanceWindow", + "ZoneMetadata", ) diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/async_client.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/async_client.py index d495b8d496ac..1c5ab4bf0c69 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/async_client.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/async_client.py @@ -16,7 +16,18 @@ import logging as std_logging from collections import OrderedDict import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union +from typing import ( + Dict, + Callable, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) from google.cloud.redis_v1 import gapic_version as package_version @@ -24,8 +35,8 @@ from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf @@ -34,10 +45,10 @@ except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore -from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.cloud.redis_v1.services.cloud_redis import pagers from google.cloud.redis_v1.types import cloud_redis -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.api_core.operation as operation # type: ignore import google.api_core.operation_async as operation_async # type: ignore import google.protobuf.empty_pb2 as empty_pb2 # type: ignore @@ -49,12 +60,14 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) + class CloudRedisAsyncClient: """Configures and manages Cloud Memorystore for Redis instances @@ -90,16 +103,24 @@ class CloudRedisAsyncClient: instance_path = staticmethod(CloudRedisClient.instance_path) parse_instance_path = staticmethod(CloudRedisClient.parse_instance_path) - common_billing_account_path = staticmethod(CloudRedisClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CloudRedisClient.parse_common_billing_account_path) + common_billing_account_path = staticmethod( + CloudRedisClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + CloudRedisClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(CloudRedisClient.common_folder_path) parse_common_folder_path = staticmethod(CloudRedisClient.parse_common_folder_path) common_organization_path = staticmethod(CloudRedisClient.common_organization_path) - parse_common_organization_path = staticmethod(CloudRedisClient.parse_common_organization_path) + parse_common_organization_path = staticmethod( + CloudRedisClient.parse_common_organization_path + ) common_project_path = staticmethod(CloudRedisClient.common_project_path) parse_common_project_path = staticmethod(CloudRedisClient.parse_common_project_path) common_location_path = staticmethod(CloudRedisClient.common_location_path) - parse_common_location_path = staticmethod(CloudRedisClient.parse_common_location_path) + parse_common_location_path = staticmethod( + CloudRedisClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -141,7 +162,9 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): """Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -204,12 +227,16 @@ def universe_domain(self) -> str: get_transport_class = CloudRedisClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, CloudRedisTransport, Callable[..., CloudRedisTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, CloudRedisTransport, Callable[..., CloudRedisTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the cloud redis async client. Args: @@ -267,31 +294,39 @@ def __init__(self, *, transport=transport, client_options=client_options, client_info=client_info, - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.redis_v1.CloudRedisAsyncClient`.", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { "serviceName": "google.cloud.redis.v1.CloudRedis", "credentialsType": None, - } + }, ) - async def list_instances(self, - request: Optional[Union[cloud_redis.ListInstancesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListInstancesAsyncPager: + async def list_instances( + self, + request: Optional[Union[cloud_redis.ListInstancesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListInstancesAsyncPager: r"""Lists all Redis instances owned by a project in either the specified location (region) or all locations. @@ -364,10 +399,14 @@ async def sample_list_instances(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -381,14 +420,14 @@ async def sample_list_instances(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_instances] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_instances + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -416,14 +455,15 @@ async def sample_list_instances(): # Done; return the response. return response - async def get_instance(self, - request: Optional[Union[cloud_redis.GetInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> cloud_redis.Instance: + async def get_instance( + self, + request: Optional[Union[cloud_redis.GetInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_redis.Instance: r"""Gets the details of a specific Redis instance. .. code-block:: python @@ -480,10 +520,14 @@ async def sample_get_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -497,14 +541,14 @@ async def sample_get_instance(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_instance] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_instance + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -521,14 +565,15 @@ async def sample_get_instance(): # Done; return the response. return response - async def get_instance_auth_string(self, - request: Optional[Union[cloud_redis.GetInstanceAuthStringRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> cloud_redis.InstanceAuthString: + async def get_instance_auth_string( + self, + request: Optional[Union[cloud_redis.GetInstanceAuthStringRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_redis.InstanceAuthString: r"""Gets the AUTH string for a Redis instance. If AUTH is not enabled for the instance the response will be empty. This information is not included in the details returned @@ -588,10 +633,14 @@ async def sample_get_instance_auth_string(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -605,14 +654,14 @@ async def sample_get_instance_auth_string(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_instance_auth_string] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_instance_auth_string + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -629,16 +678,17 @@ async def sample_get_instance_auth_string(): # Done; return the response. return response - async def create_instance(self, - request: Optional[Union[cloud_redis.CreateInstanceRequest, dict]] = None, - *, - parent: Optional[str] = None, - instance_id: Optional[str] = None, - instance: Optional[cloud_redis.Instance] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def create_instance( + self, + request: Optional[Union[cloud_redis.CreateInstanceRequest, dict]] = None, + *, + parent: Optional[str] = None, + instance_id: Optional[str] = None, + instance: Optional[cloud_redis.Instance] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Creates a Redis instance based on the specified tier and memory size. @@ -744,10 +794,14 @@ async def sample_create_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, instance_id, instance] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -765,14 +819,14 @@ async def sample_create_instance(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_instance] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_instance + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -797,15 +851,16 @@ async def sample_create_instance(): # Done; return the response. return response - async def update_instance(self, - request: Optional[Union[cloud_redis.UpdateInstanceRequest, dict]] = None, - *, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - instance: Optional[cloud_redis.Instance] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def update_instance( + self, + request: Optional[Union[cloud_redis.UpdateInstanceRequest, dict]] = None, + *, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + instance: Optional[cloud_redis.Instance] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Updates the metadata and configuration of a specific Redis instance. Completed longrunning.Operation will contain the new @@ -895,10 +950,14 @@ async def sample_update_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [update_mask, instance] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -914,14 +973,16 @@ async def sample_update_instance(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_instance] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_instance + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("instance.name", request.instance.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("instance.name", request.instance.name),) + ), ) # Validate the universe domain. @@ -946,15 +1007,16 @@ async def sample_update_instance(): # Done; return the response. return response - async def upgrade_instance(self, - request: Optional[Union[cloud_redis.UpgradeInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - redis_version: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def upgrade_instance( + self, + request: Optional[Union[cloud_redis.UpgradeInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + redis_version: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Upgrades Redis instance to the newer Redis version specified in the request. @@ -1029,10 +1091,14 @@ async def sample_upgrade_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, redis_version] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1048,14 +1114,14 @@ async def sample_upgrade_instance(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.upgrade_instance] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.upgrade_instance + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1080,15 +1146,16 @@ async def sample_upgrade_instance(): # Done; return the response. return response - async def import_instance(self, - request: Optional[Union[cloud_redis.ImportInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - input_config: Optional[cloud_redis.InputConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def import_instance( + self, + request: Optional[Union[cloud_redis.ImportInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + input_config: Optional[cloud_redis.InputConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Import a Redis RDB snapshot file from Cloud Storage into a Redis instance. Redis may stop serving during this operation. Instance @@ -1173,10 +1240,14 @@ async def sample_import_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, input_config] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1192,14 +1263,14 @@ async def sample_import_instance(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.import_instance] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.import_instance + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1224,15 +1295,16 @@ async def sample_import_instance(): # Done; return the response. return response - async def export_instance(self, - request: Optional[Union[cloud_redis.ExportInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - output_config: Optional[cloud_redis.OutputConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def export_instance( + self, + request: Optional[Union[cloud_redis.ExportInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + output_config: Optional[cloud_redis.OutputConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Export Redis instance data into a Redis RDB format file in Cloud Storage. Redis will continue serving during this operation. @@ -1314,10 +1386,14 @@ async def sample_export_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, output_config] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1333,14 +1409,14 @@ async def sample_export_instance(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.export_instance] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.export_instance + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1365,15 +1441,18 @@ async def sample_export_instance(): # Done; return the response. return response - async def failover_instance(self, - request: Optional[Union[cloud_redis.FailoverInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - data_protection_mode: Optional[cloud_redis.FailoverInstanceRequest.DataProtectionMode] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def failover_instance( + self, + request: Optional[Union[cloud_redis.FailoverInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + data_protection_mode: Optional[ + cloud_redis.FailoverInstanceRequest.DataProtectionMode + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Initiates a failover of the primary node to current replica node for a specific STANDARD tier Cloud Memorystore for Redis instance. @@ -1449,10 +1528,14 @@ async def sample_failover_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, data_protection_mode] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1468,14 +1551,14 @@ async def sample_failover_instance(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.failover_instance] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.failover_instance + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1500,14 +1583,15 @@ async def sample_failover_instance(): # Done; return the response. return response - async def delete_instance(self, - request: Optional[Union[cloud_redis.DeleteInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def delete_instance( + self, + request: Optional[Union[cloud_redis.DeleteInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Deletes a specific Redis instance. Instance stops serving and data is deleted. @@ -1581,10 +1665,14 @@ async def sample_delete_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1598,14 +1686,14 @@ async def sample_delete_instance(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_instance] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_instance + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1630,16 +1718,19 @@ async def sample_delete_instance(): # Done; return the response. return response - async def reschedule_maintenance(self, - request: Optional[Union[cloud_redis.RescheduleMaintenanceRequest, dict]] = None, - *, - name: Optional[str] = None, - reschedule_type: Optional[cloud_redis.RescheduleMaintenanceRequest.RescheduleType] = None, - schedule_time: Optional[timestamp_pb2.Timestamp] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def reschedule_maintenance( + self, + request: Optional[Union[cloud_redis.RescheduleMaintenanceRequest, dict]] = None, + *, + name: Optional[str] = None, + reschedule_type: Optional[ + cloud_redis.RescheduleMaintenanceRequest.RescheduleType + ] = None, + schedule_time: Optional[timestamp_pb2.Timestamp] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Reschedule maintenance for a given instance in a given project and location. @@ -1722,10 +1813,14 @@ async def sample_reschedule_maintenance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, reschedule_type, schedule_time] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1743,14 +1838,14 @@ async def sample_reschedule_maintenance(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.reschedule_maintenance] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.reschedule_maintenance + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1817,8 +1912,7 @@ async def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1826,7 +1920,11 @@ async def list_operations( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1873,8 +1971,7 @@ async def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1882,7 +1979,11 @@ async def get_operation( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1933,15 +2034,19 @@ async def delete_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) async def cancel_operation( self, @@ -1988,15 +2093,19 @@ async def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) async def wait_operation( self, @@ -2046,8 +2155,7 @@ async def wait_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -2055,7 +2163,11 @@ async def wait_operation( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -2102,8 +2214,7 @@ async def get_location( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -2111,7 +2222,11 @@ async def get_location( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -2158,8 +2273,7 @@ async def list_locations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -2167,7 +2281,11 @@ async def list_locations( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -2178,12 +2296,13 @@ async def __aenter__(self) -> "CloudRedisAsyncClient": async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "CloudRedisAsyncClient", -) +__all__ = ("CloudRedisAsyncClient",) diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py index 41866d187d28..edce80271466 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py @@ -19,7 +19,19 @@ import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +from typing import ( + Dict, + Callable, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) import warnings from google.cloud.redis_v1 import gapic_version as package_version @@ -28,11 +40,11 @@ from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.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.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 import google.protobuf try: @@ -42,16 +54,17 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) -from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.cloud.redis_v1.services.cloud_redis import pagers from google.cloud.redis_v1.types import cloud_redis -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.api_core.operation as operation # type: ignore import google.api_core.operation_async as operation_async # type: ignore import google.protobuf.empty_pb2 as empty_pb2 # type: ignore @@ -61,11 +74,13 @@ from .transports.grpc import CloudRedisGrpcTransport from .transports.grpc_asyncio import CloudRedisGrpcAsyncIOTransport from .transports.rest import CloudRedisRestTransport + ASYNC_REST_EXCEPTION = None try: from .transports.rest_asyncio import AsyncCloudRedisRestTransport + HAS_ASYNC_REST_DEPENDENCIES = True -except ImportError as e: # pragma: NO COVER +except ImportError as e: # pragma: NO COVER HAS_ASYNC_REST_DEPENDENCIES = False ASYNC_REST_EXCEPTION = e @@ -77,6 +92,7 @@ class CloudRedisClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ + _transport_registry = OrderedDict() # type: Dict[str, Type[CloudRedisTransport]] _transport_registry["grpc"] = CloudRedisGrpcTransport _transport_registry["grpc_asyncio"] = CloudRedisGrpcAsyncIOTransport @@ -84,9 +100,10 @@ class CloudRedisClientMeta(type): if HAS_ASYNC_REST_DEPENDENCIES: # pragma: NO COVER _transport_registry["rest_asyncio"] = AsyncCloudRedisRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[CloudRedisTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[CloudRedisTransport]: """Returns an appropriate transport class. Args: @@ -97,7 +114,9 @@ def get_transport_class(cls, The transport class to use. """ # If a specific transport is requested, return that one. - if label == "rest_asyncio" and not HAS_ASYNC_REST_DEPENDENCIES: # pragma: NO COVER + if ( + label == "rest_asyncio" and not HAS_ASYNC_REST_DEPENDENCIES + ): # pragma: NO COVER raise ASYNC_REST_EXCEPTION if label: return cls._transport_registry[label] @@ -185,14 +204,16 @@ def _use_client_cert_effective(): bool: whether client certificate should be used for mTLS Raises: ValueError: (If using a version of google-auth without should_use_client_cert and - GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) """ # check if google-auth version supports should_use_client_cert for automatic mTLS enablement if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER return mtls.should_use_client_cert() - else: # pragma: NO COVER + else: # pragma: NO COVER # if unsupported, fallback to reading from env var - use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() if use_client_cert_str not in ("true", "false"): raise ValueError( "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" @@ -231,8 +252,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CloudRedisClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -249,73 +269,108 @@ def transport(self) -> CloudRedisTransport: return self._transport @staticmethod - def instance_path(project: str,location: str,instance: str,) -> str: + def instance_path( + project: str, + location: str, + instance: str, + ) -> str: """Returns a fully-qualified instance string.""" - return "projects/{project}/locations/{location}/instances/{instance}".format(project=project, location=location, instance=instance, ) + return "projects/{project}/locations/{location}/instances/{instance}".format( + project=project, + location=location, + instance=instance, + ) @staticmethod - def parse_instance_path(path: str) -> Dict[str,str]: + def parse_instance_path(path: str) -> Dict[str, str]: """Parses a instance path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + def common_billing_account_path( + billing_account: str, + ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path(folder: str, ) -> str: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path(organization: str, ) -> str: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path(project: str, ) -> str: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path(project: str, location: str, ) -> str: + def common_location_path( + project: str, + location: str, + ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -347,14 +402,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = CloudRedisClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Figure out the client cert source to use. client_cert_source = None @@ -367,7 +426,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): api_endpoint = cls.DEFAULT_MTLS_ENDPOINT else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -392,7 +453,9 @@ def _read_environment_variables(): use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod @@ -415,7 +478,9 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: """Return the API endpoint used by the client. Args: @@ -431,17 +496,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): _default_universe = CloudRedisClient._DEFAULT_UNIVERSE if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) api_endpoint = CloudRedisClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = CloudRedisClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = CloudRedisClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) return api_endpoint @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: """Return the universe domain used by the client. Args: @@ -477,15 +550,18 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError + self, error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: return cred = self._transport._credentials @@ -518,12 +594,16 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, CloudRedisTransport, Callable[..., CloudRedisTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, CloudRedisTransport, Callable[..., CloudRedisTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the cloud redis client. Args: @@ -581,13 +661,23 @@ def __init__(self, *, self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = CloudRedisClient._read_environment_variables() - self._client_cert_source = CloudRedisClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = CloudRedisClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = CloudRedisClient._read_environment_variables() + self._client_cert_source = CloudRedisClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = CloudRedisClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -599,7 +689,9 @@ def __init__(self, *, api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -608,8 +700,10 @@ def __init__(self, *, if transport_provided: # transport is a CloudRedisTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if self._client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes " @@ -618,15 +712,17 @@ def __init__(self, *, self._transport = cast(CloudRedisTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - CloudRedisClient._get_api_endpoint( - self._client_options.api_endpoint, - self._client_cert_source, - self._universe_domain, - self._use_mtls_endpoint)) + self._api_endpoint = self._api_endpoint or CloudRedisClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) if not transport_provided: - transport_init: Union[Type[CloudRedisTransport], Callable[..., CloudRedisTransport]] = ( + transport_init: Union[ + Type[CloudRedisTransport], Callable[..., CloudRedisTransport] + ] = ( CloudRedisClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., CloudRedisTransport], transport) @@ -639,9 +735,12 @@ def __init__(self, *, "google.api_core.client_options.ClientOptions.quota_project_id": self._client_options.quota_project_id, "google.api_core.client_options.ClientOptions.client_cert_source": self._client_options.client_cert_source, "google.api_core.client_options.ClientOptions.api_audience": self._client_options.api_audience, - } - provided_unsupported_params = [name for name, value in unsupported_params.items() if value is not None] + provided_unsupported_params = [ + name + for name, value in unsupported_params.items() + if value is not None + ] if provided_unsupported_params: raise core_exceptions.AsyncRestUnsupportedParameterError( # type: ignore f"The following provided parameters are not supported for `transport=rest_asyncio`: {', '.join(provided_unsupported_params)}" @@ -655,8 +754,12 @@ def __init__(self, *, import google.auth._default # type: ignore - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) # initialize with the provided callable or the passed in class self._transport = transport_init( @@ -672,28 +775,37 @@ def __init__(self, *, ) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.redis_v1.CloudRedisClient`.", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { "serviceName": "google.cloud.redis.v1.CloudRedis", "credentialsType": None, - } + }, ) - def list_instances(self, - request: Optional[Union[cloud_redis.ListInstancesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListInstancesPager: + def list_instances( + self, + request: Optional[Union[cloud_redis.ListInstancesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListInstancesPager: r"""Lists all Redis instances owned by a project in either the specified location (region) or all locations. @@ -766,10 +878,14 @@ def sample_list_instances(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -787,9 +903,7 @@ def sample_list_instances(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -817,14 +931,15 @@ def sample_list_instances(): # Done; return the response. return response - def get_instance(self, - request: Optional[Union[cloud_redis.GetInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> cloud_redis.Instance: + def get_instance( + self, + request: Optional[Union[cloud_redis.GetInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_redis.Instance: r"""Gets the details of a specific Redis instance. .. code-block:: python @@ -881,10 +996,14 @@ def sample_get_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -902,9 +1021,7 @@ def sample_get_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -921,14 +1038,15 @@ def sample_get_instance(): # Done; return the response. return response - def get_instance_auth_string(self, - request: Optional[Union[cloud_redis.GetInstanceAuthStringRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> cloud_redis.InstanceAuthString: + def get_instance_auth_string( + self, + request: Optional[Union[cloud_redis.GetInstanceAuthStringRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_redis.InstanceAuthString: r"""Gets the AUTH string for a Redis instance. If AUTH is not enabled for the instance the response will be empty. This information is not included in the details returned @@ -988,10 +1106,14 @@ def sample_get_instance_auth_string(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1009,9 +1131,7 @@ def sample_get_instance_auth_string(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1028,16 +1148,17 @@ def sample_get_instance_auth_string(): # Done; return the response. return response - def create_instance(self, - request: Optional[Union[cloud_redis.CreateInstanceRequest, dict]] = None, - *, - parent: Optional[str] = None, - instance_id: Optional[str] = None, - instance: Optional[cloud_redis.Instance] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_instance( + self, + request: Optional[Union[cloud_redis.CreateInstanceRequest, dict]] = None, + *, + parent: Optional[str] = None, + instance_id: Optional[str] = None, + instance: Optional[cloud_redis.Instance] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Creates a Redis instance based on the specified tier and memory size. @@ -1143,10 +1264,14 @@ def sample_create_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, instance_id, instance] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1168,9 +1293,7 @@ def sample_create_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1195,15 +1318,16 @@ def sample_create_instance(): # Done; return the response. return response - def update_instance(self, - request: Optional[Union[cloud_redis.UpdateInstanceRequest, dict]] = None, - *, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - instance: Optional[cloud_redis.Instance] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_instance( + self, + request: Optional[Union[cloud_redis.UpdateInstanceRequest, dict]] = None, + *, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + instance: Optional[cloud_redis.Instance] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Updates the metadata and configuration of a specific Redis instance. Completed longrunning.Operation will contain the new @@ -1293,10 +1417,14 @@ def sample_update_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [update_mask, instance] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1316,9 +1444,9 @@ def sample_update_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("instance.name", request.instance.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("instance.name", request.instance.name),) + ), ) # Validate the universe domain. @@ -1343,15 +1471,16 @@ def sample_update_instance(): # Done; return the response. return response - def upgrade_instance(self, - request: Optional[Union[cloud_redis.UpgradeInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - redis_version: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def upgrade_instance( + self, + request: Optional[Union[cloud_redis.UpgradeInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + redis_version: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Upgrades Redis instance to the newer Redis version specified in the request. @@ -1426,10 +1555,14 @@ def sample_upgrade_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, redis_version] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1449,9 +1582,7 @@ def sample_upgrade_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1476,15 +1607,16 @@ def sample_upgrade_instance(): # Done; return the response. return response - def import_instance(self, - request: Optional[Union[cloud_redis.ImportInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - input_config: Optional[cloud_redis.InputConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def import_instance( + self, + request: Optional[Union[cloud_redis.ImportInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + input_config: Optional[cloud_redis.InputConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Import a Redis RDB snapshot file from Cloud Storage into a Redis instance. Redis may stop serving during this operation. Instance @@ -1569,10 +1701,14 @@ def sample_import_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, input_config] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1592,9 +1728,7 @@ def sample_import_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1619,15 +1753,16 @@ def sample_import_instance(): # Done; return the response. return response - def export_instance(self, - request: Optional[Union[cloud_redis.ExportInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - output_config: Optional[cloud_redis.OutputConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def export_instance( + self, + request: Optional[Union[cloud_redis.ExportInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + output_config: Optional[cloud_redis.OutputConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Export Redis instance data into a Redis RDB format file in Cloud Storage. Redis will continue serving during this operation. @@ -1709,10 +1844,14 @@ def sample_export_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, output_config] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1732,9 +1871,7 @@ def sample_export_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1759,15 +1896,18 @@ def sample_export_instance(): # Done; return the response. return response - def failover_instance(self, - request: Optional[Union[cloud_redis.FailoverInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - data_protection_mode: Optional[cloud_redis.FailoverInstanceRequest.DataProtectionMode] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def failover_instance( + self, + request: Optional[Union[cloud_redis.FailoverInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + data_protection_mode: Optional[ + cloud_redis.FailoverInstanceRequest.DataProtectionMode + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Initiates a failover of the primary node to current replica node for a specific STANDARD tier Cloud Memorystore for Redis instance. @@ -1843,10 +1983,14 @@ def sample_failover_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, data_protection_mode] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1866,9 +2010,7 @@ def sample_failover_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1893,14 +2035,15 @@ def sample_failover_instance(): # Done; return the response. return response - def delete_instance(self, - request: Optional[Union[cloud_redis.DeleteInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_instance( + self, + request: Optional[Union[cloud_redis.DeleteInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Deletes a specific Redis instance. Instance stops serving and data is deleted. @@ -1974,10 +2117,14 @@ def sample_delete_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1995,9 +2142,7 @@ def sample_delete_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2022,16 +2167,19 @@ def sample_delete_instance(): # Done; return the response. return response - def reschedule_maintenance(self, - request: Optional[Union[cloud_redis.RescheduleMaintenanceRequest, dict]] = None, - *, - name: Optional[str] = None, - reschedule_type: Optional[cloud_redis.RescheduleMaintenanceRequest.RescheduleType] = None, - schedule_time: Optional[timestamp_pb2.Timestamp] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def reschedule_maintenance( + self, + request: Optional[Union[cloud_redis.RescheduleMaintenanceRequest, dict]] = None, + *, + name: Optional[str] = None, + reschedule_type: Optional[ + cloud_redis.RescheduleMaintenanceRequest.RescheduleType + ] = None, + schedule_time: Optional[timestamp_pb2.Timestamp] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Reschedule maintenance for a given instance in a given project and location. @@ -2114,10 +2262,14 @@ def sample_reschedule_maintenance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, reschedule_type, schedule_time] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -2139,9 +2291,7 @@ def sample_reschedule_maintenance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2221,8 +2371,7 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -2231,7 +2380,11 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -2281,8 +2434,7 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -2291,7 +2443,11 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -2345,15 +2501,19 @@ def delete_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) def cancel_operation( self, @@ -2400,15 +2560,19 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) def wait_operation( self, @@ -2458,8 +2622,7 @@ def wait_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -2468,7 +2631,11 @@ def wait_operation( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -2518,8 +2685,7 @@ def get_location( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -2528,7 +2694,11 @@ def get_location( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -2578,8 +2748,7 @@ def list_locations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -2588,7 +2757,11 @@ def list_locations( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -2597,11 +2770,11 @@ def list_locations( raise e -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "CloudRedisClient", -) +__all__ = ("CloudRedisClient",) diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py index b46ab33210ea..8c09c0eed96b 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py @@ -25,14 +25,16 @@ from google.api_core import retry as retries from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf -from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.cloud.redis_v1.types import cloud_redis -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ @@ -41,24 +43,23 @@ class CloudRedisTransport(abc.ABC): """Abstract transport class for CloudRedis.""" - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - DEFAULT_HOST: str = 'redis.googleapis.com' + DEFAULT_HOST: str = "redis.googleapis.com" def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -97,31 +98,43 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host self._wrapped_methods: Dict[Callable, Callable] = {} @@ -223,14 +236,14 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -240,102 +253,107 @@ def operations_client(self): raise NotImplementedError() @property - def list_instances(self) -> Callable[ - [cloud_redis.ListInstancesRequest], - Union[ - cloud_redis.ListInstancesResponse, - Awaitable[cloud_redis.ListInstancesResponse] - ]]: + def list_instances( + self, + ) -> Callable[ + [cloud_redis.ListInstancesRequest], + Union[ + cloud_redis.ListInstancesResponse, + Awaitable[cloud_redis.ListInstancesResponse], + ], + ]: raise NotImplementedError() @property - def get_instance(self) -> Callable[ - [cloud_redis.GetInstanceRequest], - Union[ - cloud_redis.Instance, - Awaitable[cloud_redis.Instance] - ]]: + def get_instance( + self, + ) -> Callable[ + [cloud_redis.GetInstanceRequest], + Union[cloud_redis.Instance, Awaitable[cloud_redis.Instance]], + ]: raise NotImplementedError() @property - def get_instance_auth_string(self) -> Callable[ - [cloud_redis.GetInstanceAuthStringRequest], - Union[ - cloud_redis.InstanceAuthString, - Awaitable[cloud_redis.InstanceAuthString] - ]]: + def get_instance_auth_string( + self, + ) -> Callable[ + [cloud_redis.GetInstanceAuthStringRequest], + Union[ + cloud_redis.InstanceAuthString, Awaitable[cloud_redis.InstanceAuthString] + ], + ]: raise NotImplementedError() @property - def create_instance(self) -> Callable[ - [cloud_redis.CreateInstanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_instance( + self, + ) -> Callable[ + [cloud_redis.CreateInstanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def update_instance(self) -> Callable[ - [cloud_redis.UpdateInstanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def update_instance( + self, + ) -> Callable[ + [cloud_redis.UpdateInstanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def upgrade_instance(self) -> Callable[ - [cloud_redis.UpgradeInstanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def upgrade_instance( + self, + ) -> Callable[ + [cloud_redis.UpgradeInstanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def import_instance(self) -> Callable[ - [cloud_redis.ImportInstanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def import_instance( + self, + ) -> Callable[ + [cloud_redis.ImportInstanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def export_instance(self) -> Callable[ - [cloud_redis.ExportInstanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def export_instance( + self, + ) -> Callable[ + [cloud_redis.ExportInstanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def failover_instance(self) -> Callable[ - [cloud_redis.FailoverInstanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def failover_instance( + self, + ) -> Callable[ + [cloud_redis.FailoverInstanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def delete_instance(self) -> Callable[ - [cloud_redis.DeleteInstanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def delete_instance( + self, + ) -> Callable[ + [cloud_redis.DeleteInstanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def reschedule_maintenance(self) -> Callable[ - [cloud_redis.RescheduleMaintenanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def reschedule_maintenance( + self, + ) -> Callable[ + [cloud_redis.RescheduleMaintenanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property @@ -343,7 +361,10 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], ]: raise NotImplementedError() @@ -359,19 +380,13 @@ def get_operation( @property def cancel_operation( self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: raise NotImplementedError() @property def delete_operation( self, - ) -> Callable[ - [operations_pb2.DeleteOperationRequest], - None, - ]: + ) -> Callable[[operations_pb2.DeleteOperationRequest], None,]: raise NotImplementedError() @property @@ -384,7 +399,8 @@ def wait_operation( raise NotImplementedError() @property - def get_location(self, + def get_location( + self, ) -> Callable[ [locations_pb2.GetLocationRequest], Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], @@ -392,10 +408,14 @@ def get_location(self, raise NotImplementedError() @property - def list_locations(self, + def list_locations( + self, ) -> Callable[ [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], ]: raise NotImplementedError() @@ -404,6 +424,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'CloudRedisTransport', -) +__all__ = ("CloudRedisTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/rest.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/rest.py index d4b8530eb1af..3a2499bf8e2b 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/rest.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/rest.py @@ -27,7 +27,7 @@ from google.protobuf import json_format from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from requests import __version__ as requests_version import dataclasses @@ -49,6 +49,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -173,7 +174,14 @@ def post_upgrade_instance(self, response): """ - def pre_create_instance(self, request: cloud_redis.CreateInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.CreateInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_create_instance( + self, + request: cloud_redis.CreateInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.CreateInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for create_instance Override in a subclass to manipulate the request or metadata @@ -181,7 +189,9 @@ def pre_create_instance(self, request: cloud_redis.CreateInstanceRequest, metada """ return request, metadata - def post_create_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_create_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for create_instance DEPRECATED. Please use the `post_create_instance_with_metadata` @@ -194,7 +204,11 @@ def post_create_instance(self, response: operations_pb2.Operation) -> operations """ return response - def post_create_instance_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_create_instance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for create_instance Override in a subclass to read or manipulate the response or metadata after it @@ -209,7 +223,13 @@ def post_create_instance_with_metadata(self, response: operations_pb2.Operation, """ return response, metadata - def pre_delete_instance(self, request: cloud_redis.DeleteInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.DeleteInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_delete_instance( + self, + request: cloud_redis.DeleteInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.DeleteInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for delete_instance Override in a subclass to manipulate the request or metadata @@ -217,7 +237,9 @@ def pre_delete_instance(self, request: cloud_redis.DeleteInstanceRequest, metada """ return request, metadata - def post_delete_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_delete_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for delete_instance DEPRECATED. Please use the `post_delete_instance_with_metadata` @@ -230,7 +252,11 @@ def post_delete_instance(self, response: operations_pb2.Operation) -> operations """ return response - def post_delete_instance_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_delete_instance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for delete_instance Override in a subclass to read or manipulate the response or metadata after it @@ -245,7 +271,13 @@ def post_delete_instance_with_metadata(self, response: operations_pb2.Operation, """ return response, metadata - def pre_export_instance(self, request: cloud_redis.ExportInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.ExportInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_export_instance( + self, + request: cloud_redis.ExportInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.ExportInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for export_instance Override in a subclass to manipulate the request or metadata @@ -253,7 +285,9 @@ def pre_export_instance(self, request: cloud_redis.ExportInstanceRequest, metada """ return request, metadata - def post_export_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_export_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for export_instance DEPRECATED. Please use the `post_export_instance_with_metadata` @@ -266,7 +300,11 @@ def post_export_instance(self, response: operations_pb2.Operation) -> operations """ return response - def post_export_instance_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_export_instance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for export_instance Override in a subclass to read or manipulate the response or metadata after it @@ -281,7 +319,13 @@ def post_export_instance_with_metadata(self, response: operations_pb2.Operation, """ return response, metadata - def pre_failover_instance(self, request: cloud_redis.FailoverInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.FailoverInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_failover_instance( + self, + request: cloud_redis.FailoverInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.FailoverInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for failover_instance Override in a subclass to manipulate the request or metadata @@ -289,7 +333,9 @@ def pre_failover_instance(self, request: cloud_redis.FailoverInstanceRequest, me """ return request, metadata - def post_failover_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_failover_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for failover_instance DEPRECATED. Please use the `post_failover_instance_with_metadata` @@ -302,7 +348,11 @@ def post_failover_instance(self, response: operations_pb2.Operation) -> operatio """ return response - def post_failover_instance_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_failover_instance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for failover_instance Override in a subclass to read or manipulate the response or metadata after it @@ -317,7 +367,11 @@ def post_failover_instance_with_metadata(self, response: operations_pb2.Operatio """ return response, metadata - def pre_get_instance(self, request: cloud_redis.GetInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.GetInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_get_instance( + self, + request: cloud_redis.GetInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[cloud_redis.GetInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_instance Override in a subclass to manipulate the request or metadata @@ -338,7 +392,11 @@ def post_get_instance(self, response: cloud_redis.Instance) -> cloud_redis.Insta """ return response - def post_get_instance_with_metadata(self, response: cloud_redis.Instance, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.Instance, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_instance_with_metadata( + self, + response: cloud_redis.Instance, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[cloud_redis.Instance, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_instance Override in a subclass to read or manipulate the response or metadata after it @@ -353,7 +411,14 @@ def post_get_instance_with_metadata(self, response: cloud_redis.Instance, metada """ return response, metadata - def pre_get_instance_auth_string(self, request: cloud_redis.GetInstanceAuthStringRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.GetInstanceAuthStringRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_get_instance_auth_string( + self, + request: cloud_redis.GetInstanceAuthStringRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.GetInstanceAuthStringRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for get_instance_auth_string Override in a subclass to manipulate the request or metadata @@ -361,7 +426,9 @@ def pre_get_instance_auth_string(self, request: cloud_redis.GetInstanceAuthStrin """ return request, metadata - def post_get_instance_auth_string(self, response: cloud_redis.InstanceAuthString) -> cloud_redis.InstanceAuthString: + def post_get_instance_auth_string( + self, response: cloud_redis.InstanceAuthString + ) -> cloud_redis.InstanceAuthString: """Post-rpc interceptor for get_instance_auth_string DEPRECATED. Please use the `post_get_instance_auth_string_with_metadata` @@ -374,7 +441,11 @@ def post_get_instance_auth_string(self, response: cloud_redis.InstanceAuthString """ return response - def post_get_instance_auth_string_with_metadata(self, response: cloud_redis.InstanceAuthString, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.InstanceAuthString, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_instance_auth_string_with_metadata( + self, + response: cloud_redis.InstanceAuthString, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[cloud_redis.InstanceAuthString, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_instance_auth_string Override in a subclass to read or manipulate the response or metadata after it @@ -389,7 +460,13 @@ def post_get_instance_auth_string_with_metadata(self, response: cloud_redis.Inst """ return response, metadata - def pre_import_instance(self, request: cloud_redis.ImportInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.ImportInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_import_instance( + self, + request: cloud_redis.ImportInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.ImportInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for import_instance Override in a subclass to manipulate the request or metadata @@ -397,7 +474,9 @@ def pre_import_instance(self, request: cloud_redis.ImportInstanceRequest, metada """ return request, metadata - def post_import_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_import_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for import_instance DEPRECATED. Please use the `post_import_instance_with_metadata` @@ -410,7 +489,11 @@ def post_import_instance(self, response: operations_pb2.Operation) -> operations """ return response - def post_import_instance_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_import_instance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for import_instance Override in a subclass to read or manipulate the response or metadata after it @@ -425,7 +508,13 @@ def post_import_instance_with_metadata(self, response: operations_pb2.Operation, """ return response, metadata - def pre_list_instances(self, request: cloud_redis.ListInstancesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.ListInstancesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_instances( + self, + request: cloud_redis.ListInstancesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.ListInstancesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_instances Override in a subclass to manipulate the request or metadata @@ -433,7 +522,9 @@ def pre_list_instances(self, request: cloud_redis.ListInstancesRequest, metadata """ return request, metadata - def post_list_instances(self, response: cloud_redis.ListInstancesResponse) -> cloud_redis.ListInstancesResponse: + def post_list_instances( + self, response: cloud_redis.ListInstancesResponse + ) -> cloud_redis.ListInstancesResponse: """Post-rpc interceptor for list_instances DEPRECATED. Please use the `post_list_instances_with_metadata` @@ -446,7 +537,13 @@ def post_list_instances(self, response: cloud_redis.ListInstancesResponse) -> cl """ return response - def post_list_instances_with_metadata(self, response: cloud_redis.ListInstancesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.ListInstancesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_instances_with_metadata( + self, + response: cloud_redis.ListInstancesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.ListInstancesResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for list_instances Override in a subclass to read or manipulate the response or metadata after it @@ -461,7 +558,14 @@ def post_list_instances_with_metadata(self, response: cloud_redis.ListInstancesR """ return response, metadata - def pre_reschedule_maintenance(self, request: cloud_redis.RescheduleMaintenanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.RescheduleMaintenanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_reschedule_maintenance( + self, + request: cloud_redis.RescheduleMaintenanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.RescheduleMaintenanceRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for reschedule_maintenance Override in a subclass to manipulate the request or metadata @@ -469,7 +573,9 @@ def pre_reschedule_maintenance(self, request: cloud_redis.RescheduleMaintenanceR """ return request, metadata - def post_reschedule_maintenance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_reschedule_maintenance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for reschedule_maintenance DEPRECATED. Please use the `post_reschedule_maintenance_with_metadata` @@ -482,7 +588,11 @@ def post_reschedule_maintenance(self, response: operations_pb2.Operation) -> ope """ return response - def post_reschedule_maintenance_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_reschedule_maintenance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for reschedule_maintenance Override in a subclass to read or manipulate the response or metadata after it @@ -497,7 +607,13 @@ def post_reschedule_maintenance_with_metadata(self, response: operations_pb2.Ope """ return response, metadata - def pre_update_instance(self, request: cloud_redis.UpdateInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.UpdateInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_update_instance( + self, + request: cloud_redis.UpdateInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.UpdateInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for update_instance Override in a subclass to manipulate the request or metadata @@ -505,7 +621,9 @@ def pre_update_instance(self, request: cloud_redis.UpdateInstanceRequest, metada """ return request, metadata - def post_update_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_update_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for update_instance DEPRECATED. Please use the `post_update_instance_with_metadata` @@ -518,7 +636,11 @@ def post_update_instance(self, response: operations_pb2.Operation) -> operations """ return response - def post_update_instance_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_update_instance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for update_instance Override in a subclass to read or manipulate the response or metadata after it @@ -533,7 +655,13 @@ def post_update_instance_with_metadata(self, response: operations_pb2.Operation, """ return response, metadata - def pre_upgrade_instance(self, request: cloud_redis.UpgradeInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.UpgradeInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_upgrade_instance( + self, + request: cloud_redis.UpgradeInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.UpgradeInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for upgrade_instance Override in a subclass to manipulate the request or metadata @@ -541,7 +669,9 @@ def pre_upgrade_instance(self, request: cloud_redis.UpgradeInstanceRequest, meta """ return request, metadata - def post_upgrade_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_upgrade_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for upgrade_instance DEPRECATED. Please use the `post_upgrade_instance_with_metadata` @@ -554,7 +684,11 @@ def post_upgrade_instance(self, response: operations_pb2.Operation) -> operation """ return response - def post_upgrade_instance_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_upgrade_instance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for upgrade_instance Override in a subclass to read or manipulate the response or metadata after it @@ -570,8 +704,12 @@ def post_upgrade_instance_with_metadata(self, response: operations_pb2.Operation return response, metadata def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_location Override in a subclass to manipulate the request or metadata @@ -591,8 +729,12 @@ def post_get_location( return response def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_locations Override in a subclass to manipulate the request or metadata @@ -612,8 +754,12 @@ def post_list_locations( return response def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for cancel_operation Override in a subclass to manipulate the request or metadata @@ -621,9 +767,7 @@ def pre_cancel_operation( """ return request, metadata - def post_cancel_operation( - self, response: None - ) -> None: + def post_cancel_operation(self, response: None) -> None: """Post-rpc interceptor for cancel_operation Override in a subclass to manipulate the response @@ -633,8 +777,12 @@ def post_cancel_operation( return response def pre_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for delete_operation Override in a subclass to manipulate the request or metadata @@ -642,9 +790,7 @@ def pre_delete_operation( """ return request, metadata - def post_delete_operation( - self, response: None - ) -> None: + def post_delete_operation(self, response: None) -> None: """Post-rpc interceptor for delete_operation Override in a subclass to manipulate the response @@ -654,8 +800,12 @@ def post_delete_operation( return response def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_operation Override in a subclass to manipulate the request or metadata @@ -675,8 +825,12 @@ def post_get_operation( return response def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_operations Override in a subclass to manipulate the request or metadata @@ -696,8 +850,12 @@ def post_list_operations( return response def pre_wait_operation( - self, request: operations_pb2.WaitOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.WaitOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.WaitOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.WaitOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for wait_operation Override in a subclass to manipulate the request or metadata @@ -756,62 +914,63 @@ class CloudRedisRestTransport(_BaseCloudRedisRestTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__(self, *, - host: str = 'redis.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[CloudRedisRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: + def __init__( + self, + *, + host: str = "redis.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[CloudRedisRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. - NOTE: This REST transport functionality is currently in a beta - state (preview). We welcome your feedback via a GitHub issue in - this library's repository. Thank you! - - Args: - host (Optional[str]): - The hostname to connect to (default: 'redis.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. This argument will be - removed in the next major version of this library. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - interceptor (Optional[CloudRedisRestInterceptor]): Interceptor used - to manipulate requests, request metadata, and responses. - api_audience (Optional[str]): The intended audience for the API calls - to the service that will be set when using certain 3rd party - authentication flows. Audience is typically a resource identifier. - If not set, the host value will be used as a default. + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to (default: 'redis.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[CloudRedisRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. """ # Run the base constructor # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. @@ -823,10 +982,11 @@ def __init__(self, *, client_info=client_info, always_use_jwt_access=always_use_jwt_access, url_scheme=url_scheme, - api_audience=api_audience + api_audience=api_audience, ) self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) + self._credentials, default_host=self.DEFAULT_HOST + ) self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None if client_cert_source_for_mtls: self._session.configure_mtls_channel(client_cert_source_for_mtls) @@ -843,53 +1003,58 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Only create a new client if we do not already have one. if self._operations_client is None: http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ + "google.longrunning.Operations.CancelOperation": [ { - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", }, ], - 'google.longrunning.Operations.DeleteOperation': [ + "google.longrunning.Operations.DeleteOperation": [ { - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", }, ], - 'google.longrunning.Operations.GetOperation': [ + "google.longrunning.Operations.GetOperation": [ { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", }, ], - 'google.longrunning.Operations.ListOperations': [ + "google.longrunning.Operations.ListOperations": [ { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", }, ], - 'google.longrunning.Operations.WaitOperation': [ + "google.longrunning.Operations.WaitOperation": [ { - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}:wait', - 'body': '*', + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/operations/*}:wait", + "body": "*", }, ], } rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) # Return the client from cache. return self._operations_client - class _CreateInstance(_BaseCloudRedisRestTransport._BaseCreateInstance, CloudRedisRestStub): + class _CreateInstance( + _BaseCloudRedisRestTransport._BaseCreateInstance, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.CreateInstance") @@ -901,27 +1066,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: cloud_redis.CreateInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: cloud_redis.CreateInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the create instance method over HTTP. Args: @@ -944,32 +1111,48 @@ def __call__(self, """ - http_options = _BaseCloudRedisRestTransport._BaseCreateInstance._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseCreateInstance._get_http_options() + ) request, metadata = self._interceptor.pre_create_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseCreateInstance._get_transcoded_request(http_options, request) + transcoded_request = _BaseCloudRedisRestTransport._BaseCreateInstance._get_transcoded_request( + http_options, request + ) - body = _BaseCloudRedisRestTransport._BaseCreateInstance._get_request_body_json(transcoded_request) + body = ( + _BaseCloudRedisRestTransport._BaseCreateInstance._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseCreateInstance._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseCreateInstance._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.CreateInstance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "CreateInstance", "httpRequest": http_request, @@ -978,7 +1161,15 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._CreateInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = CloudRedisRestTransport._CreateInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -991,20 +1182,24 @@ def __call__(self, resp = self._interceptor.post_create_instance(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_instance_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_create_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisClient.create_instance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "CreateInstance", "metadata": http_response["headers"], @@ -1013,7 +1208,9 @@ def __call__(self, ) return resp - class _DeleteInstance(_BaseCloudRedisRestTransport._BaseDeleteInstance, CloudRedisRestStub): + class _DeleteInstance( + _BaseCloudRedisRestTransport._BaseDeleteInstance, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.DeleteInstance") @@ -1025,26 +1222,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: cloud_redis.DeleteInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: cloud_redis.DeleteInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the delete instance method over HTTP. Args: @@ -1067,30 +1266,42 @@ def __call__(self, """ - http_options = _BaseCloudRedisRestTransport._BaseDeleteInstance._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseDeleteInstance._get_http_options() + ) request, metadata = self._interceptor.pre_delete_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseDeleteInstance._get_transcoded_request(http_options, request) + transcoded_request = _BaseCloudRedisRestTransport._BaseDeleteInstance._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseDeleteInstance._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseDeleteInstance._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.DeleteInstance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "DeleteInstance", "httpRequest": http_request, @@ -1099,7 +1310,14 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._DeleteInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = CloudRedisRestTransport._DeleteInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1112,20 +1330,24 @@ def __call__(self, resp = self._interceptor.post_delete_instance(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_instance_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_delete_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisClient.delete_instance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "DeleteInstance", "metadata": http_response["headers"], @@ -1134,7 +1356,9 @@ def __call__(self, ) return resp - class _ExportInstance(_BaseCloudRedisRestTransport._BaseExportInstance, CloudRedisRestStub): + class _ExportInstance( + _BaseCloudRedisRestTransport._BaseExportInstance, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.ExportInstance") @@ -1146,27 +1370,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: cloud_redis.ExportInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: cloud_redis.ExportInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the export instance method over HTTP. Args: @@ -1189,32 +1415,48 @@ def __call__(self, """ - http_options = _BaseCloudRedisRestTransport._BaseExportInstance._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseExportInstance._get_http_options() + ) request, metadata = self._interceptor.pre_export_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseExportInstance._get_transcoded_request(http_options, request) + transcoded_request = _BaseCloudRedisRestTransport._BaseExportInstance._get_transcoded_request( + http_options, request + ) - body = _BaseCloudRedisRestTransport._BaseExportInstance._get_request_body_json(transcoded_request) + body = ( + _BaseCloudRedisRestTransport._BaseExportInstance._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseExportInstance._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseExportInstance._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.ExportInstance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ExportInstance", "httpRequest": http_request, @@ -1223,7 +1465,15 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._ExportInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = CloudRedisRestTransport._ExportInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1236,20 +1486,24 @@ def __call__(self, resp = self._interceptor.post_export_instance(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_export_instance_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_export_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisClient.export_instance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ExportInstance", "metadata": http_response["headers"], @@ -1258,7 +1512,9 @@ def __call__(self, ) return resp - class _FailoverInstance(_BaseCloudRedisRestTransport._BaseFailoverInstance, CloudRedisRestStub): + class _FailoverInstance( + _BaseCloudRedisRestTransport._BaseFailoverInstance, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.FailoverInstance") @@ -1270,27 +1526,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: cloud_redis.FailoverInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: cloud_redis.FailoverInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the failover instance method over HTTP. Args: @@ -1313,32 +1571,46 @@ def __call__(self, """ - http_options = _BaseCloudRedisRestTransport._BaseFailoverInstance._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseFailoverInstance._get_http_options() + ) - request, metadata = self._interceptor.pre_failover_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseFailoverInstance._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_failover_instance( + request, metadata + ) + transcoded_request = _BaseCloudRedisRestTransport._BaseFailoverInstance._get_transcoded_request( + http_options, request + ) - body = _BaseCloudRedisRestTransport._BaseFailoverInstance._get_request_body_json(transcoded_request) + body = _BaseCloudRedisRestTransport._BaseFailoverInstance._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseFailoverInstance._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseCloudRedisRestTransport._BaseFailoverInstance._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.FailoverInstance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "FailoverInstance", "httpRequest": http_request, @@ -1347,7 +1619,15 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._FailoverInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = CloudRedisRestTransport._FailoverInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1360,20 +1640,24 @@ def __call__(self, resp = self._interceptor.post_failover_instance(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_failover_instance_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_failover_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisClient.failover_instance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "FailoverInstance", "metadata": http_response["headers"], @@ -1382,7 +1666,9 @@ def __call__(self, ) return resp - class _GetInstance(_BaseCloudRedisRestTransport._BaseGetInstance, CloudRedisRestStub): + class _GetInstance( + _BaseCloudRedisRestTransport._BaseGetInstance, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.GetInstance") @@ -1394,26 +1680,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: cloud_redis.GetInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> cloud_redis.Instance: + def __call__( + self, + request: cloud_redis.GetInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_redis.Instance: r"""Call the get instance method over HTTP. Args: @@ -1433,30 +1721,44 @@ def __call__(self, A Memorystore for Redis instance. """ - http_options = _BaseCloudRedisRestTransport._BaseGetInstance._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseGetInstance._get_http_options() + ) request, metadata = self._interceptor.pre_get_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseGetInstance._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseGetInstance._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseGetInstance._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseGetInstance._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.GetInstance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "GetInstance", "httpRequest": http_request, @@ -1465,7 +1767,14 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._GetInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = CloudRedisRestTransport._GetInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1480,20 +1789,24 @@ def __call__(self, resp = self._interceptor.post_get_instance(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_instance_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = cloud_redis.Instance.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisClient.get_instance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "GetInstance", "metadata": http_response["headers"], @@ -1502,7 +1815,9 @@ def __call__(self, ) return resp - class _GetInstanceAuthString(_BaseCloudRedisRestTransport._BaseGetInstanceAuthString, CloudRedisRestStub): + class _GetInstanceAuthString( + _BaseCloudRedisRestTransport._BaseGetInstanceAuthString, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.GetInstanceAuthString") @@ -1514,26 +1829,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: cloud_redis.GetInstanceAuthStringRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> cloud_redis.InstanceAuthString: + def __call__( + self, + request: cloud_redis.GetInstanceAuthStringRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_redis.InstanceAuthString: r"""Call the get instance auth string method over HTTP. Args: @@ -1553,30 +1870,42 @@ def __call__(self, Instance AUTH string details. """ - http_options = _BaseCloudRedisRestTransport._BaseGetInstanceAuthString._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseGetInstanceAuthString._get_http_options() + ) - request, metadata = self._interceptor.pre_get_instance_auth_string(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseGetInstanceAuthString._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_get_instance_auth_string( + request, metadata + ) + transcoded_request = _BaseCloudRedisRestTransport._BaseGetInstanceAuthString._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseGetInstanceAuthString._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseCloudRedisRestTransport._BaseGetInstanceAuthString._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.GetInstanceAuthString", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "GetInstanceAuthString", "httpRequest": http_request, @@ -1585,7 +1914,14 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._GetInstanceAuthString._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = CloudRedisRestTransport._GetInstanceAuthString._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1600,20 +1936,24 @@ def __call__(self, resp = self._interceptor.post_get_instance_auth_string(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_instance_auth_string_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_instance_auth_string_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = cloud_redis.InstanceAuthString.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisClient.get_instance_auth_string", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "GetInstanceAuthString", "metadata": http_response["headers"], @@ -1622,7 +1962,9 @@ def __call__(self, ) return resp - class _ImportInstance(_BaseCloudRedisRestTransport._BaseImportInstance, CloudRedisRestStub): + class _ImportInstance( + _BaseCloudRedisRestTransport._BaseImportInstance, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.ImportInstance") @@ -1634,27 +1976,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: cloud_redis.ImportInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: cloud_redis.ImportInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the import instance method over HTTP. Args: @@ -1677,32 +2021,48 @@ def __call__(self, """ - http_options = _BaseCloudRedisRestTransport._BaseImportInstance._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseImportInstance._get_http_options() + ) request, metadata = self._interceptor.pre_import_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseImportInstance._get_transcoded_request(http_options, request) + transcoded_request = _BaseCloudRedisRestTransport._BaseImportInstance._get_transcoded_request( + http_options, request + ) - body = _BaseCloudRedisRestTransport._BaseImportInstance._get_request_body_json(transcoded_request) + body = ( + _BaseCloudRedisRestTransport._BaseImportInstance._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseImportInstance._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseImportInstance._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.ImportInstance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ImportInstance", "httpRequest": http_request, @@ -1711,7 +2071,15 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._ImportInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = CloudRedisRestTransport._ImportInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1724,20 +2092,24 @@ def __call__(self, resp = self._interceptor.post_import_instance(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_import_instance_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_import_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisClient.import_instance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ImportInstance", "metadata": http_response["headers"], @@ -1746,7 +2118,9 @@ def __call__(self, ) return resp - class _ListInstances(_BaseCloudRedisRestTransport._BaseListInstances, CloudRedisRestStub): + class _ListInstances( + _BaseCloudRedisRestTransport._BaseListInstances, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.ListInstances") @@ -1758,26 +2132,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: cloud_redis.ListInstancesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> cloud_redis.ListInstancesResponse: + def __call__( + self, + request: cloud_redis.ListInstancesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_redis.ListInstancesResponse: r"""Call the list instances method over HTTP. Args: @@ -1799,30 +2175,44 @@ def __call__(self, """ - http_options = _BaseCloudRedisRestTransport._BaseListInstances._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseListInstances._get_http_options() + ) request, metadata = self._interceptor.pre_list_instances(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseListInstances._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseListInstances._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseListInstances._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseListInstances._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.ListInstances", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ListInstances", "httpRequest": http_request, @@ -1831,7 +2221,14 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._ListInstances._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = CloudRedisRestTransport._ListInstances._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1846,20 +2243,26 @@ def __call__(self, resp = self._interceptor.post_list_instances(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_instances_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_instances_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = cloud_redis.ListInstancesResponse.to_json(response) + response_payload = cloud_redis.ListInstancesResponse.to_json( + response + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisClient.list_instances", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ListInstances", "metadata": http_response["headers"], @@ -1868,7 +2271,9 @@ def __call__(self, ) return resp - class _RescheduleMaintenance(_BaseCloudRedisRestTransport._BaseRescheduleMaintenance, CloudRedisRestStub): + class _RescheduleMaintenance( + _BaseCloudRedisRestTransport._BaseRescheduleMaintenance, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.RescheduleMaintenance") @@ -1880,27 +2285,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: cloud_redis.RescheduleMaintenanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: cloud_redis.RescheduleMaintenanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the reschedule maintenance method over HTTP. Args: @@ -1923,32 +2330,46 @@ def __call__(self, """ - http_options = _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_http_options() + ) - request, metadata = self._interceptor.pre_reschedule_maintenance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_reschedule_maintenance( + request, metadata + ) + transcoded_request = _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_transcoded_request( + http_options, request + ) - body = _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_request_body_json(transcoded_request) + body = _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.RescheduleMaintenance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "RescheduleMaintenance", "httpRequest": http_request, @@ -1957,7 +2378,15 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._RescheduleMaintenance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = CloudRedisRestTransport._RescheduleMaintenance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1970,20 +2399,24 @@ def __call__(self, resp = self._interceptor.post_reschedule_maintenance(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_reschedule_maintenance_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_reschedule_maintenance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisClient.reschedule_maintenance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "RescheduleMaintenance", "metadata": http_response["headers"], @@ -1992,7 +2425,9 @@ def __call__(self, ) return resp - class _UpdateInstance(_BaseCloudRedisRestTransport._BaseUpdateInstance, CloudRedisRestStub): + class _UpdateInstance( + _BaseCloudRedisRestTransport._BaseUpdateInstance, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.UpdateInstance") @@ -2004,27 +2439,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: cloud_redis.UpdateInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: cloud_redis.UpdateInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the update instance method over HTTP. Args: @@ -2047,32 +2484,48 @@ def __call__(self, """ - http_options = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseUpdateInstance._get_http_options() + ) request, metadata = self._interceptor.pre_update_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_transcoded_request(http_options, request) + transcoded_request = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_transcoded_request( + http_options, request + ) - body = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_request_body_json(transcoded_request) + body = ( + _BaseCloudRedisRestTransport._BaseUpdateInstance._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseUpdateInstance._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.UpdateInstance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "UpdateInstance", "httpRequest": http_request, @@ -2081,7 +2534,15 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._UpdateInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = CloudRedisRestTransport._UpdateInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2094,20 +2555,24 @@ def __call__(self, resp = self._interceptor.post_update_instance(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_instance_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_update_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisClient.update_instance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "UpdateInstance", "metadata": http_response["headers"], @@ -2116,7 +2581,9 @@ def __call__(self, ) return resp - class _UpgradeInstance(_BaseCloudRedisRestTransport._BaseUpgradeInstance, CloudRedisRestStub): + class _UpgradeInstance( + _BaseCloudRedisRestTransport._BaseUpgradeInstance, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.UpgradeInstance") @@ -2128,27 +2595,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: cloud_redis.UpgradeInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: cloud_redis.UpgradeInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the upgrade instance method over HTTP. Args: @@ -2171,32 +2640,46 @@ def __call__(self, """ - http_options = _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_http_options() + ) - request, metadata = self._interceptor.pre_upgrade_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_upgrade_instance( + request, metadata + ) + transcoded_request = _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_transcoded_request( + http_options, request + ) - body = _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_request_body_json(transcoded_request) + body = _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.UpgradeInstance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "UpgradeInstance", "httpRequest": http_request, @@ -2205,7 +2688,15 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._UpgradeInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = CloudRedisRestTransport._UpgradeInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2218,20 +2709,24 @@ def __call__(self, resp = self._interceptor.post_upgrade_instance(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_upgrade_instance_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_upgrade_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisClient.upgrade_instance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "UpgradeInstance", "metadata": http_response["headers"], @@ -2241,98 +2736,104 @@ def __call__(self, return resp @property - def create_instance(self) -> Callable[ - [cloud_redis.CreateInstanceRequest], - operations_pb2.Operation]: + def create_instance( + self, + ) -> Callable[[cloud_redis.CreateInstanceRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._CreateInstance(self._session, self._host, self._interceptor) # type: ignore + return self._CreateInstance(self._session, self._host, self._interceptor) # type: ignore @property - def delete_instance(self) -> Callable[ - [cloud_redis.DeleteInstanceRequest], - operations_pb2.Operation]: + def delete_instance( + self, + ) -> Callable[[cloud_redis.DeleteInstanceRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._DeleteInstance(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteInstance(self._session, self._host, self._interceptor) # type: ignore @property - def export_instance(self) -> Callable[ - [cloud_redis.ExportInstanceRequest], - operations_pb2.Operation]: + def export_instance( + self, + ) -> Callable[[cloud_redis.ExportInstanceRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._ExportInstance(self._session, self._host, self._interceptor) # type: ignore + return self._ExportInstance(self._session, self._host, self._interceptor) # type: ignore @property - def failover_instance(self) -> Callable[ - [cloud_redis.FailoverInstanceRequest], - operations_pb2.Operation]: + def failover_instance( + self, + ) -> Callable[[cloud_redis.FailoverInstanceRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._FailoverInstance(self._session, self._host, self._interceptor) # type: ignore + return self._FailoverInstance(self._session, self._host, self._interceptor) # type: ignore @property - def get_instance(self) -> Callable[ - [cloud_redis.GetInstanceRequest], - cloud_redis.Instance]: + def get_instance( + self, + ) -> Callable[[cloud_redis.GetInstanceRequest], cloud_redis.Instance]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._GetInstance(self._session, self._host, self._interceptor) # type: ignore + return self._GetInstance(self._session, self._host, self._interceptor) # type: ignore @property - def get_instance_auth_string(self) -> Callable[ - [cloud_redis.GetInstanceAuthStringRequest], - cloud_redis.InstanceAuthString]: + def get_instance_auth_string( + self, + ) -> Callable[ + [cloud_redis.GetInstanceAuthStringRequest], cloud_redis.InstanceAuthString + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._GetInstanceAuthString(self._session, self._host, self._interceptor) # type: ignore + return self._GetInstanceAuthString(self._session, self._host, self._interceptor) # type: ignore @property - def import_instance(self) -> Callable[ - [cloud_redis.ImportInstanceRequest], - operations_pb2.Operation]: + def import_instance( + self, + ) -> Callable[[cloud_redis.ImportInstanceRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._ImportInstance(self._session, self._host, self._interceptor) # type: ignore + return self._ImportInstance(self._session, self._host, self._interceptor) # type: ignore @property - def list_instances(self) -> Callable[ - [cloud_redis.ListInstancesRequest], - cloud_redis.ListInstancesResponse]: + def list_instances( + self, + ) -> Callable[ + [cloud_redis.ListInstancesRequest], cloud_redis.ListInstancesResponse + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._ListInstances(self._session, self._host, self._interceptor) # type: ignore + return self._ListInstances(self._session, self._host, self._interceptor) # type: ignore @property - def reschedule_maintenance(self) -> Callable[ - [cloud_redis.RescheduleMaintenanceRequest], - operations_pb2.Operation]: + def reschedule_maintenance( + self, + ) -> Callable[[cloud_redis.RescheduleMaintenanceRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._RescheduleMaintenance(self._session, self._host, self._interceptor) # type: ignore + return self._RescheduleMaintenance(self._session, self._host, self._interceptor) # type: ignore @property - def update_instance(self) -> Callable[ - [cloud_redis.UpdateInstanceRequest], - operations_pb2.Operation]: + def update_instance( + self, + ) -> Callable[[cloud_redis.UpdateInstanceRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._UpdateInstance(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateInstance(self._session, self._host, self._interceptor) # type: ignore @property - def upgrade_instance(self) -> Callable[ - [cloud_redis.UpgradeInstanceRequest], - operations_pb2.Operation]: + def upgrade_instance( + self, + ) -> Callable[[cloud_redis.UpgradeInstanceRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._UpgradeInstance(self._session, self._host, self._interceptor) # type: ignore + return self._UpgradeInstance(self._session, self._host, self._interceptor) # type: ignore @property def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - class _GetLocation(_BaseCloudRedisRestTransport._BaseGetLocation, CloudRedisRestStub): + class _GetLocation( + _BaseCloudRedisRestTransport._BaseGetLocation, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.GetLocation") @@ -2344,27 +2845,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> locations_pb2.Location: - + def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: r"""Call the get location method over HTTP. Args: @@ -2382,30 +2884,44 @@ def __call__(self, locations_pb2.Location: Response from GetLocation method. """ - http_options = _BaseCloudRedisRestTransport._BaseGetLocation._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseGetLocation._get_http_options() + ) request, metadata = self._interceptor.pre_get_location(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseGetLocation._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.GetLocation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "GetLocation", "httpRequest": http_request, @@ -2414,7 +2930,14 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = CloudRedisRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2425,19 +2948,21 @@ def __call__(self, resp = locations_pb2.Location() resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_location(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.GetLocation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "GetLocation", "httpResponse": http_response, @@ -2448,9 +2973,11 @@ def __call__(self, @property def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - class _ListLocations(_BaseCloudRedisRestTransport._BaseListLocations, CloudRedisRestStub): + class _ListLocations( + _BaseCloudRedisRestTransport._BaseListLocations, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.ListLocations") @@ -2462,27 +2989,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> locations_pb2.ListLocationsResponse: - + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: r"""Call the list locations method over HTTP. Args: @@ -2500,30 +3028,44 @@ def __call__(self, locations_pb2.ListLocationsResponse: Response from ListLocations method. """ - http_options = _BaseCloudRedisRestTransport._BaseListLocations._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseListLocations._get_http_options() + ) request, metadata = self._interceptor.pre_list_locations(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseListLocations._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseListLocations._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseListLocations._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.ListLocations", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ListLocations", "httpRequest": http_request, @@ -2532,7 +3074,14 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = CloudRedisRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2543,19 +3092,21 @@ def __call__(self, resp = locations_pb2.ListLocationsResponse() resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_locations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.ListLocations", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ListLocations", "httpResponse": http_response, @@ -2566,9 +3117,11 @@ def __call__(self, @property def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - class _CancelOperation(_BaseCloudRedisRestTransport._BaseCancelOperation, CloudRedisRestStub): + class _CancelOperation( + _BaseCloudRedisRestTransport._BaseCancelOperation, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.CancelOperation") @@ -2580,27 +3133,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> None: - + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Call the cancel operation method over HTTP. Args: @@ -2615,30 +3169,42 @@ def __call__(self, be of type `bytes`. """ - http_options = _BaseCloudRedisRestTransport._BaseCancelOperation._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseCancelOperation._get_http_options() + ) - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = _BaseCloudRedisRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseCloudRedisRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.CancelOperation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "CancelOperation", "httpRequest": http_request, @@ -2647,7 +3213,14 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._CancelOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = CloudRedisRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2658,9 +3231,11 @@ def __call__(self, @property def delete_operation(self): - return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - class _DeleteOperation(_BaseCloudRedisRestTransport._BaseDeleteOperation, CloudRedisRestStub): + class _DeleteOperation( + _BaseCloudRedisRestTransport._BaseDeleteOperation, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.DeleteOperation") @@ -2672,27 +3247,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: operations_pb2.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> None: - + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Call the delete operation method over HTTP. Args: @@ -2707,30 +3283,42 @@ def __call__(self, be of type `bytes`. """ - http_options = _BaseCloudRedisRestTransport._BaseDeleteOperation._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseDeleteOperation._get_http_options() + ) - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + transcoded_request = _BaseCloudRedisRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseCloudRedisRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.DeleteOperation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "DeleteOperation", "httpRequest": http_request, @@ -2739,7 +3327,14 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._DeleteOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = CloudRedisRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2750,9 +3345,11 @@ def __call__(self, @property def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(_BaseCloudRedisRestTransport._BaseGetOperation, CloudRedisRestStub): + class _GetOperation( + _BaseCloudRedisRestTransport._BaseGetOperation, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.GetOperation") @@ -2764,27 +3361,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the get operation method over HTTP. Args: @@ -2802,30 +3400,44 @@ def __call__(self, operations_pb2.Operation: Response from GetOperation method. """ - http_options = _BaseCloudRedisRestTransport._BaseGetOperation._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.GetOperation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "GetOperation", "httpRequest": http_request, @@ -2834,7 +3446,14 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = CloudRedisRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2845,19 +3464,21 @@ def __call__(self, resp = operations_pb2.Operation() resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.GetOperation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "GetOperation", "httpResponse": http_response, @@ -2868,9 +3489,11 @@ def __call__(self, @property def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(_BaseCloudRedisRestTransport._BaseListOperations, CloudRedisRestStub): + class _ListOperations( + _BaseCloudRedisRestTransport._BaseListOperations, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.ListOperations") @@ -2882,27 +3505,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.ListOperationsResponse: - + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: r"""Call the list operations method over HTTP. Args: @@ -2920,30 +3544,42 @@ def __call__(self, operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options = _BaseCloudRedisRestTransport._BaseListOperations._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseListOperations._get_transcoded_request(http_options, request) + transcoded_request = _BaseCloudRedisRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseListOperations._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.ListOperations", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ListOperations", "httpRequest": http_request, @@ -2952,7 +3588,14 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = CloudRedisRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2963,19 +3606,21 @@ def __call__(self, resp = operations_pb2.ListOperationsResponse() resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.ListOperations", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ListOperations", "httpResponse": http_response, @@ -2986,9 +3631,11 @@ def __call__(self, @property def wait_operation(self): - return self._WaitOperation(self._session, self._host, self._interceptor) # type: ignore + return self._WaitOperation(self._session, self._host, self._interceptor) # type: ignore - class _WaitOperation(_BaseCloudRedisRestTransport._BaseWaitOperation, CloudRedisRestStub): + class _WaitOperation( + _BaseCloudRedisRestTransport._BaseWaitOperation, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.WaitOperation") @@ -3000,28 +3647,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: operations_pb2.WaitOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - + def __call__( + self, + request: operations_pb2.WaitOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the wait operation method over HTTP. Args: @@ -3039,32 +3687,50 @@ def __call__(self, operations_pb2.Operation: Response from WaitOperation method. """ - http_options = _BaseCloudRedisRestTransport._BaseWaitOperation._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseWaitOperation._get_http_options() + ) request, metadata = self._interceptor.pre_wait_operation(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseWaitOperation._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseWaitOperation._get_transcoded_request( + http_options, request + ) + ) - body = _BaseCloudRedisRestTransport._BaseWaitOperation._get_request_body_json(transcoded_request) + body = ( + _BaseCloudRedisRestTransport._BaseWaitOperation._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseWaitOperation._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseWaitOperation._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.WaitOperation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "WaitOperation", "httpRequest": http_request, @@ -3073,7 +3739,15 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._WaitOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = CloudRedisRestTransport._WaitOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3084,19 +3758,21 @@ def __call__(self, resp = operations_pb2.Operation() resp = json_format.Parse(content, resp) resp = self._interceptor.post_wait_operation(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.WaitOperation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "WaitOperation", "httpResponse": http_response, @@ -3113,6 +3789,4 @@ def close(self): self._session.close() -__all__=( - 'CloudRedisRestTransport', -) +__all__ = ("CloudRedisRestTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/rest_asyncio.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/rest_asyncio.py index 3d6ae2872202..f90f8ae11a47 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/rest_asyncio.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/rest_asyncio.py @@ -15,20 +15,23 @@ # import google.auth + try: - import aiohttp # type: ignore - from google.auth.aio.transport.sessions import AsyncAuthorizedSession # type: ignore - from google.api_core import rest_streaming_async # type: ignore - from google.api_core.operations_v1 import AsyncOperationsRestClient # type: ignore + import aiohttp # type: ignore + from google.auth.aio.transport.sessions import AsyncAuthorizedSession # type: ignore + from google.api_core import rest_streaming_async # type: ignore + from google.api_core.operations_v1 import AsyncOperationsRestClient # type: ignore except ImportError as e: # pragma: NO COVER - raise ImportError("`rest_asyncio` transport requires the library to be installed with the `async_rest` extra. Install the library with the `async_rest` extra using `pip install google-cloud-redis[async_rest]`") from e + raise ImportError( + "`rest_asyncio` transport requires the library to be installed with the `async_rest` extra. Install the library with the `async_rest` extra using `pip install google-cloud-redis[async_rest]`" + ) from e from google.auth.aio import credentials as ga_credentials_async # type: ignore from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.api_core import retry_async as retries from google.api_core import rest_helpers from google.api_core import rest_streaming_async # type: ignore @@ -36,7 +39,7 @@ from google.protobuf import json_format from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore import json # type: ignore import dataclasses @@ -56,6 +59,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -185,7 +189,14 @@ async def post_upgrade_instance(self, response): """ - async def pre_create_instance(self, request: cloud_redis.CreateInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.CreateInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + async def pre_create_instance( + self, + request: cloud_redis.CreateInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.CreateInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for create_instance Override in a subclass to manipulate the request or metadata @@ -193,7 +204,9 @@ async def pre_create_instance(self, request: cloud_redis.CreateInstanceRequest, """ return request, metadata - async def post_create_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + async def post_create_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for create_instance DEPRECATED. Please use the `post_create_instance_with_metadata` @@ -206,7 +219,11 @@ async def post_create_instance(self, response: operations_pb2.Operation) -> oper """ return response - async def post_create_instance_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + async def post_create_instance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for create_instance Override in a subclass to read or manipulate the response or metadata after it @@ -221,7 +238,13 @@ async def post_create_instance_with_metadata(self, response: operations_pb2.Oper """ return response, metadata - async def pre_delete_instance(self, request: cloud_redis.DeleteInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.DeleteInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + async def pre_delete_instance( + self, + request: cloud_redis.DeleteInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.DeleteInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for delete_instance Override in a subclass to manipulate the request or metadata @@ -229,7 +252,9 @@ async def pre_delete_instance(self, request: cloud_redis.DeleteInstanceRequest, """ return request, metadata - async def post_delete_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + async def post_delete_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for delete_instance DEPRECATED. Please use the `post_delete_instance_with_metadata` @@ -242,7 +267,11 @@ async def post_delete_instance(self, response: operations_pb2.Operation) -> oper """ return response - async def post_delete_instance_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + async def post_delete_instance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for delete_instance Override in a subclass to read or manipulate the response or metadata after it @@ -257,7 +286,13 @@ async def post_delete_instance_with_metadata(self, response: operations_pb2.Oper """ return response, metadata - async def pre_export_instance(self, request: cloud_redis.ExportInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.ExportInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + async def pre_export_instance( + self, + request: cloud_redis.ExportInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.ExportInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for export_instance Override in a subclass to manipulate the request or metadata @@ -265,7 +300,9 @@ async def pre_export_instance(self, request: cloud_redis.ExportInstanceRequest, """ return request, metadata - async def post_export_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + async def post_export_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for export_instance DEPRECATED. Please use the `post_export_instance_with_metadata` @@ -278,7 +315,11 @@ async def post_export_instance(self, response: operations_pb2.Operation) -> oper """ return response - async def post_export_instance_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + async def post_export_instance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for export_instance Override in a subclass to read or manipulate the response or metadata after it @@ -293,7 +334,13 @@ async def post_export_instance_with_metadata(self, response: operations_pb2.Oper """ return response, metadata - async def pre_failover_instance(self, request: cloud_redis.FailoverInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.FailoverInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + async def pre_failover_instance( + self, + request: cloud_redis.FailoverInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.FailoverInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for failover_instance Override in a subclass to manipulate the request or metadata @@ -301,7 +348,9 @@ async def pre_failover_instance(self, request: cloud_redis.FailoverInstanceReque """ return request, metadata - async def post_failover_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + async def post_failover_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for failover_instance DEPRECATED. Please use the `post_failover_instance_with_metadata` @@ -314,7 +363,11 @@ async def post_failover_instance(self, response: operations_pb2.Operation) -> op """ return response - async def post_failover_instance_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + async def post_failover_instance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for failover_instance Override in a subclass to read or manipulate the response or metadata after it @@ -329,7 +382,11 @@ async def post_failover_instance_with_metadata(self, response: operations_pb2.Op """ return response, metadata - async def pre_get_instance(self, request: cloud_redis.GetInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.GetInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + async def pre_get_instance( + self, + request: cloud_redis.GetInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[cloud_redis.GetInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_instance Override in a subclass to manipulate the request or metadata @@ -337,7 +394,9 @@ async def pre_get_instance(self, request: cloud_redis.GetInstanceRequest, metada """ return request, metadata - async def post_get_instance(self, response: cloud_redis.Instance) -> cloud_redis.Instance: + async def post_get_instance( + self, response: cloud_redis.Instance + ) -> cloud_redis.Instance: """Post-rpc interceptor for get_instance DEPRECATED. Please use the `post_get_instance_with_metadata` @@ -350,7 +409,11 @@ async def post_get_instance(self, response: cloud_redis.Instance) -> cloud_redis """ return response - async def post_get_instance_with_metadata(self, response: cloud_redis.Instance, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.Instance, Sequence[Tuple[str, Union[str, bytes]]]]: + async def post_get_instance_with_metadata( + self, + response: cloud_redis.Instance, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[cloud_redis.Instance, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_instance Override in a subclass to read or manipulate the response or metadata after it @@ -365,7 +428,14 @@ async def post_get_instance_with_metadata(self, response: cloud_redis.Instance, """ return response, metadata - async def pre_get_instance_auth_string(self, request: cloud_redis.GetInstanceAuthStringRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.GetInstanceAuthStringRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + async def pre_get_instance_auth_string( + self, + request: cloud_redis.GetInstanceAuthStringRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.GetInstanceAuthStringRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for get_instance_auth_string Override in a subclass to manipulate the request or metadata @@ -373,7 +443,9 @@ async def pre_get_instance_auth_string(self, request: cloud_redis.GetInstanceAut """ return request, metadata - async def post_get_instance_auth_string(self, response: cloud_redis.InstanceAuthString) -> cloud_redis.InstanceAuthString: + async def post_get_instance_auth_string( + self, response: cloud_redis.InstanceAuthString + ) -> cloud_redis.InstanceAuthString: """Post-rpc interceptor for get_instance_auth_string DEPRECATED. Please use the `post_get_instance_auth_string_with_metadata` @@ -386,7 +458,11 @@ async def post_get_instance_auth_string(self, response: cloud_redis.InstanceAuth """ return response - async def post_get_instance_auth_string_with_metadata(self, response: cloud_redis.InstanceAuthString, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.InstanceAuthString, Sequence[Tuple[str, Union[str, bytes]]]]: + async def post_get_instance_auth_string_with_metadata( + self, + response: cloud_redis.InstanceAuthString, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[cloud_redis.InstanceAuthString, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_instance_auth_string Override in a subclass to read or manipulate the response or metadata after it @@ -401,7 +477,13 @@ async def post_get_instance_auth_string_with_metadata(self, response: cloud_redi """ return response, metadata - async def pre_import_instance(self, request: cloud_redis.ImportInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.ImportInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + async def pre_import_instance( + self, + request: cloud_redis.ImportInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.ImportInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for import_instance Override in a subclass to manipulate the request or metadata @@ -409,7 +491,9 @@ async def pre_import_instance(self, request: cloud_redis.ImportInstanceRequest, """ return request, metadata - async def post_import_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + async def post_import_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for import_instance DEPRECATED. Please use the `post_import_instance_with_metadata` @@ -422,7 +506,11 @@ async def post_import_instance(self, response: operations_pb2.Operation) -> oper """ return response - async def post_import_instance_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + async def post_import_instance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for import_instance Override in a subclass to read or manipulate the response or metadata after it @@ -437,7 +525,13 @@ async def post_import_instance_with_metadata(self, response: operations_pb2.Oper """ return response, metadata - async def pre_list_instances(self, request: cloud_redis.ListInstancesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.ListInstancesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + async def pre_list_instances( + self, + request: cloud_redis.ListInstancesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.ListInstancesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_instances Override in a subclass to manipulate the request or metadata @@ -445,7 +539,9 @@ async def pre_list_instances(self, request: cloud_redis.ListInstancesRequest, me """ return request, metadata - async def post_list_instances(self, response: cloud_redis.ListInstancesResponse) -> cloud_redis.ListInstancesResponse: + async def post_list_instances( + self, response: cloud_redis.ListInstancesResponse + ) -> cloud_redis.ListInstancesResponse: """Post-rpc interceptor for list_instances DEPRECATED. Please use the `post_list_instances_with_metadata` @@ -458,7 +554,13 @@ async def post_list_instances(self, response: cloud_redis.ListInstancesResponse) """ return response - async def post_list_instances_with_metadata(self, response: cloud_redis.ListInstancesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.ListInstancesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + async def post_list_instances_with_metadata( + self, + response: cloud_redis.ListInstancesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.ListInstancesResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for list_instances Override in a subclass to read or manipulate the response or metadata after it @@ -473,7 +575,14 @@ async def post_list_instances_with_metadata(self, response: cloud_redis.ListInst """ return response, metadata - async def pre_reschedule_maintenance(self, request: cloud_redis.RescheduleMaintenanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.RescheduleMaintenanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + async def pre_reschedule_maintenance( + self, + request: cloud_redis.RescheduleMaintenanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.RescheduleMaintenanceRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for reschedule_maintenance Override in a subclass to manipulate the request or metadata @@ -481,7 +590,9 @@ async def pre_reschedule_maintenance(self, request: cloud_redis.RescheduleMainte """ return request, metadata - async def post_reschedule_maintenance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + async def post_reschedule_maintenance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for reschedule_maintenance DEPRECATED. Please use the `post_reschedule_maintenance_with_metadata` @@ -494,7 +605,11 @@ async def post_reschedule_maintenance(self, response: operations_pb2.Operation) """ return response - async def post_reschedule_maintenance_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + async def post_reschedule_maintenance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for reschedule_maintenance Override in a subclass to read or manipulate the response or metadata after it @@ -509,7 +624,13 @@ async def post_reschedule_maintenance_with_metadata(self, response: operations_p """ return response, metadata - async def pre_update_instance(self, request: cloud_redis.UpdateInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.UpdateInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + async def pre_update_instance( + self, + request: cloud_redis.UpdateInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.UpdateInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for update_instance Override in a subclass to manipulate the request or metadata @@ -517,7 +638,9 @@ async def pre_update_instance(self, request: cloud_redis.UpdateInstanceRequest, """ return request, metadata - async def post_update_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + async def post_update_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for update_instance DEPRECATED. Please use the `post_update_instance_with_metadata` @@ -530,7 +653,11 @@ async def post_update_instance(self, response: operations_pb2.Operation) -> oper """ return response - async def post_update_instance_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + async def post_update_instance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for update_instance Override in a subclass to read or manipulate the response or metadata after it @@ -545,7 +672,13 @@ async def post_update_instance_with_metadata(self, response: operations_pb2.Oper """ return response, metadata - async def pre_upgrade_instance(self, request: cloud_redis.UpgradeInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.UpgradeInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + async def pre_upgrade_instance( + self, + request: cloud_redis.UpgradeInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.UpgradeInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for upgrade_instance Override in a subclass to manipulate the request or metadata @@ -553,7 +686,9 @@ async def pre_upgrade_instance(self, request: cloud_redis.UpgradeInstanceRequest """ return request, metadata - async def post_upgrade_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + async def post_upgrade_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for upgrade_instance DEPRECATED. Please use the `post_upgrade_instance_with_metadata` @@ -566,7 +701,11 @@ async def post_upgrade_instance(self, response: operations_pb2.Operation) -> ope """ return response - async def post_upgrade_instance_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + async def post_upgrade_instance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for upgrade_instance Override in a subclass to read or manipulate the response or metadata after it @@ -582,8 +721,12 @@ async def post_upgrade_instance_with_metadata(self, response: operations_pb2.Ope return response, metadata async def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_location Override in a subclass to manipulate the request or metadata @@ -603,8 +746,12 @@ async def post_get_location( return response async def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_locations Override in a subclass to manipulate the request or metadata @@ -624,8 +771,12 @@ async def post_list_locations( return response async def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for cancel_operation Override in a subclass to manipulate the request or metadata @@ -633,9 +784,7 @@ async def pre_cancel_operation( """ return request, metadata - async def post_cancel_operation( - self, response: None - ) -> None: + async def post_cancel_operation(self, response: None) -> None: """Post-rpc interceptor for cancel_operation Override in a subclass to manipulate the response @@ -645,8 +794,12 @@ async def post_cancel_operation( return response async def pre_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for delete_operation Override in a subclass to manipulate the request or metadata @@ -654,9 +807,7 @@ async def pre_delete_operation( """ return request, metadata - async def post_delete_operation( - self, response: None - ) -> None: + async def post_delete_operation(self, response: None) -> None: """Post-rpc interceptor for delete_operation Override in a subclass to manipulate the response @@ -666,8 +817,12 @@ async def post_delete_operation( return response async def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_operation Override in a subclass to manipulate the request or metadata @@ -687,8 +842,12 @@ async def post_get_operation( return response async def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_operations Override in a subclass to manipulate the request or metadata @@ -708,8 +867,12 @@ async def post_list_operations( return response async def pre_wait_operation( - self, request: operations_pb2.WaitOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.WaitOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.WaitOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.WaitOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for wait_operation Override in a subclass to manipulate the request or metadata @@ -735,6 +898,7 @@ class AsyncCloudRedisRestStub: _host: str _interceptor: AsyncCloudRedisRestInterceptor + class AsyncCloudRedisRestTransport(_BaseCloudRedisRestTransport): """Asynchronous REST backend transport for CloudRedis. @@ -766,38 +930,40 @@ class AsyncCloudRedisRestTransport(_BaseCloudRedisRestTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__(self, - *, - host: str = 'redis.googleapis.com', - credentials: Optional[ga_credentials_async.Credentials] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - url_scheme: str = 'https', - interceptor: Optional[AsyncCloudRedisRestInterceptor] = None, - ) -> None: + + def __init__( + self, + *, + host: str = "redis.googleapis.com", + credentials: Optional[ga_credentials_async.Credentials] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + url_scheme: str = "https", + interceptor: Optional[AsyncCloudRedisRestInterceptor] = None, + ) -> None: """Instantiate the transport. - NOTE: This async REST transport functionality is currently in a beta - state (preview). We welcome your feedback via a GitHub issue in - this library's repository. Thank you! - - Args: - host (Optional[str]): - The hostname to connect to (default: 'redis.googleapis.com'). - credentials (Optional[google.auth.aio.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - url_scheme (str): the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - interceptor (Optional[AsyncCloudRedisRestInterceptor]): Interceptor used - to manipulate requests, request metadata, and responses. + NOTE: This async REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to (default: 'redis.googleapis.com'). + credentials (Optional[google.auth.aio.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + url_scheme (str): the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[AsyncCloudRedisRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. """ # Run the base constructor super().__init__( @@ -806,16 +972,18 @@ def __init__(self, client_info=client_info, always_use_jwt_access=False, url_scheme=url_scheme, - api_audience=None + api_audience=None, ) self._session = AsyncAuthorizedSession(self._credentials) # type: ignore self._interceptor = interceptor or AsyncCloudRedisRestInterceptor() self._wrap_with_kind = True self._prep_wrapped_messages(client_info) - self._operations_client: Optional[operations_v1.AsyncOperationsRestClient] = None + self._operations_client: Optional[ + operations_v1.AsyncOperationsRestClient + ] = None def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { self.list_instances: self._wrap_method( self.list_instances, @@ -914,7 +1082,9 @@ def _wrap_method(self, func, *args, **kwargs): kwargs["kind"] = self.kind return gapic_v1.method_async.wrap_method(func, *args, **kwargs) - class _CreateInstance(_BaseCloudRedisRestTransport._BaseCreateInstance, AsyncCloudRedisRestStub): + class _CreateInstance( + _BaseCloudRedisRestTransport._BaseCreateInstance, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.CreateInstance") @@ -926,27 +1096,29 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - async def __call__(self, - request: cloud_redis.CreateInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + async def __call__( + self, + request: cloud_redis.CreateInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the create instance method over HTTP. Args: @@ -969,32 +1141,50 @@ async def __call__(self, """ - http_options = _BaseCloudRedisRestTransport._BaseCreateInstance._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseCreateInstance._get_http_options() + ) - request, metadata = await self._interceptor.pre_create_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseCreateInstance._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_create_instance( + request, metadata + ) + transcoded_request = _BaseCloudRedisRestTransport._BaseCreateInstance._get_transcoded_request( + http_options, request + ) - body = _BaseCloudRedisRestTransport._BaseCreateInstance._get_request_body_json(transcoded_request) + body = ( + _BaseCloudRedisRestTransport._BaseCreateInstance._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseCreateInstance._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseCreateInstance._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.CreateInstance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "CreateInstance", "httpRequest": http_request, @@ -1003,15 +1193,25 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._CreateInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = await AsyncCloudRedisRestTransport._CreateInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore # Return the response @@ -1021,20 +1221,24 @@ async def __call__(self, json_format.Parse(content, pb_resp, ignore_unknown_fields=True) resp = await self._interceptor.post_create_instance(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = await self._interceptor.post_create_instance_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = await self._interceptor.post_create_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), - "status": "OK", # need to obtain this properly + "headers": dict(response.headers), + "status": "OK", # need to obtain this properly } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.create_instance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "CreateInstance", "metadata": http_response["headers"], @@ -1044,7 +1248,9 @@ async def __call__(self, return resp - class _DeleteInstance(_BaseCloudRedisRestTransport._BaseDeleteInstance, AsyncCloudRedisRestStub): + class _DeleteInstance( + _BaseCloudRedisRestTransport._BaseDeleteInstance, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.DeleteInstance") @@ -1056,26 +1262,28 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - async def __call__(self, - request: cloud_redis.DeleteInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + async def __call__( + self, + request: cloud_redis.DeleteInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the delete instance method over HTTP. Args: @@ -1098,30 +1306,44 @@ async def __call__(self, """ - http_options = _BaseCloudRedisRestTransport._BaseDeleteInstance._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseDeleteInstance._get_http_options() + ) - request, metadata = await self._interceptor.pre_delete_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseDeleteInstance._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_delete_instance( + request, metadata + ) + transcoded_request = _BaseCloudRedisRestTransport._BaseDeleteInstance._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseDeleteInstance._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseDeleteInstance._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.DeleteInstance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "DeleteInstance", "httpRequest": http_request, @@ -1130,15 +1352,24 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._DeleteInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = await AsyncCloudRedisRestTransport._DeleteInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore # Return the response @@ -1148,20 +1379,24 @@ async def __call__(self, json_format.Parse(content, pb_resp, ignore_unknown_fields=True) resp = await self._interceptor.post_delete_instance(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = await self._interceptor.post_delete_instance_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = await self._interceptor.post_delete_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), - "status": "OK", # need to obtain this properly + "headers": dict(response.headers), + "status": "OK", # need to obtain this properly } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.delete_instance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "DeleteInstance", "metadata": http_response["headers"], @@ -1171,7 +1406,9 @@ async def __call__(self, return resp - class _ExportInstance(_BaseCloudRedisRestTransport._BaseExportInstance, AsyncCloudRedisRestStub): + class _ExportInstance( + _BaseCloudRedisRestTransport._BaseExportInstance, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.ExportInstance") @@ -1183,27 +1420,29 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - async def __call__(self, - request: cloud_redis.ExportInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + async def __call__( + self, + request: cloud_redis.ExportInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the export instance method over HTTP. Args: @@ -1226,32 +1465,50 @@ async def __call__(self, """ - http_options = _BaseCloudRedisRestTransport._BaseExportInstance._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseExportInstance._get_http_options() + ) - request, metadata = await self._interceptor.pre_export_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseExportInstance._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_export_instance( + request, metadata + ) + transcoded_request = _BaseCloudRedisRestTransport._BaseExportInstance._get_transcoded_request( + http_options, request + ) - body = _BaseCloudRedisRestTransport._BaseExportInstance._get_request_body_json(transcoded_request) + body = ( + _BaseCloudRedisRestTransport._BaseExportInstance._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseExportInstance._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseExportInstance._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.ExportInstance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ExportInstance", "httpRequest": http_request, @@ -1260,15 +1517,25 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._ExportInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = await AsyncCloudRedisRestTransport._ExportInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore # Return the response @@ -1278,20 +1545,24 @@ async def __call__(self, json_format.Parse(content, pb_resp, ignore_unknown_fields=True) resp = await self._interceptor.post_export_instance(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = await self._interceptor.post_export_instance_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = await self._interceptor.post_export_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), - "status": "OK", # need to obtain this properly + "headers": dict(response.headers), + "status": "OK", # need to obtain this properly } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.export_instance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ExportInstance", "metadata": http_response["headers"], @@ -1301,7 +1572,9 @@ async def __call__(self, return resp - class _FailoverInstance(_BaseCloudRedisRestTransport._BaseFailoverInstance, AsyncCloudRedisRestStub): + class _FailoverInstance( + _BaseCloudRedisRestTransport._BaseFailoverInstance, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.FailoverInstance") @@ -1313,27 +1586,29 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - async def __call__(self, - request: cloud_redis.FailoverInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + async def __call__( + self, + request: cloud_redis.FailoverInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the failover instance method over HTTP. Args: @@ -1356,32 +1631,46 @@ async def __call__(self, """ - http_options = _BaseCloudRedisRestTransport._BaseFailoverInstance._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseFailoverInstance._get_http_options() + ) - request, metadata = await self._interceptor.pre_failover_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseFailoverInstance._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_failover_instance( + request, metadata + ) + transcoded_request = _BaseCloudRedisRestTransport._BaseFailoverInstance._get_transcoded_request( + http_options, request + ) - body = _BaseCloudRedisRestTransport._BaseFailoverInstance._get_request_body_json(transcoded_request) + body = _BaseCloudRedisRestTransport._BaseFailoverInstance._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseFailoverInstance._get_query_params_json(transcoded_request) + query_params = _BaseCloudRedisRestTransport._BaseFailoverInstance._get_query_params_json( + transcoded_request + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.FailoverInstance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "FailoverInstance", "httpRequest": http_request, @@ -1390,15 +1679,27 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._FailoverInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = ( + await AsyncCloudRedisRestTransport._FailoverInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore # Return the response @@ -1408,20 +1709,24 @@ async def __call__(self, json_format.Parse(content, pb_resp, ignore_unknown_fields=True) resp = await self._interceptor.post_failover_instance(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = await self._interceptor.post_failover_instance_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = await self._interceptor.post_failover_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), - "status": "OK", # need to obtain this properly + "headers": dict(response.headers), + "status": "OK", # need to obtain this properly } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.failover_instance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "FailoverInstance", "metadata": http_response["headers"], @@ -1431,7 +1736,9 @@ async def __call__(self, return resp - class _GetInstance(_BaseCloudRedisRestTransport._BaseGetInstance, AsyncCloudRedisRestStub): + class _GetInstance( + _BaseCloudRedisRestTransport._BaseGetInstance, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.GetInstance") @@ -1443,26 +1750,28 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - async def __call__(self, - request: cloud_redis.GetInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> cloud_redis.Instance: + async def __call__( + self, + request: cloud_redis.GetInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_redis.Instance: r"""Call the get instance method over HTTP. Args: @@ -1482,30 +1791,46 @@ async def __call__(self, A Memorystore for Redis instance. """ - http_options = _BaseCloudRedisRestTransport._BaseGetInstance._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseGetInstance._get_http_options() + ) - request, metadata = await self._interceptor.pre_get_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseGetInstance._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_get_instance( + request, metadata + ) + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseGetInstance._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseGetInstance._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseGetInstance._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.GetInstance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "GetInstance", "httpRequest": http_request, @@ -1514,15 +1839,24 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._GetInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = await AsyncCloudRedisRestTransport._GetInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore # Return the response @@ -1532,20 +1866,24 @@ async def __call__(self, json_format.Parse(content, pb_resp, ignore_unknown_fields=True) resp = await self._interceptor.post_get_instance(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = await self._interceptor.post_get_instance_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = await self._interceptor.post_get_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = cloud_redis.Instance.to_json(response) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), - "status": "OK", # need to obtain this properly + "headers": dict(response.headers), + "status": "OK", # need to obtain this properly } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.get_instance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "GetInstance", "metadata": http_response["headers"], @@ -1555,7 +1893,9 @@ async def __call__(self, return resp - class _GetInstanceAuthString(_BaseCloudRedisRestTransport._BaseGetInstanceAuthString, AsyncCloudRedisRestStub): + class _GetInstanceAuthString( + _BaseCloudRedisRestTransport._BaseGetInstanceAuthString, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.GetInstanceAuthString") @@ -1567,26 +1907,28 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - async def __call__(self, - request: cloud_redis.GetInstanceAuthStringRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> cloud_redis.InstanceAuthString: + async def __call__( + self, + request: cloud_redis.GetInstanceAuthStringRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_redis.InstanceAuthString: r"""Call the get instance auth string method over HTTP. Args: @@ -1606,30 +1948,42 @@ async def __call__(self, Instance AUTH string details. """ - http_options = _BaseCloudRedisRestTransport._BaseGetInstanceAuthString._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseGetInstanceAuthString._get_http_options() + ) - request, metadata = await self._interceptor.pre_get_instance_auth_string(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseGetInstanceAuthString._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_get_instance_auth_string( + request, metadata + ) + transcoded_request = _BaseCloudRedisRestTransport._BaseGetInstanceAuthString._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseGetInstanceAuthString._get_query_params_json(transcoded_request) + query_params = _BaseCloudRedisRestTransport._BaseGetInstanceAuthString._get_query_params_json( + transcoded_request + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.GetInstanceAuthString", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "GetInstanceAuthString", "httpRequest": http_request, @@ -1638,15 +1992,26 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._GetInstanceAuthString._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = ( + await AsyncCloudRedisRestTransport._GetInstanceAuthString._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore # Return the response @@ -1656,20 +2021,27 @@ async def __call__(self, json_format.Parse(content, pb_resp, ignore_unknown_fields=True) resp = await self._interceptor.post_get_instance_auth_string(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = await self._interceptor.post_get_instance_auth_string_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + ( + resp, + _, + ) = await self._interceptor.post_get_instance_auth_string_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = cloud_redis.InstanceAuthString.to_json(response) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), - "status": "OK", # need to obtain this properly + "headers": dict(response.headers), + "status": "OK", # need to obtain this properly } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.get_instance_auth_string", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "GetInstanceAuthString", "metadata": http_response["headers"], @@ -1679,7 +2051,9 @@ async def __call__(self, return resp - class _ImportInstance(_BaseCloudRedisRestTransport._BaseImportInstance, AsyncCloudRedisRestStub): + class _ImportInstance( + _BaseCloudRedisRestTransport._BaseImportInstance, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.ImportInstance") @@ -1691,27 +2065,29 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - async def __call__(self, - request: cloud_redis.ImportInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + async def __call__( + self, + request: cloud_redis.ImportInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the import instance method over HTTP. Args: @@ -1734,32 +2110,50 @@ async def __call__(self, """ - http_options = _BaseCloudRedisRestTransport._BaseImportInstance._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseImportInstance._get_http_options() + ) - request, metadata = await self._interceptor.pre_import_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseImportInstance._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_import_instance( + request, metadata + ) + transcoded_request = _BaseCloudRedisRestTransport._BaseImportInstance._get_transcoded_request( + http_options, request + ) - body = _BaseCloudRedisRestTransport._BaseImportInstance._get_request_body_json(transcoded_request) + body = ( + _BaseCloudRedisRestTransport._BaseImportInstance._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseImportInstance._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseImportInstance._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.ImportInstance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ImportInstance", "httpRequest": http_request, @@ -1768,15 +2162,25 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._ImportInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = await AsyncCloudRedisRestTransport._ImportInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore # Return the response @@ -1786,20 +2190,24 @@ async def __call__(self, json_format.Parse(content, pb_resp, ignore_unknown_fields=True) resp = await self._interceptor.post_import_instance(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = await self._interceptor.post_import_instance_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = await self._interceptor.post_import_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), - "status": "OK", # need to obtain this properly + "headers": dict(response.headers), + "status": "OK", # need to obtain this properly } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.import_instance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ImportInstance", "metadata": http_response["headers"], @@ -1809,7 +2217,9 @@ async def __call__(self, return resp - class _ListInstances(_BaseCloudRedisRestTransport._BaseListInstances, AsyncCloudRedisRestStub): + class _ListInstances( + _BaseCloudRedisRestTransport._BaseListInstances, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.ListInstances") @@ -1821,26 +2231,28 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - async def __call__(self, - request: cloud_redis.ListInstancesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> cloud_redis.ListInstancesResponse: + async def __call__( + self, + request: cloud_redis.ListInstancesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_redis.ListInstancesResponse: r"""Call the list instances method over HTTP. Args: @@ -1862,30 +2274,46 @@ async def __call__(self, """ - http_options = _BaseCloudRedisRestTransport._BaseListInstances._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseListInstances._get_http_options() + ) - request, metadata = await self._interceptor.pre_list_instances(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseListInstances._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_list_instances( + request, metadata + ) + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseListInstances._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseListInstances._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseListInstances._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.ListInstances", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ListInstances", "httpRequest": http_request, @@ -1894,15 +2322,24 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._ListInstances._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = await AsyncCloudRedisRestTransport._ListInstances._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore # Return the response @@ -1912,20 +2349,26 @@ async def __call__(self, json_format.Parse(content, pb_resp, ignore_unknown_fields=True) resp = await self._interceptor.post_list_instances(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = await self._interceptor.post_list_instances_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = await self._interceptor.post_list_instances_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = cloud_redis.ListInstancesResponse.to_json(response) + response_payload = cloud_redis.ListInstancesResponse.to_json( + response + ) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), - "status": "OK", # need to obtain this properly + "headers": dict(response.headers), + "status": "OK", # need to obtain this properly } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.list_instances", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ListInstances", "metadata": http_response["headers"], @@ -1935,7 +2378,9 @@ async def __call__(self, return resp - class _RescheduleMaintenance(_BaseCloudRedisRestTransport._BaseRescheduleMaintenance, AsyncCloudRedisRestStub): + class _RescheduleMaintenance( + _BaseCloudRedisRestTransport._BaseRescheduleMaintenance, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.RescheduleMaintenance") @@ -1947,27 +2392,29 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - async def __call__(self, - request: cloud_redis.RescheduleMaintenanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + async def __call__( + self, + request: cloud_redis.RescheduleMaintenanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the reschedule maintenance method over HTTP. Args: @@ -1990,32 +2437,46 @@ async def __call__(self, """ - http_options = _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_http_options() + ) - request, metadata = await self._interceptor.pre_reschedule_maintenance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_reschedule_maintenance( + request, metadata + ) + transcoded_request = _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_transcoded_request( + http_options, request + ) - body = _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_request_body_json(transcoded_request) + body = _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_query_params_json(transcoded_request) + query_params = _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_query_params_json( + transcoded_request + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.RescheduleMaintenance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "RescheduleMaintenance", "httpRequest": http_request, @@ -2024,15 +2485,27 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._RescheduleMaintenance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = ( + await AsyncCloudRedisRestTransport._RescheduleMaintenance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore # Return the response @@ -2042,20 +2515,24 @@ async def __call__(self, json_format.Parse(content, pb_resp, ignore_unknown_fields=True) resp = await self._interceptor.post_reschedule_maintenance(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = await self._interceptor.post_reschedule_maintenance_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = await self._interceptor.post_reschedule_maintenance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), - "status": "OK", # need to obtain this properly + "headers": dict(response.headers), + "status": "OK", # need to obtain this properly } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.reschedule_maintenance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "RescheduleMaintenance", "metadata": http_response["headers"], @@ -2065,7 +2542,9 @@ async def __call__(self, return resp - class _UpdateInstance(_BaseCloudRedisRestTransport._BaseUpdateInstance, AsyncCloudRedisRestStub): + class _UpdateInstance( + _BaseCloudRedisRestTransport._BaseUpdateInstance, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.UpdateInstance") @@ -2077,27 +2556,29 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - async def __call__(self, - request: cloud_redis.UpdateInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + async def __call__( + self, + request: cloud_redis.UpdateInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the update instance method over HTTP. Args: @@ -2120,32 +2601,50 @@ async def __call__(self, """ - http_options = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseUpdateInstance._get_http_options() + ) - request, metadata = await self._interceptor.pre_update_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_update_instance( + request, metadata + ) + transcoded_request = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_transcoded_request( + http_options, request + ) - body = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_request_body_json(transcoded_request) + body = ( + _BaseCloudRedisRestTransport._BaseUpdateInstance._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseUpdateInstance._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.UpdateInstance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "UpdateInstance", "httpRequest": http_request, @@ -2154,15 +2653,25 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._UpdateInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = await AsyncCloudRedisRestTransport._UpdateInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore # Return the response @@ -2172,20 +2681,24 @@ async def __call__(self, json_format.Parse(content, pb_resp, ignore_unknown_fields=True) resp = await self._interceptor.post_update_instance(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = await self._interceptor.post_update_instance_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = await self._interceptor.post_update_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), - "status": "OK", # need to obtain this properly + "headers": dict(response.headers), + "status": "OK", # need to obtain this properly } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.update_instance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "UpdateInstance", "metadata": http_response["headers"], @@ -2195,7 +2708,9 @@ async def __call__(self, return resp - class _UpgradeInstance(_BaseCloudRedisRestTransport._BaseUpgradeInstance, AsyncCloudRedisRestStub): + class _UpgradeInstance( + _BaseCloudRedisRestTransport._BaseUpgradeInstance, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.UpgradeInstance") @@ -2207,27 +2722,29 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - async def __call__(self, - request: cloud_redis.UpgradeInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + async def __call__( + self, + request: cloud_redis.UpgradeInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the upgrade instance method over HTTP. Args: @@ -2250,32 +2767,46 @@ async def __call__(self, """ - http_options = _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_http_options() + ) - request, metadata = await self._interceptor.pre_upgrade_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_upgrade_instance( + request, metadata + ) + transcoded_request = _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_transcoded_request( + http_options, request + ) - body = _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_request_body_json(transcoded_request) + body = _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_query_params_json(transcoded_request) + query_params = _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_query_params_json( + transcoded_request + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.UpgradeInstance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "UpgradeInstance", "httpRequest": http_request, @@ -2284,15 +2815,27 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._UpgradeInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = ( + await AsyncCloudRedisRestTransport._UpgradeInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore # Return the response @@ -2302,20 +2845,24 @@ async def __call__(self, json_format.Parse(content, pb_resp, ignore_unknown_fields=True) resp = await self._interceptor.post_upgrade_instance(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = await self._interceptor.post_upgrade_instance_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = await self._interceptor.post_upgrade_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), - "status": "OK", # need to obtain this properly + "headers": dict(response.headers), + "status": "OK", # need to obtain this properly } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.upgrade_instance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "UpgradeInstance", "metadata": http_response["headers"], @@ -2335,123 +2882,131 @@ def operations_client(self) -> AsyncOperationsRestClient: # Only create a new client if we do not already have one. if self._operations_client is None: http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ + "google.longrunning.Operations.CancelOperation": [ { - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", }, ], - 'google.longrunning.Operations.DeleteOperation': [ + "google.longrunning.Operations.DeleteOperation": [ { - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", }, ], - 'google.longrunning.Operations.GetOperation': [ + "google.longrunning.Operations.GetOperation": [ { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", }, ], - 'google.longrunning.Operations.ListOperations': [ + "google.longrunning.Operations.ListOperations": [ { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", }, ], - 'google.longrunning.Operations.WaitOperation': [ + "google.longrunning.Operations.WaitOperation": [ { - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}:wait', - 'body': '*', + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/operations/*}:wait", + "body": "*", }, ], } rest_transport = operations_v1.AsyncOperationsRestTransport( # type: ignore - host=self._host, - # use the credentials which are saved - credentials=self._credentials, # type: ignore - http_options=http_options, - path_prefix="v1" + host=self._host, + # use the credentials which are saved + credentials=self._credentials, # type: ignore + http_options=http_options, + path_prefix="v1", ) - self._operations_client = AsyncOperationsRestClient(transport=rest_transport) + self._operations_client = AsyncOperationsRestClient( + transport=rest_transport + ) # Return the client from cache. return self._operations_client @property - def create_instance(self) -> Callable[ - [cloud_redis.CreateInstanceRequest], - operations_pb2.Operation]: + def create_instance( + self, + ) -> Callable[[cloud_redis.CreateInstanceRequest], operations_pb2.Operation]: return self._CreateInstance(self._session, self._host, self._interceptor) # type: ignore @property - def delete_instance(self) -> Callable[ - [cloud_redis.DeleteInstanceRequest], - operations_pb2.Operation]: + def delete_instance( + self, + ) -> Callable[[cloud_redis.DeleteInstanceRequest], operations_pb2.Operation]: return self._DeleteInstance(self._session, self._host, self._interceptor) # type: ignore @property - def export_instance(self) -> Callable[ - [cloud_redis.ExportInstanceRequest], - operations_pb2.Operation]: + def export_instance( + self, + ) -> Callable[[cloud_redis.ExportInstanceRequest], operations_pb2.Operation]: return self._ExportInstance(self._session, self._host, self._interceptor) # type: ignore @property - def failover_instance(self) -> Callable[ - [cloud_redis.FailoverInstanceRequest], - operations_pb2.Operation]: + def failover_instance( + self, + ) -> Callable[[cloud_redis.FailoverInstanceRequest], operations_pb2.Operation]: return self._FailoverInstance(self._session, self._host, self._interceptor) # type: ignore @property - def get_instance(self) -> Callable[ - [cloud_redis.GetInstanceRequest], - cloud_redis.Instance]: + def get_instance( + self, + ) -> Callable[[cloud_redis.GetInstanceRequest], cloud_redis.Instance]: return self._GetInstance(self._session, self._host, self._interceptor) # type: ignore @property - def get_instance_auth_string(self) -> Callable[ - [cloud_redis.GetInstanceAuthStringRequest], - cloud_redis.InstanceAuthString]: + def get_instance_auth_string( + self, + ) -> Callable[ + [cloud_redis.GetInstanceAuthStringRequest], cloud_redis.InstanceAuthString + ]: return self._GetInstanceAuthString(self._session, self._host, self._interceptor) # type: ignore @property - def import_instance(self) -> Callable[ - [cloud_redis.ImportInstanceRequest], - operations_pb2.Operation]: + def import_instance( + self, + ) -> Callable[[cloud_redis.ImportInstanceRequest], operations_pb2.Operation]: return self._ImportInstance(self._session, self._host, self._interceptor) # type: ignore @property - def list_instances(self) -> Callable[ - [cloud_redis.ListInstancesRequest], - cloud_redis.ListInstancesResponse]: + def list_instances( + self, + ) -> Callable[ + [cloud_redis.ListInstancesRequest], cloud_redis.ListInstancesResponse + ]: return self._ListInstances(self._session, self._host, self._interceptor) # type: ignore @property - def reschedule_maintenance(self) -> Callable[ - [cloud_redis.RescheduleMaintenanceRequest], - operations_pb2.Operation]: + def reschedule_maintenance( + self, + ) -> Callable[[cloud_redis.RescheduleMaintenanceRequest], operations_pb2.Operation]: return self._RescheduleMaintenance(self._session, self._host, self._interceptor) # type: ignore @property - def update_instance(self) -> Callable[ - [cloud_redis.UpdateInstanceRequest], - operations_pb2.Operation]: + def update_instance( + self, + ) -> Callable[[cloud_redis.UpdateInstanceRequest], operations_pb2.Operation]: return self._UpdateInstance(self._session, self._host, self._interceptor) # type: ignore @property - def upgrade_instance(self) -> Callable[ - [cloud_redis.UpgradeInstanceRequest], - operations_pb2.Operation]: + def upgrade_instance( + self, + ) -> Callable[[cloud_redis.UpgradeInstanceRequest], operations_pb2.Operation]: return self._UpgradeInstance(self._session, self._host, self._interceptor) # type: ignore @property def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - class _GetLocation(_BaseCloudRedisRestTransport._BaseGetLocation, AsyncCloudRedisRestStub): + class _GetLocation( + _BaseCloudRedisRestTransport._BaseGetLocation, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.GetLocation") @@ -2463,27 +3018,28 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - async def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> locations_pb2.Location: - + async def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: r"""Call the get location method over HTTP. Args: @@ -2501,30 +3057,46 @@ async def __call__(self, locations_pb2.Location: Response from GetLocation method. """ - http_options = _BaseCloudRedisRestTransport._BaseGetLocation._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseGetLocation._get_http_options() + ) - request, metadata = await self._interceptor.pre_get_location(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_get_location( + request, metadata + ) + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseGetLocation._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.GetLocation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "GetLocation", "httpRequest": http_request, @@ -2533,34 +3105,45 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = await AsyncCloudRedisRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore content = await response.read() resp = locations_pb2.Location() resp = json_format.Parse(content, resp) resp = await self._interceptor.post_get_location(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.GetLocation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "GetLocation", "httpResponse": http_response, @@ -2571,9 +3154,11 @@ async def __call__(self, @property def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - class _ListLocations(_BaseCloudRedisRestTransport._BaseListLocations, AsyncCloudRedisRestStub): + class _ListLocations( + _BaseCloudRedisRestTransport._BaseListLocations, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.ListLocations") @@ -2585,27 +3170,28 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - async def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> locations_pb2.ListLocationsResponse: - + async def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: r"""Call the list locations method over HTTP. Args: @@ -2623,30 +3209,46 @@ async def __call__(self, locations_pb2.ListLocationsResponse: Response from ListLocations method. """ - http_options = _BaseCloudRedisRestTransport._BaseListLocations._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseListLocations._get_http_options() + ) - request, metadata = await self._interceptor.pre_list_locations(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseListLocations._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_list_locations( + request, metadata + ) + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseListLocations._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseListLocations._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.ListLocations", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ListLocations", "httpRequest": http_request, @@ -2655,34 +3257,45 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = await AsyncCloudRedisRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore content = await response.read() resp = locations_pb2.ListLocationsResponse() resp = json_format.Parse(content, resp) resp = await self._interceptor.post_list_locations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.ListLocations", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ListLocations", "httpResponse": http_response, @@ -2693,9 +3306,11 @@ async def __call__(self, @property def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - class _CancelOperation(_BaseCloudRedisRestTransport._BaseCancelOperation, AsyncCloudRedisRestStub): + class _CancelOperation( + _BaseCloudRedisRestTransport._BaseCancelOperation, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.CancelOperation") @@ -2707,27 +3322,28 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - async def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> None: - + async def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Call the cancel operation method over HTTP. Args: @@ -2742,30 +3358,42 @@ async def __call__(self, be of type `bytes`. """ - http_options = _BaseCloudRedisRestTransport._BaseCancelOperation._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseCancelOperation._get_http_options() + ) - request, metadata = await self._interceptor.pre_cancel_operation(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = _BaseCloudRedisRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) + query_params = _BaseCloudRedisRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.CancelOperation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "CancelOperation", "httpRequest": http_request, @@ -2774,24 +3402,37 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._CancelOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = ( + await AsyncCloudRedisRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore return await self._interceptor.post_cancel_operation(None) @property def delete_operation(self): - return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - class _DeleteOperation(_BaseCloudRedisRestTransport._BaseDeleteOperation, AsyncCloudRedisRestStub): + class _DeleteOperation( + _BaseCloudRedisRestTransport._BaseDeleteOperation, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.DeleteOperation") @@ -2803,27 +3444,28 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - async def __call__(self, - request: operations_pb2.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> None: - + async def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Call the delete operation method over HTTP. Args: @@ -2838,30 +3480,42 @@ async def __call__(self, be of type `bytes`. """ - http_options = _BaseCloudRedisRestTransport._BaseDeleteOperation._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseDeleteOperation._get_http_options() + ) - request, metadata = await self._interceptor.pre_delete_operation(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_delete_operation( + request, metadata + ) + transcoded_request = _BaseCloudRedisRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) + query_params = _BaseCloudRedisRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.DeleteOperation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "DeleteOperation", "httpRequest": http_request, @@ -2870,24 +3524,37 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._DeleteOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = ( + await AsyncCloudRedisRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore return await self._interceptor.post_delete_operation(None) @property def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(_BaseCloudRedisRestTransport._BaseGetOperation, AsyncCloudRedisRestStub): + class _GetOperation( + _BaseCloudRedisRestTransport._BaseGetOperation, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.GetOperation") @@ -2899,27 +3566,28 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - async def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - + async def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the get operation method over HTTP. Args: @@ -2937,30 +3605,46 @@ async def __call__(self, operations_pb2.Operation: Response from GetOperation method. """ - http_options = _BaseCloudRedisRestTransport._BaseGetOperation._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseGetOperation._get_http_options() + ) - request, metadata = await self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_get_operation( + request, metadata + ) + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.GetOperation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "GetOperation", "httpRequest": http_request, @@ -2969,34 +3653,45 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = await AsyncCloudRedisRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore content = await response.read() resp = operations_pb2.Operation() resp = json_format.Parse(content, resp) resp = await self._interceptor.post_get_operation(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.GetOperation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "GetOperation", "httpResponse": http_response, @@ -3007,9 +3702,11 @@ async def __call__(self, @property def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(_BaseCloudRedisRestTransport._BaseListOperations, AsyncCloudRedisRestStub): + class _ListOperations( + _BaseCloudRedisRestTransport._BaseListOperations, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.ListOperations") @@ -3021,27 +3718,28 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - async def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.ListOperationsResponse: - + async def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: r"""Call the list operations method over HTTP. Args: @@ -3059,30 +3757,44 @@ async def __call__(self, operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options = _BaseCloudRedisRestTransport._BaseListOperations._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseListOperations._get_http_options() + ) - request, metadata = await self._interceptor.pre_list_operations(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseListOperations._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_list_operations( + request, metadata + ) + transcoded_request = _BaseCloudRedisRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseListOperations._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.ListOperations", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ListOperations", "httpRequest": http_request, @@ -3091,34 +3803,45 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = await AsyncCloudRedisRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore content = await response.read() resp = operations_pb2.ListOperationsResponse() resp = json_format.Parse(content, resp) resp = await self._interceptor.post_list_operations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.ListOperations", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ListOperations", "httpResponse": http_response, @@ -3129,9 +3852,11 @@ async def __call__(self, @property def wait_operation(self): - return self._WaitOperation(self._session, self._host, self._interceptor) # type: ignore + return self._WaitOperation(self._session, self._host, self._interceptor) # type: ignore - class _WaitOperation(_BaseCloudRedisRestTransport._BaseWaitOperation, AsyncCloudRedisRestStub): + class _WaitOperation( + _BaseCloudRedisRestTransport._BaseWaitOperation, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.WaitOperation") @@ -3143,28 +3868,29 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - async def __call__(self, - request: operations_pb2.WaitOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - + async def __call__( + self, + request: operations_pb2.WaitOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the wait operation method over HTTP. Args: @@ -3182,32 +3908,52 @@ async def __call__(self, operations_pb2.Operation: Response from WaitOperation method. """ - http_options = _BaseCloudRedisRestTransport._BaseWaitOperation._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseWaitOperation._get_http_options() + ) - request, metadata = await self._interceptor.pre_wait_operation(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseWaitOperation._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_wait_operation( + request, metadata + ) + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseWaitOperation._get_transcoded_request( + http_options, request + ) + ) - body = _BaseCloudRedisRestTransport._BaseWaitOperation._get_request_body_json(transcoded_request) + body = ( + _BaseCloudRedisRestTransport._BaseWaitOperation._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseWaitOperation._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseWaitOperation._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.WaitOperation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "WaitOperation", "httpRequest": http_request, @@ -3216,34 +3962,46 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._WaitOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = await AsyncCloudRedisRestTransport._WaitOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore content = await response.read() resp = operations_pb2.Operation() resp = json_format.Parse(content, resp) resp = await self._interceptor.post_wait_operation(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.WaitOperation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "WaitOperation", "httpResponse": http_response, diff --git a/packages/gapic-generator/tests/integration/goldens/redis/setup.py b/packages/gapic-generator/tests/integration/goldens/redis/setup.py index 02095ef25809..0ddf593dccc7 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/setup.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/setup.py @@ -17,23 +17,23 @@ import os import re -import setuptools # type: ignore +import setuptools # type: ignore package_root = os.path.abspath(os.path.dirname(__file__)) -name = 'google-cloud-redis' +name = "google-cloud-redis" description = "Google Cloud Redis API client library" version = None -with open(os.path.join(package_root, 'google/cloud/redis/gapic_version.py')) as fp: +with open(os.path.join(package_root, "google/cloud/redis/gapic_version.py")) as fp: version_candidates = re.findall( r"(?<=\")\d+\.\d+\.\d+[^\"\s]*(?=\")", fp.read(), ) - assert (len(version_candidates) == 1) + assert len(version_candidates) == 1 version = version_candidates[0] if version[0] == "0": @@ -52,9 +52,7 @@ "protobuf >= 6.33.5, < 8.0.0", ] extras = { - "async_rest": [ - "google-auth[aiohttp] >= 2.35.0, <3.0.0" - ], + "async_rest": ["google-auth[aiohttp] >= 2.35.0, <3.0.0"], } url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-redis" diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/__init__.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/__init__.py index 043562140c7d..4c5a72d4111d 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/__init__.py @@ -47,10 +47,12 @@ from .types.cloud_redis import WeeklyMaintenanceWindow from .types.cloud_redis import ZoneMetadata -if hasattr(api_core, "check_python_version") and hasattr(api_core, "check_dependency_versions"): # pragma: NO COVER - api_core.check_python_version("google.cloud.redis_v1") # type: ignore - api_core.check_dependency_versions("google.cloud.redis_v1") # type: ignore -else: # pragma: NO COVER +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.cloud.redis_v1") # type: ignore + api_core.check_dependency_versions("google.cloud.redis_v1") # type: ignore +else: # pragma: NO COVER # An older version of api_core is installed which does not define the # functions above. We do equivalent checks manually. try: @@ -59,12 +61,14 @@ _py_version_str = sys.version.split()[0] _package_label = "google.cloud.redis_v1" if sys.version_info < (3, 10): - warnings.warn("You are using a non-supported Python version " + - f"({_py_version_str}). Google will not post any further " + - f"updates to {_package_label} supporting this Python version. " + - "Please upgrade to the latest Python version, or at " + - f"least to Python 3.10, and then update {_package_label}.", - FutureWarning) + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.10, and then update {_package_label}.", + FutureWarning, + ) def parse_version_to_tuple(version_string: str): """Safely converts a semantic version string to a comparable tuple of integers. @@ -102,47 +106,51 @@ def _get_version(dependency_name): _recommendation = " (we recommend 7.x)" (_version_used, _version_used_string) = _get_version(_dependency_package) if _version_used and _version_used < _next_supported_version_tuple: - warnings.warn(f"Package {_package_label} depends on " + - f"{_dependency_package}, currently installed at version " + - f"{_version_used_string}. Future updates to " + - f"{_package_label} will require {_dependency_package} at " + - f"version {_next_supported_version} or higher{_recommendation}." + - " Please ensure " + - "that either (a) your Python environment doesn't pin the " + - f"version of {_dependency_package}, so that updates to " + - f"{_package_label} can require the higher version, or " + - "(b) you manually update your Python environment to use at " + - f"least version {_next_supported_version} of " + - f"{_dependency_package}.", - FutureWarning) + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) except Exception: - warnings.warn("Could not determine the version of Python " + - "currently being used. To continue receiving " + - "updates for {_package_label}, ensure you are " + - "using a supported version of Python; see " + - "https://devguide.python.org/versions/") + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) __all__ = ( - 'CloudRedisAsyncClient', -'CloudRedisClient', -'CreateInstanceRequest', -'DeleteInstanceRequest', -'GcsDestination', -'GcsSource', -'GetInstanceRequest', -'InputConfig', -'Instance', -'ListInstancesRequest', -'ListInstancesResponse', -'LocationMetadata', -'MaintenancePolicy', -'MaintenanceSchedule', -'NodeInfo', -'OperationMetadata', -'OutputConfig', -'PersistenceConfig', -'TlsCertificate', -'UpdateInstanceRequest', -'WeeklyMaintenanceWindow', -'ZoneMetadata', + "CloudRedisAsyncClient", + "CloudRedisClient", + "CreateInstanceRequest", + "DeleteInstanceRequest", + "GcsDestination", + "GcsSource", + "GetInstanceRequest", + "InputConfig", + "Instance", + "ListInstancesRequest", + "ListInstancesResponse", + "LocationMetadata", + "MaintenancePolicy", + "MaintenanceSchedule", + "NodeInfo", + "OperationMetadata", + "OutputConfig", + "PersistenceConfig", + "TlsCertificate", + "UpdateInstanceRequest", + "WeeklyMaintenanceWindow", + "ZoneMetadata", ) diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/async_client.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/async_client.py index 4fe84212c68f..6a68a85d3ceb 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/async_client.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/async_client.py @@ -16,7 +16,18 @@ import logging as std_logging from collections import OrderedDict import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union +from typing import ( + Dict, + Callable, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) from google.cloud.redis_v1 import gapic_version as package_version @@ -24,8 +35,8 @@ from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf @@ -34,10 +45,10 @@ except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore -from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.cloud.redis_v1.services.cloud_redis import pagers from google.cloud.redis_v1.types import cloud_redis -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.api_core.operation as operation # type: ignore import google.api_core.operation_async as operation_async # type: ignore import google.protobuf.empty_pb2 as empty_pb2 # type: ignore @@ -49,12 +60,14 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) + class CloudRedisAsyncClient: """Configures and manages Cloud Memorystore for Redis instances @@ -90,16 +103,24 @@ class CloudRedisAsyncClient: instance_path = staticmethod(CloudRedisClient.instance_path) parse_instance_path = staticmethod(CloudRedisClient.parse_instance_path) - common_billing_account_path = staticmethod(CloudRedisClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CloudRedisClient.parse_common_billing_account_path) + common_billing_account_path = staticmethod( + CloudRedisClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + CloudRedisClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(CloudRedisClient.common_folder_path) parse_common_folder_path = staticmethod(CloudRedisClient.parse_common_folder_path) common_organization_path = staticmethod(CloudRedisClient.common_organization_path) - parse_common_organization_path = staticmethod(CloudRedisClient.parse_common_organization_path) + parse_common_organization_path = staticmethod( + CloudRedisClient.parse_common_organization_path + ) common_project_path = staticmethod(CloudRedisClient.common_project_path) parse_common_project_path = staticmethod(CloudRedisClient.parse_common_project_path) common_location_path = staticmethod(CloudRedisClient.common_location_path) - parse_common_location_path = staticmethod(CloudRedisClient.parse_common_location_path) + parse_common_location_path = staticmethod( + CloudRedisClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -141,7 +162,9 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): """Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -204,12 +227,16 @@ def universe_domain(self) -> str: get_transport_class = CloudRedisClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, CloudRedisTransport, Callable[..., CloudRedisTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, CloudRedisTransport, Callable[..., CloudRedisTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the cloud redis async client. Args: @@ -267,31 +294,39 @@ def __init__(self, *, transport=transport, client_options=client_options, client_info=client_info, - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.redis_v1.CloudRedisAsyncClient`.", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { "serviceName": "google.cloud.redis.v1.CloudRedis", "credentialsType": None, - } + }, ) - async def list_instances(self, - request: Optional[Union[cloud_redis.ListInstancesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListInstancesAsyncPager: + async def list_instances( + self, + request: Optional[Union[cloud_redis.ListInstancesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListInstancesAsyncPager: r"""Lists all Redis instances owned by a project in either the specified location (region) or all locations. @@ -364,10 +399,14 @@ async def sample_list_instances(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -381,14 +420,14 @@ async def sample_list_instances(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_instances] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_instances + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -416,14 +455,15 @@ async def sample_list_instances(): # Done; return the response. return response - async def get_instance(self, - request: Optional[Union[cloud_redis.GetInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> cloud_redis.Instance: + async def get_instance( + self, + request: Optional[Union[cloud_redis.GetInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_redis.Instance: r"""Gets the details of a specific Redis instance. .. code-block:: python @@ -480,10 +520,14 @@ async def sample_get_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -497,14 +541,14 @@ async def sample_get_instance(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_instance] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_instance + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -521,16 +565,17 @@ async def sample_get_instance(): # Done; return the response. return response - async def create_instance(self, - request: Optional[Union[cloud_redis.CreateInstanceRequest, dict]] = None, - *, - parent: Optional[str] = None, - instance_id: Optional[str] = None, - instance: Optional[cloud_redis.Instance] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def create_instance( + self, + request: Optional[Union[cloud_redis.CreateInstanceRequest, dict]] = None, + *, + parent: Optional[str] = None, + instance_id: Optional[str] = None, + instance: Optional[cloud_redis.Instance] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Creates a Redis instance based on the specified tier and memory size. @@ -636,10 +681,14 @@ async def sample_create_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, instance_id, instance] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -657,14 +706,14 @@ async def sample_create_instance(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_instance] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_instance + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -689,15 +738,16 @@ async def sample_create_instance(): # Done; return the response. return response - async def update_instance(self, - request: Optional[Union[cloud_redis.UpdateInstanceRequest, dict]] = None, - *, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - instance: Optional[cloud_redis.Instance] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def update_instance( + self, + request: Optional[Union[cloud_redis.UpdateInstanceRequest, dict]] = None, + *, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + instance: Optional[cloud_redis.Instance] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Updates the metadata and configuration of a specific Redis instance. Completed longrunning.Operation will contain the new @@ -787,10 +837,14 @@ async def sample_update_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [update_mask, instance] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -806,14 +860,16 @@ async def sample_update_instance(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_instance] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_instance + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("instance.name", request.instance.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("instance.name", request.instance.name),) + ), ) # Validate the universe domain. @@ -838,14 +894,15 @@ async def sample_update_instance(): # Done; return the response. return response - async def delete_instance(self, - request: Optional[Union[cloud_redis.DeleteInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def delete_instance( + self, + request: Optional[Union[cloud_redis.DeleteInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Deletes a specific Redis instance. Instance stops serving and data is deleted. @@ -919,10 +976,14 @@ async def sample_delete_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -936,14 +997,14 @@ async def sample_delete_instance(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_instance] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_instance + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1010,8 +1071,7 @@ async def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1019,7 +1079,11 @@ async def list_operations( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1066,8 +1130,7 @@ async def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1075,7 +1138,11 @@ async def get_operation( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1126,15 +1193,19 @@ async def delete_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) async def cancel_operation( self, @@ -1181,15 +1252,19 @@ async def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) async def wait_operation( self, @@ -1239,8 +1314,7 @@ async def wait_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1248,7 +1322,11 @@ async def wait_operation( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1295,8 +1373,7 @@ async def get_location( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1304,7 +1381,11 @@ async def get_location( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1351,8 +1432,7 @@ async def list_locations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1360,7 +1440,11 @@ async def list_locations( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1371,12 +1455,13 @@ async def __aenter__(self) -> "CloudRedisAsyncClient": async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "CloudRedisAsyncClient", -) +__all__ = ("CloudRedisAsyncClient",) diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py index bfbfe9f50c4a..53f0feb56edb 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py @@ -19,7 +19,19 @@ import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +from typing import ( + Dict, + Callable, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) import warnings from google.cloud.redis_v1 import gapic_version as package_version @@ -28,11 +40,11 @@ from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.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.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 import google.protobuf try: @@ -42,16 +54,17 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) -from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.cloud.redis_v1.services.cloud_redis import pagers from google.cloud.redis_v1.types import cloud_redis -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.api_core.operation as operation # type: ignore import google.api_core.operation_async as operation_async # type: ignore import google.protobuf.empty_pb2 as empty_pb2 # type: ignore @@ -61,11 +74,13 @@ from .transports.grpc import CloudRedisGrpcTransport from .transports.grpc_asyncio import CloudRedisGrpcAsyncIOTransport from .transports.rest import CloudRedisRestTransport + ASYNC_REST_EXCEPTION = None try: from .transports.rest_asyncio import AsyncCloudRedisRestTransport + HAS_ASYNC_REST_DEPENDENCIES = True -except ImportError as e: # pragma: NO COVER +except ImportError as e: # pragma: NO COVER HAS_ASYNC_REST_DEPENDENCIES = False ASYNC_REST_EXCEPTION = e @@ -77,6 +92,7 @@ class CloudRedisClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ + _transport_registry = OrderedDict() # type: Dict[str, Type[CloudRedisTransport]] _transport_registry["grpc"] = CloudRedisGrpcTransport _transport_registry["grpc_asyncio"] = CloudRedisGrpcAsyncIOTransport @@ -84,9 +100,10 @@ class CloudRedisClientMeta(type): if HAS_ASYNC_REST_DEPENDENCIES: # pragma: NO COVER _transport_registry["rest_asyncio"] = AsyncCloudRedisRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[CloudRedisTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[CloudRedisTransport]: """Returns an appropriate transport class. Args: @@ -97,7 +114,9 @@ def get_transport_class(cls, The transport class to use. """ # If a specific transport is requested, return that one. - if label == "rest_asyncio" and not HAS_ASYNC_REST_DEPENDENCIES: # pragma: NO COVER + if ( + label == "rest_asyncio" and not HAS_ASYNC_REST_DEPENDENCIES + ): # pragma: NO COVER raise ASYNC_REST_EXCEPTION if label: return cls._transport_registry[label] @@ -185,14 +204,16 @@ def _use_client_cert_effective(): bool: whether client certificate should be used for mTLS Raises: ValueError: (If using a version of google-auth without should_use_client_cert and - GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) """ # check if google-auth version supports should_use_client_cert for automatic mTLS enablement if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER return mtls.should_use_client_cert() - else: # pragma: NO COVER + else: # pragma: NO COVER # if unsupported, fallback to reading from env var - use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() if use_client_cert_str not in ("true", "false"): raise ValueError( "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" @@ -231,8 +252,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CloudRedisClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -249,73 +269,108 @@ def transport(self) -> CloudRedisTransport: return self._transport @staticmethod - def instance_path(project: str,location: str,instance: str,) -> str: + def instance_path( + project: str, + location: str, + instance: str, + ) -> str: """Returns a fully-qualified instance string.""" - return "projects/{project}/locations/{location}/instances/{instance}".format(project=project, location=location, instance=instance, ) + return "projects/{project}/locations/{location}/instances/{instance}".format( + project=project, + location=location, + instance=instance, + ) @staticmethod - def parse_instance_path(path: str) -> Dict[str,str]: + def parse_instance_path(path: str) -> Dict[str, str]: """Parses a instance path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + def common_billing_account_path( + billing_account: str, + ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path(folder: str, ) -> str: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path(organization: str, ) -> str: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path(project: str, ) -> str: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path(project: str, location: str, ) -> str: + def common_location_path( + project: str, + location: str, + ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -347,14 +402,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = CloudRedisClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Figure out the client cert source to use. client_cert_source = None @@ -367,7 +426,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): api_endpoint = cls.DEFAULT_MTLS_ENDPOINT else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -392,7 +453,9 @@ def _read_environment_variables(): use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod @@ -415,7 +478,9 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: """Return the API endpoint used by the client. Args: @@ -431,17 +496,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): _default_universe = CloudRedisClient._DEFAULT_UNIVERSE if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) api_endpoint = CloudRedisClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = CloudRedisClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = CloudRedisClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) return api_endpoint @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: """Return the universe domain used by the client. Args: @@ -477,15 +550,18 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError + self, error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: return cred = self._transport._credentials @@ -518,12 +594,16 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, CloudRedisTransport, Callable[..., CloudRedisTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, CloudRedisTransport, Callable[..., CloudRedisTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the cloud redis client. Args: @@ -581,13 +661,23 @@ def __init__(self, *, self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = CloudRedisClient._read_environment_variables() - self._client_cert_source = CloudRedisClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = CloudRedisClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = CloudRedisClient._read_environment_variables() + self._client_cert_source = CloudRedisClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = CloudRedisClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -599,7 +689,9 @@ def __init__(self, *, api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -608,8 +700,10 @@ def __init__(self, *, if transport_provided: # transport is a CloudRedisTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if self._client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes " @@ -618,15 +712,17 @@ def __init__(self, *, self._transport = cast(CloudRedisTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - CloudRedisClient._get_api_endpoint( - self._client_options.api_endpoint, - self._client_cert_source, - self._universe_domain, - self._use_mtls_endpoint)) + self._api_endpoint = self._api_endpoint or CloudRedisClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) if not transport_provided: - transport_init: Union[Type[CloudRedisTransport], Callable[..., CloudRedisTransport]] = ( + transport_init: Union[ + Type[CloudRedisTransport], Callable[..., CloudRedisTransport] + ] = ( CloudRedisClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., CloudRedisTransport], transport) @@ -639,9 +735,12 @@ def __init__(self, *, "google.api_core.client_options.ClientOptions.quota_project_id": self._client_options.quota_project_id, "google.api_core.client_options.ClientOptions.client_cert_source": self._client_options.client_cert_source, "google.api_core.client_options.ClientOptions.api_audience": self._client_options.api_audience, - } - provided_unsupported_params = [name for name, value in unsupported_params.items() if value is not None] + provided_unsupported_params = [ + name + for name, value in unsupported_params.items() + if value is not None + ] if provided_unsupported_params: raise core_exceptions.AsyncRestUnsupportedParameterError( # type: ignore f"The following provided parameters are not supported for `transport=rest_asyncio`: {', '.join(provided_unsupported_params)}" @@ -655,8 +754,12 @@ def __init__(self, *, import google.auth._default # type: ignore - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) # initialize with the provided callable or the passed in class self._transport = transport_init( @@ -672,28 +775,37 @@ def __init__(self, *, ) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.redis_v1.CloudRedisClient`.", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { "serviceName": "google.cloud.redis.v1.CloudRedis", "credentialsType": None, - } + }, ) - def list_instances(self, - request: Optional[Union[cloud_redis.ListInstancesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListInstancesPager: + def list_instances( + self, + request: Optional[Union[cloud_redis.ListInstancesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListInstancesPager: r"""Lists all Redis instances owned by a project in either the specified location (region) or all locations. @@ -766,10 +878,14 @@ def sample_list_instances(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -787,9 +903,7 @@ def sample_list_instances(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -817,14 +931,15 @@ def sample_list_instances(): # Done; return the response. return response - def get_instance(self, - request: Optional[Union[cloud_redis.GetInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> cloud_redis.Instance: + def get_instance( + self, + request: Optional[Union[cloud_redis.GetInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_redis.Instance: r"""Gets the details of a specific Redis instance. .. code-block:: python @@ -881,10 +996,14 @@ def sample_get_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -902,9 +1021,7 @@ def sample_get_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -921,16 +1038,17 @@ def sample_get_instance(): # Done; return the response. return response - def create_instance(self, - request: Optional[Union[cloud_redis.CreateInstanceRequest, dict]] = None, - *, - parent: Optional[str] = None, - instance_id: Optional[str] = None, - instance: Optional[cloud_redis.Instance] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_instance( + self, + request: Optional[Union[cloud_redis.CreateInstanceRequest, dict]] = None, + *, + parent: Optional[str] = None, + instance_id: Optional[str] = None, + instance: Optional[cloud_redis.Instance] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Creates a Redis instance based on the specified tier and memory size. @@ -1036,10 +1154,14 @@ def sample_create_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, instance_id, instance] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1061,9 +1183,7 @@ def sample_create_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1088,15 +1208,16 @@ def sample_create_instance(): # Done; return the response. return response - def update_instance(self, - request: Optional[Union[cloud_redis.UpdateInstanceRequest, dict]] = None, - *, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - instance: Optional[cloud_redis.Instance] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_instance( + self, + request: Optional[Union[cloud_redis.UpdateInstanceRequest, dict]] = None, + *, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + instance: Optional[cloud_redis.Instance] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Updates the metadata and configuration of a specific Redis instance. Completed longrunning.Operation will contain the new @@ -1186,10 +1307,14 @@ def sample_update_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [update_mask, instance] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1209,9 +1334,9 @@ def sample_update_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("instance.name", request.instance.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("instance.name", request.instance.name),) + ), ) # Validate the universe domain. @@ -1236,14 +1361,15 @@ def sample_update_instance(): # Done; return the response. return response - def delete_instance(self, - request: Optional[Union[cloud_redis.DeleteInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_instance( + self, + request: Optional[Union[cloud_redis.DeleteInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Deletes a specific Redis instance. Instance stops serving and data is deleted. @@ -1317,10 +1443,14 @@ def sample_delete_instance(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1338,9 +1468,7 @@ def sample_delete_instance(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1420,8 +1548,7 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1430,7 +1557,11 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1480,8 +1611,7 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1490,7 +1620,11 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1544,15 +1678,19 @@ def delete_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) def cancel_operation( self, @@ -1599,15 +1737,19 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) def wait_operation( self, @@ -1657,8 +1799,7 @@ def wait_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1667,7 +1808,11 @@ def wait_operation( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1717,8 +1862,7 @@ def get_location( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1727,7 +1871,11 @@ def get_location( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1777,8 +1925,7 @@ def list_locations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1787,7 +1934,11 @@ def list_locations( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1796,11 +1947,11 @@ def list_locations( raise e -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "CloudRedisClient", -) +__all__ = ("CloudRedisClient",) diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/base.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/base.py index 7568952b9032..ffa7471c6158 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/base.py @@ -25,14 +25,16 @@ from google.api_core import retry as retries from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf -from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.cloud.redis_v1.types import cloud_redis -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ @@ -41,24 +43,23 @@ class CloudRedisTransport(abc.ABC): """Abstract transport class for CloudRedis.""" - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - DEFAULT_HOST: str = 'redis.googleapis.com' + DEFAULT_HOST: str = "redis.googleapis.com" def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -97,31 +98,43 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host self._wrapped_methods: Dict[Callable, Callable] = {} @@ -193,14 +206,14 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -210,48 +223,51 @@ def operations_client(self): raise NotImplementedError() @property - def list_instances(self) -> Callable[ - [cloud_redis.ListInstancesRequest], - Union[ - cloud_redis.ListInstancesResponse, - Awaitable[cloud_redis.ListInstancesResponse] - ]]: + def list_instances( + self, + ) -> Callable[ + [cloud_redis.ListInstancesRequest], + Union[ + cloud_redis.ListInstancesResponse, + Awaitable[cloud_redis.ListInstancesResponse], + ], + ]: raise NotImplementedError() @property - def get_instance(self) -> Callable[ - [cloud_redis.GetInstanceRequest], - Union[ - cloud_redis.Instance, - Awaitable[cloud_redis.Instance] - ]]: + def get_instance( + self, + ) -> Callable[ + [cloud_redis.GetInstanceRequest], + Union[cloud_redis.Instance, Awaitable[cloud_redis.Instance]], + ]: raise NotImplementedError() @property - def create_instance(self) -> Callable[ - [cloud_redis.CreateInstanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_instance( + self, + ) -> Callable[ + [cloud_redis.CreateInstanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def update_instance(self) -> Callable[ - [cloud_redis.UpdateInstanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def update_instance( + self, + ) -> Callable[ + [cloud_redis.UpdateInstanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def delete_instance(self) -> Callable[ - [cloud_redis.DeleteInstanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def delete_instance( + self, + ) -> Callable[ + [cloud_redis.DeleteInstanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property @@ -259,7 +275,10 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], ]: raise NotImplementedError() @@ -275,19 +294,13 @@ def get_operation( @property def cancel_operation( self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: raise NotImplementedError() @property def delete_operation( self, - ) -> Callable[ - [operations_pb2.DeleteOperationRequest], - None, - ]: + ) -> Callable[[operations_pb2.DeleteOperationRequest], None,]: raise NotImplementedError() @property @@ -300,7 +313,8 @@ def wait_operation( raise NotImplementedError() @property - def get_location(self, + def get_location( + self, ) -> Callable[ [locations_pb2.GetLocationRequest], Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], @@ -308,10 +322,14 @@ def get_location(self, raise NotImplementedError() @property - def list_locations(self, + def list_locations( + self, ) -> Callable[ [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], ]: raise NotImplementedError() @@ -320,6 +338,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'CloudRedisTransport', -) +__all__ = ("CloudRedisTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/rest.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/rest.py index 4743b5d9405f..6130f65f556e 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/rest.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/rest.py @@ -27,7 +27,7 @@ from google.protobuf import json_format from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from requests import __version__ as requests_version import dataclasses @@ -49,6 +49,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -125,7 +126,14 @@ def post_update_instance(self, response): """ - def pre_create_instance(self, request: cloud_redis.CreateInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.CreateInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_create_instance( + self, + request: cloud_redis.CreateInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.CreateInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for create_instance Override in a subclass to manipulate the request or metadata @@ -133,7 +141,9 @@ def pre_create_instance(self, request: cloud_redis.CreateInstanceRequest, metada """ return request, metadata - def post_create_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_create_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for create_instance DEPRECATED. Please use the `post_create_instance_with_metadata` @@ -146,7 +156,11 @@ def post_create_instance(self, response: operations_pb2.Operation) -> operations """ return response - def post_create_instance_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_create_instance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for create_instance Override in a subclass to read or manipulate the response or metadata after it @@ -161,7 +175,13 @@ def post_create_instance_with_metadata(self, response: operations_pb2.Operation, """ return response, metadata - def pre_delete_instance(self, request: cloud_redis.DeleteInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.DeleteInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_delete_instance( + self, + request: cloud_redis.DeleteInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.DeleteInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for delete_instance Override in a subclass to manipulate the request or metadata @@ -169,7 +189,9 @@ def pre_delete_instance(self, request: cloud_redis.DeleteInstanceRequest, metada """ return request, metadata - def post_delete_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_delete_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for delete_instance DEPRECATED. Please use the `post_delete_instance_with_metadata` @@ -182,7 +204,11 @@ def post_delete_instance(self, response: operations_pb2.Operation) -> operations """ return response - def post_delete_instance_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_delete_instance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for delete_instance Override in a subclass to read or manipulate the response or metadata after it @@ -197,7 +223,11 @@ def post_delete_instance_with_metadata(self, response: operations_pb2.Operation, """ return response, metadata - def pre_get_instance(self, request: cloud_redis.GetInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.GetInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_get_instance( + self, + request: cloud_redis.GetInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[cloud_redis.GetInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_instance Override in a subclass to manipulate the request or metadata @@ -218,7 +248,11 @@ def post_get_instance(self, response: cloud_redis.Instance) -> cloud_redis.Insta """ return response - def post_get_instance_with_metadata(self, response: cloud_redis.Instance, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.Instance, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_instance_with_metadata( + self, + response: cloud_redis.Instance, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[cloud_redis.Instance, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_instance Override in a subclass to read or manipulate the response or metadata after it @@ -233,7 +267,13 @@ def post_get_instance_with_metadata(self, response: cloud_redis.Instance, metada """ return response, metadata - def pre_list_instances(self, request: cloud_redis.ListInstancesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.ListInstancesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_instances( + self, + request: cloud_redis.ListInstancesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.ListInstancesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_instances Override in a subclass to manipulate the request or metadata @@ -241,7 +281,9 @@ def pre_list_instances(self, request: cloud_redis.ListInstancesRequest, metadata """ return request, metadata - def post_list_instances(self, response: cloud_redis.ListInstancesResponse) -> cloud_redis.ListInstancesResponse: + def post_list_instances( + self, response: cloud_redis.ListInstancesResponse + ) -> cloud_redis.ListInstancesResponse: """Post-rpc interceptor for list_instances DEPRECATED. Please use the `post_list_instances_with_metadata` @@ -254,7 +296,13 @@ def post_list_instances(self, response: cloud_redis.ListInstancesResponse) -> cl """ return response - def post_list_instances_with_metadata(self, response: cloud_redis.ListInstancesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.ListInstancesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_instances_with_metadata( + self, + response: cloud_redis.ListInstancesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.ListInstancesResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for list_instances Override in a subclass to read or manipulate the response or metadata after it @@ -269,7 +317,13 @@ def post_list_instances_with_metadata(self, response: cloud_redis.ListInstancesR """ return response, metadata - def pre_update_instance(self, request: cloud_redis.UpdateInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.UpdateInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_update_instance( + self, + request: cloud_redis.UpdateInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.UpdateInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for update_instance Override in a subclass to manipulate the request or metadata @@ -277,7 +331,9 @@ def pre_update_instance(self, request: cloud_redis.UpdateInstanceRequest, metada """ return request, metadata - def post_update_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_update_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for update_instance DEPRECATED. Please use the `post_update_instance_with_metadata` @@ -290,7 +346,11 @@ def post_update_instance(self, response: operations_pb2.Operation) -> operations """ return response - def post_update_instance_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_update_instance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for update_instance Override in a subclass to read or manipulate the response or metadata after it @@ -306,8 +366,12 @@ def post_update_instance_with_metadata(self, response: operations_pb2.Operation, return response, metadata def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_location Override in a subclass to manipulate the request or metadata @@ -327,8 +391,12 @@ def post_get_location( return response def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_locations Override in a subclass to manipulate the request or metadata @@ -348,8 +416,12 @@ def post_list_locations( return response def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for cancel_operation Override in a subclass to manipulate the request or metadata @@ -357,9 +429,7 @@ def pre_cancel_operation( """ return request, metadata - def post_cancel_operation( - self, response: None - ) -> None: + def post_cancel_operation(self, response: None) -> None: """Post-rpc interceptor for cancel_operation Override in a subclass to manipulate the response @@ -369,8 +439,12 @@ def post_cancel_operation( return response def pre_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for delete_operation Override in a subclass to manipulate the request or metadata @@ -378,9 +452,7 @@ def pre_delete_operation( """ return request, metadata - def post_delete_operation( - self, response: None - ) -> None: + def post_delete_operation(self, response: None) -> None: """Post-rpc interceptor for delete_operation Override in a subclass to manipulate the response @@ -390,8 +462,12 @@ def post_delete_operation( return response def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_operation Override in a subclass to manipulate the request or metadata @@ -411,8 +487,12 @@ def post_get_operation( return response def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_operations Override in a subclass to manipulate the request or metadata @@ -432,8 +512,12 @@ def post_list_operations( return response def pre_wait_operation( - self, request: operations_pb2.WaitOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.WaitOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.WaitOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.WaitOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for wait_operation Override in a subclass to manipulate the request or metadata @@ -492,62 +576,63 @@ class CloudRedisRestTransport(_BaseCloudRedisRestTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__(self, *, - host: str = 'redis.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[CloudRedisRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: + def __init__( + self, + *, + host: str = "redis.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[CloudRedisRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. - NOTE: This REST transport functionality is currently in a beta - state (preview). We welcome your feedback via a GitHub issue in - this library's repository. Thank you! - - Args: - host (Optional[str]): - The hostname to connect to (default: 'redis.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. This argument will be - removed in the next major version of this library. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - interceptor (Optional[CloudRedisRestInterceptor]): Interceptor used - to manipulate requests, request metadata, and responses. - api_audience (Optional[str]): The intended audience for the API calls - to the service that will be set when using certain 3rd party - authentication flows. Audience is typically a resource identifier. - If not set, the host value will be used as a default. + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to (default: 'redis.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[CloudRedisRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. """ # Run the base constructor # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. @@ -559,10 +644,11 @@ def __init__(self, *, client_info=client_info, always_use_jwt_access=always_use_jwt_access, url_scheme=url_scheme, - api_audience=api_audience + api_audience=api_audience, ) self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) + self._credentials, default_host=self.DEFAULT_HOST + ) self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None if client_cert_source_for_mtls: self._session.configure_mtls_channel(client_cert_source_for_mtls) @@ -579,53 +665,58 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Only create a new client if we do not already have one. if self._operations_client is None: http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ + "google.longrunning.Operations.CancelOperation": [ { - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", }, ], - 'google.longrunning.Operations.DeleteOperation': [ + "google.longrunning.Operations.DeleteOperation": [ { - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", }, ], - 'google.longrunning.Operations.GetOperation': [ + "google.longrunning.Operations.GetOperation": [ { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", }, ], - 'google.longrunning.Operations.ListOperations': [ + "google.longrunning.Operations.ListOperations": [ { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", }, ], - 'google.longrunning.Operations.WaitOperation': [ + "google.longrunning.Operations.WaitOperation": [ { - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}:wait', - 'body': '*', + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/operations/*}:wait", + "body": "*", }, ], } rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) # Return the client from cache. return self._operations_client - class _CreateInstance(_BaseCloudRedisRestTransport._BaseCreateInstance, CloudRedisRestStub): + class _CreateInstance( + _BaseCloudRedisRestTransport._BaseCreateInstance, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.CreateInstance") @@ -637,27 +728,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: cloud_redis.CreateInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: cloud_redis.CreateInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the create instance method over HTTP. Args: @@ -680,32 +773,48 @@ def __call__(self, """ - http_options = _BaseCloudRedisRestTransport._BaseCreateInstance._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseCreateInstance._get_http_options() + ) request, metadata = self._interceptor.pre_create_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseCreateInstance._get_transcoded_request(http_options, request) + transcoded_request = _BaseCloudRedisRestTransport._BaseCreateInstance._get_transcoded_request( + http_options, request + ) - body = _BaseCloudRedisRestTransport._BaseCreateInstance._get_request_body_json(transcoded_request) + body = ( + _BaseCloudRedisRestTransport._BaseCreateInstance._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseCreateInstance._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseCreateInstance._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.CreateInstance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "CreateInstance", "httpRequest": http_request, @@ -714,7 +823,15 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._CreateInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = CloudRedisRestTransport._CreateInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -727,20 +844,24 @@ def __call__(self, resp = self._interceptor.post_create_instance(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_instance_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_create_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisClient.create_instance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "CreateInstance", "metadata": http_response["headers"], @@ -749,7 +870,9 @@ def __call__(self, ) return resp - class _DeleteInstance(_BaseCloudRedisRestTransport._BaseDeleteInstance, CloudRedisRestStub): + class _DeleteInstance( + _BaseCloudRedisRestTransport._BaseDeleteInstance, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.DeleteInstance") @@ -761,26 +884,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: cloud_redis.DeleteInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: cloud_redis.DeleteInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the delete instance method over HTTP. Args: @@ -803,30 +928,42 @@ def __call__(self, """ - http_options = _BaseCloudRedisRestTransport._BaseDeleteInstance._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseDeleteInstance._get_http_options() + ) request, metadata = self._interceptor.pre_delete_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseDeleteInstance._get_transcoded_request(http_options, request) + transcoded_request = _BaseCloudRedisRestTransport._BaseDeleteInstance._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseDeleteInstance._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseDeleteInstance._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.DeleteInstance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "DeleteInstance", "httpRequest": http_request, @@ -835,7 +972,14 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._DeleteInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = CloudRedisRestTransport._DeleteInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -848,20 +992,24 @@ def __call__(self, resp = self._interceptor.post_delete_instance(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_instance_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_delete_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisClient.delete_instance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "DeleteInstance", "metadata": http_response["headers"], @@ -870,7 +1018,9 @@ def __call__(self, ) return resp - class _GetInstance(_BaseCloudRedisRestTransport._BaseGetInstance, CloudRedisRestStub): + class _GetInstance( + _BaseCloudRedisRestTransport._BaseGetInstance, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.GetInstance") @@ -882,26 +1032,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: cloud_redis.GetInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> cloud_redis.Instance: + def __call__( + self, + request: cloud_redis.GetInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_redis.Instance: r"""Call the get instance method over HTTP. Args: @@ -921,30 +1073,44 @@ def __call__(self, A Memorystore for Redis instance. """ - http_options = _BaseCloudRedisRestTransport._BaseGetInstance._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseGetInstance._get_http_options() + ) request, metadata = self._interceptor.pre_get_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseGetInstance._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseGetInstance._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseGetInstance._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseGetInstance._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.GetInstance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "GetInstance", "httpRequest": http_request, @@ -953,7 +1119,14 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._GetInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = CloudRedisRestTransport._GetInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -968,20 +1141,24 @@ def __call__(self, resp = self._interceptor.post_get_instance(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_instance_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = cloud_redis.Instance.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisClient.get_instance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "GetInstance", "metadata": http_response["headers"], @@ -990,7 +1167,9 @@ def __call__(self, ) return resp - class _ListInstances(_BaseCloudRedisRestTransport._BaseListInstances, CloudRedisRestStub): + class _ListInstances( + _BaseCloudRedisRestTransport._BaseListInstances, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.ListInstances") @@ -1002,26 +1181,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: cloud_redis.ListInstancesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> cloud_redis.ListInstancesResponse: + def __call__( + self, + request: cloud_redis.ListInstancesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_redis.ListInstancesResponse: r"""Call the list instances method over HTTP. Args: @@ -1043,30 +1224,44 @@ def __call__(self, """ - http_options = _BaseCloudRedisRestTransport._BaseListInstances._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseListInstances._get_http_options() + ) request, metadata = self._interceptor.pre_list_instances(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseListInstances._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseListInstances._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseListInstances._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseListInstances._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.ListInstances", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ListInstances", "httpRequest": http_request, @@ -1075,7 +1270,14 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._ListInstances._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = CloudRedisRestTransport._ListInstances._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1090,20 +1292,26 @@ def __call__(self, resp = self._interceptor.post_list_instances(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_instances_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_instances_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = cloud_redis.ListInstancesResponse.to_json(response) + response_payload = cloud_redis.ListInstancesResponse.to_json( + response + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisClient.list_instances", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ListInstances", "metadata": http_response["headers"], @@ -1112,7 +1320,9 @@ def __call__(self, ) return resp - class _UpdateInstance(_BaseCloudRedisRestTransport._BaseUpdateInstance, CloudRedisRestStub): + class _UpdateInstance( + _BaseCloudRedisRestTransport._BaseUpdateInstance, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.UpdateInstance") @@ -1124,27 +1334,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: cloud_redis.UpdateInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: cloud_redis.UpdateInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the update instance method over HTTP. Args: @@ -1167,32 +1379,48 @@ def __call__(self, """ - http_options = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseUpdateInstance._get_http_options() + ) request, metadata = self._interceptor.pre_update_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_transcoded_request(http_options, request) + transcoded_request = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_transcoded_request( + http_options, request + ) - body = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_request_body_json(transcoded_request) + body = ( + _BaseCloudRedisRestTransport._BaseUpdateInstance._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseUpdateInstance._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.UpdateInstance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "UpdateInstance", "httpRequest": http_request, @@ -1201,7 +1429,15 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._UpdateInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = CloudRedisRestTransport._UpdateInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1214,20 +1450,24 @@ def __call__(self, resp = self._interceptor.post_update_instance(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_instance_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_update_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisClient.update_instance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "UpdateInstance", "metadata": http_response["headers"], @@ -1237,50 +1477,54 @@ def __call__(self, return resp @property - def create_instance(self) -> Callable[ - [cloud_redis.CreateInstanceRequest], - operations_pb2.Operation]: + def create_instance( + self, + ) -> Callable[[cloud_redis.CreateInstanceRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._CreateInstance(self._session, self._host, self._interceptor) # type: ignore + return self._CreateInstance(self._session, self._host, self._interceptor) # type: ignore @property - def delete_instance(self) -> Callable[ - [cloud_redis.DeleteInstanceRequest], - operations_pb2.Operation]: + def delete_instance( + self, + ) -> Callable[[cloud_redis.DeleteInstanceRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._DeleteInstance(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteInstance(self._session, self._host, self._interceptor) # type: ignore @property - def get_instance(self) -> Callable[ - [cloud_redis.GetInstanceRequest], - cloud_redis.Instance]: + def get_instance( + self, + ) -> Callable[[cloud_redis.GetInstanceRequest], cloud_redis.Instance]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._GetInstance(self._session, self._host, self._interceptor) # type: ignore + return self._GetInstance(self._session, self._host, self._interceptor) # type: ignore @property - def list_instances(self) -> Callable[ - [cloud_redis.ListInstancesRequest], - cloud_redis.ListInstancesResponse]: + def list_instances( + self, + ) -> Callable[ + [cloud_redis.ListInstancesRequest], cloud_redis.ListInstancesResponse + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._ListInstances(self._session, self._host, self._interceptor) # type: ignore + return self._ListInstances(self._session, self._host, self._interceptor) # type: ignore @property - def update_instance(self) -> Callable[ - [cloud_redis.UpdateInstanceRequest], - operations_pb2.Operation]: + def update_instance( + self, + ) -> Callable[[cloud_redis.UpdateInstanceRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._UpdateInstance(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateInstance(self._session, self._host, self._interceptor) # type: ignore @property def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - class _GetLocation(_BaseCloudRedisRestTransport._BaseGetLocation, CloudRedisRestStub): + class _GetLocation( + _BaseCloudRedisRestTransport._BaseGetLocation, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.GetLocation") @@ -1292,27 +1536,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> locations_pb2.Location: - + def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: r"""Call the get location method over HTTP. Args: @@ -1330,30 +1575,44 @@ def __call__(self, locations_pb2.Location: Response from GetLocation method. """ - http_options = _BaseCloudRedisRestTransport._BaseGetLocation._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseGetLocation._get_http_options() + ) request, metadata = self._interceptor.pre_get_location(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseGetLocation._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.GetLocation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "GetLocation", "httpRequest": http_request, @@ -1362,7 +1621,14 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = CloudRedisRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1373,19 +1639,21 @@ def __call__(self, resp = locations_pb2.Location() resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_location(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.GetLocation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "GetLocation", "httpResponse": http_response, @@ -1396,9 +1664,11 @@ def __call__(self, @property def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - class _ListLocations(_BaseCloudRedisRestTransport._BaseListLocations, CloudRedisRestStub): + class _ListLocations( + _BaseCloudRedisRestTransport._BaseListLocations, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.ListLocations") @@ -1410,27 +1680,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> locations_pb2.ListLocationsResponse: - + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: r"""Call the list locations method over HTTP. Args: @@ -1448,30 +1719,44 @@ def __call__(self, locations_pb2.ListLocationsResponse: Response from ListLocations method. """ - http_options = _BaseCloudRedisRestTransport._BaseListLocations._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseListLocations._get_http_options() + ) request, metadata = self._interceptor.pre_list_locations(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseListLocations._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseListLocations._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseListLocations._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.ListLocations", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ListLocations", "httpRequest": http_request, @@ -1480,7 +1765,14 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = CloudRedisRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1491,19 +1783,21 @@ def __call__(self, resp = locations_pb2.ListLocationsResponse() resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_locations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.ListLocations", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ListLocations", "httpResponse": http_response, @@ -1514,9 +1808,11 @@ def __call__(self, @property def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - class _CancelOperation(_BaseCloudRedisRestTransport._BaseCancelOperation, CloudRedisRestStub): + class _CancelOperation( + _BaseCloudRedisRestTransport._BaseCancelOperation, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.CancelOperation") @@ -1528,27 +1824,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> None: - + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Call the cancel operation method over HTTP. Args: @@ -1563,30 +1860,42 @@ def __call__(self, be of type `bytes`. """ - http_options = _BaseCloudRedisRestTransport._BaseCancelOperation._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseCancelOperation._get_http_options() + ) - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = _BaseCloudRedisRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseCloudRedisRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.CancelOperation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "CancelOperation", "httpRequest": http_request, @@ -1595,7 +1904,14 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._CancelOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = CloudRedisRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1606,9 +1922,11 @@ def __call__(self, @property def delete_operation(self): - return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - class _DeleteOperation(_BaseCloudRedisRestTransport._BaseDeleteOperation, CloudRedisRestStub): + class _DeleteOperation( + _BaseCloudRedisRestTransport._BaseDeleteOperation, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.DeleteOperation") @@ -1620,27 +1938,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: operations_pb2.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> None: - + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Call the delete operation method over HTTP. Args: @@ -1655,30 +1974,42 @@ def __call__(self, be of type `bytes`. """ - http_options = _BaseCloudRedisRestTransport._BaseDeleteOperation._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseDeleteOperation._get_http_options() + ) - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + transcoded_request = _BaseCloudRedisRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseCloudRedisRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.DeleteOperation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "DeleteOperation", "httpRequest": http_request, @@ -1687,7 +2018,14 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._DeleteOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = CloudRedisRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1698,9 +2036,11 @@ def __call__(self, @property def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(_BaseCloudRedisRestTransport._BaseGetOperation, CloudRedisRestStub): + class _GetOperation( + _BaseCloudRedisRestTransport._BaseGetOperation, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.GetOperation") @@ -1712,27 +2052,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the get operation method over HTTP. Args: @@ -1750,30 +2091,44 @@ def __call__(self, operations_pb2.Operation: Response from GetOperation method. """ - http_options = _BaseCloudRedisRestTransport._BaseGetOperation._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.GetOperation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "GetOperation", "httpRequest": http_request, @@ -1782,7 +2137,14 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = CloudRedisRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1793,19 +2155,21 @@ def __call__(self, resp = operations_pb2.Operation() resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.GetOperation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "GetOperation", "httpResponse": http_response, @@ -1816,9 +2180,11 @@ def __call__(self, @property def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(_BaseCloudRedisRestTransport._BaseListOperations, CloudRedisRestStub): + class _ListOperations( + _BaseCloudRedisRestTransport._BaseListOperations, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.ListOperations") @@ -1830,27 +2196,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.ListOperationsResponse: - + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: r"""Call the list operations method over HTTP. Args: @@ -1868,30 +2235,42 @@ def __call__(self, operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options = _BaseCloudRedisRestTransport._BaseListOperations._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseListOperations._get_transcoded_request(http_options, request) + transcoded_request = _BaseCloudRedisRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseListOperations._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.ListOperations", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ListOperations", "httpRequest": http_request, @@ -1900,7 +2279,14 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = CloudRedisRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1911,19 +2297,21 @@ def __call__(self, resp = operations_pb2.ListOperationsResponse() resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.ListOperations", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ListOperations", "httpResponse": http_response, @@ -1934,9 +2322,11 @@ def __call__(self, @property def wait_operation(self): - return self._WaitOperation(self._session, self._host, self._interceptor) # type: ignore + return self._WaitOperation(self._session, self._host, self._interceptor) # type: ignore - class _WaitOperation(_BaseCloudRedisRestTransport._BaseWaitOperation, CloudRedisRestStub): + class _WaitOperation( + _BaseCloudRedisRestTransport._BaseWaitOperation, CloudRedisRestStub + ): def __hash__(self): return hash("CloudRedisRestTransport.WaitOperation") @@ -1948,28 +2338,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: operations_pb2.WaitOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - + def __call__( + self, + request: operations_pb2.WaitOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the wait operation method over HTTP. Args: @@ -1987,32 +2378,50 @@ def __call__(self, operations_pb2.Operation: Response from WaitOperation method. """ - http_options = _BaseCloudRedisRestTransport._BaseWaitOperation._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseWaitOperation._get_http_options() + ) request, metadata = self._interceptor.pre_wait_operation(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseWaitOperation._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseWaitOperation._get_transcoded_request( + http_options, request + ) + ) - body = _BaseCloudRedisRestTransport._BaseWaitOperation._get_request_body_json(transcoded_request) + body = ( + _BaseCloudRedisRestTransport._BaseWaitOperation._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseWaitOperation._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseWaitOperation._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.WaitOperation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "WaitOperation", "httpRequest": http_request, @@ -2021,7 +2430,15 @@ def __call__(self, ) # Send the request - response = CloudRedisRestTransport._WaitOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = CloudRedisRestTransport._WaitOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2032,19 +2449,21 @@ def __call__(self, resp = operations_pb2.Operation() resp = json_format.Parse(content, resp) resp = self._interceptor.post_wait_operation(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.WaitOperation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "WaitOperation", "httpResponse": http_response, @@ -2061,6 +2480,4 @@ def close(self): self._session.close() -__all__=( - 'CloudRedisRestTransport', -) +__all__ = ("CloudRedisRestTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/rest_asyncio.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/rest_asyncio.py index 6561868e208d..954e54c81b4d 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/rest_asyncio.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/rest_asyncio.py @@ -15,20 +15,23 @@ # import google.auth + try: - import aiohttp # type: ignore - from google.auth.aio.transport.sessions import AsyncAuthorizedSession # type: ignore - from google.api_core import rest_streaming_async # type: ignore - from google.api_core.operations_v1 import AsyncOperationsRestClient # type: ignore + import aiohttp # type: ignore + from google.auth.aio.transport.sessions import AsyncAuthorizedSession # type: ignore + from google.api_core import rest_streaming_async # type: ignore + from google.api_core.operations_v1 import AsyncOperationsRestClient # type: ignore except ImportError as e: # pragma: NO COVER - raise ImportError("`rest_asyncio` transport requires the library to be installed with the `async_rest` extra. Install the library with the `async_rest` extra using `pip install google-cloud-redis[async_rest]`") from e + raise ImportError( + "`rest_asyncio` transport requires the library to be installed with the `async_rest` extra. Install the library with the `async_rest` extra using `pip install google-cloud-redis[async_rest]`" + ) from e from google.auth.aio import credentials as ga_credentials_async # type: ignore from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.api_core import retry_async as retries from google.api_core import rest_helpers from google.api_core import rest_streaming_async # type: ignore @@ -36,7 +39,7 @@ from google.protobuf import json_format from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore import json # type: ignore import dataclasses @@ -56,6 +59,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -137,7 +141,14 @@ async def post_update_instance(self, response): """ - async def pre_create_instance(self, request: cloud_redis.CreateInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.CreateInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + async def pre_create_instance( + self, + request: cloud_redis.CreateInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.CreateInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for create_instance Override in a subclass to manipulate the request or metadata @@ -145,7 +156,9 @@ async def pre_create_instance(self, request: cloud_redis.CreateInstanceRequest, """ return request, metadata - async def post_create_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + async def post_create_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for create_instance DEPRECATED. Please use the `post_create_instance_with_metadata` @@ -158,7 +171,11 @@ async def post_create_instance(self, response: operations_pb2.Operation) -> oper """ return response - async def post_create_instance_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + async def post_create_instance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for create_instance Override in a subclass to read or manipulate the response or metadata after it @@ -173,7 +190,13 @@ async def post_create_instance_with_metadata(self, response: operations_pb2.Oper """ return response, metadata - async def pre_delete_instance(self, request: cloud_redis.DeleteInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.DeleteInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + async def pre_delete_instance( + self, + request: cloud_redis.DeleteInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.DeleteInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for delete_instance Override in a subclass to manipulate the request or metadata @@ -181,7 +204,9 @@ async def pre_delete_instance(self, request: cloud_redis.DeleteInstanceRequest, """ return request, metadata - async def post_delete_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + async def post_delete_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for delete_instance DEPRECATED. Please use the `post_delete_instance_with_metadata` @@ -194,7 +219,11 @@ async def post_delete_instance(self, response: operations_pb2.Operation) -> oper """ return response - async def post_delete_instance_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + async def post_delete_instance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for delete_instance Override in a subclass to read or manipulate the response or metadata after it @@ -209,7 +238,11 @@ async def post_delete_instance_with_metadata(self, response: operations_pb2.Oper """ return response, metadata - async def pre_get_instance(self, request: cloud_redis.GetInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.GetInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + async def pre_get_instance( + self, + request: cloud_redis.GetInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[cloud_redis.GetInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_instance Override in a subclass to manipulate the request or metadata @@ -217,7 +250,9 @@ async def pre_get_instance(self, request: cloud_redis.GetInstanceRequest, metada """ return request, metadata - async def post_get_instance(self, response: cloud_redis.Instance) -> cloud_redis.Instance: + async def post_get_instance( + self, response: cloud_redis.Instance + ) -> cloud_redis.Instance: """Post-rpc interceptor for get_instance DEPRECATED. Please use the `post_get_instance_with_metadata` @@ -230,7 +265,11 @@ async def post_get_instance(self, response: cloud_redis.Instance) -> cloud_redis """ return response - async def post_get_instance_with_metadata(self, response: cloud_redis.Instance, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.Instance, Sequence[Tuple[str, Union[str, bytes]]]]: + async def post_get_instance_with_metadata( + self, + response: cloud_redis.Instance, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[cloud_redis.Instance, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_instance Override in a subclass to read or manipulate the response or metadata after it @@ -245,7 +284,13 @@ async def post_get_instance_with_metadata(self, response: cloud_redis.Instance, """ return response, metadata - async def pre_list_instances(self, request: cloud_redis.ListInstancesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.ListInstancesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + async def pre_list_instances( + self, + request: cloud_redis.ListInstancesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.ListInstancesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_instances Override in a subclass to manipulate the request or metadata @@ -253,7 +298,9 @@ async def pre_list_instances(self, request: cloud_redis.ListInstancesRequest, me """ return request, metadata - async def post_list_instances(self, response: cloud_redis.ListInstancesResponse) -> cloud_redis.ListInstancesResponse: + async def post_list_instances( + self, response: cloud_redis.ListInstancesResponse + ) -> cloud_redis.ListInstancesResponse: """Post-rpc interceptor for list_instances DEPRECATED. Please use the `post_list_instances_with_metadata` @@ -266,7 +313,13 @@ async def post_list_instances(self, response: cloud_redis.ListInstancesResponse) """ return response - async def post_list_instances_with_metadata(self, response: cloud_redis.ListInstancesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.ListInstancesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + async def post_list_instances_with_metadata( + self, + response: cloud_redis.ListInstancesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.ListInstancesResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for list_instances Override in a subclass to read or manipulate the response or metadata after it @@ -281,7 +334,13 @@ async def post_list_instances_with_metadata(self, response: cloud_redis.ListInst """ return response, metadata - async def pre_update_instance(self, request: cloud_redis.UpdateInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[cloud_redis.UpdateInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + async def pre_update_instance( + self, + request: cloud_redis.UpdateInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cloud_redis.UpdateInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for update_instance Override in a subclass to manipulate the request or metadata @@ -289,7 +348,9 @@ async def pre_update_instance(self, request: cloud_redis.UpdateInstanceRequest, """ return request, metadata - async def post_update_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + async def post_update_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for update_instance DEPRECATED. Please use the `post_update_instance_with_metadata` @@ -302,7 +363,11 @@ async def post_update_instance(self, response: operations_pb2.Operation) -> oper """ return response - async def post_update_instance_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + async def post_update_instance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for update_instance Override in a subclass to read or manipulate the response or metadata after it @@ -318,8 +383,12 @@ async def post_update_instance_with_metadata(self, response: operations_pb2.Oper return response, metadata async def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_location Override in a subclass to manipulate the request or metadata @@ -339,8 +408,12 @@ async def post_get_location( return response async def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_locations Override in a subclass to manipulate the request or metadata @@ -360,8 +433,12 @@ async def post_list_locations( return response async def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for cancel_operation Override in a subclass to manipulate the request or metadata @@ -369,9 +446,7 @@ async def pre_cancel_operation( """ return request, metadata - async def post_cancel_operation( - self, response: None - ) -> None: + async def post_cancel_operation(self, response: None) -> None: """Post-rpc interceptor for cancel_operation Override in a subclass to manipulate the response @@ -381,8 +456,12 @@ async def post_cancel_operation( return response async def pre_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for delete_operation Override in a subclass to manipulate the request or metadata @@ -390,9 +469,7 @@ async def pre_delete_operation( """ return request, metadata - async def post_delete_operation( - self, response: None - ) -> None: + async def post_delete_operation(self, response: None) -> None: """Post-rpc interceptor for delete_operation Override in a subclass to manipulate the response @@ -402,8 +479,12 @@ async def post_delete_operation( return response async def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_operation Override in a subclass to manipulate the request or metadata @@ -423,8 +504,12 @@ async def post_get_operation( return response async def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_operations Override in a subclass to manipulate the request or metadata @@ -444,8 +529,12 @@ async def post_list_operations( return response async def pre_wait_operation( - self, request: operations_pb2.WaitOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.WaitOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.WaitOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.WaitOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for wait_operation Override in a subclass to manipulate the request or metadata @@ -471,6 +560,7 @@ class AsyncCloudRedisRestStub: _host: str _interceptor: AsyncCloudRedisRestInterceptor + class AsyncCloudRedisRestTransport(_BaseCloudRedisRestTransport): """Asynchronous REST backend transport for CloudRedis. @@ -502,38 +592,40 @@ class AsyncCloudRedisRestTransport(_BaseCloudRedisRestTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__(self, - *, - host: str = 'redis.googleapis.com', - credentials: Optional[ga_credentials_async.Credentials] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - url_scheme: str = 'https', - interceptor: Optional[AsyncCloudRedisRestInterceptor] = None, - ) -> None: + + def __init__( + self, + *, + host: str = "redis.googleapis.com", + credentials: Optional[ga_credentials_async.Credentials] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + url_scheme: str = "https", + interceptor: Optional[AsyncCloudRedisRestInterceptor] = None, + ) -> None: """Instantiate the transport. - NOTE: This async REST transport functionality is currently in a beta - state (preview). We welcome your feedback via a GitHub issue in - this library's repository. Thank you! - - Args: - host (Optional[str]): - The hostname to connect to (default: 'redis.googleapis.com'). - credentials (Optional[google.auth.aio.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - url_scheme (str): the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - interceptor (Optional[AsyncCloudRedisRestInterceptor]): Interceptor used - to manipulate requests, request metadata, and responses. + NOTE: This async REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to (default: 'redis.googleapis.com'). + credentials (Optional[google.auth.aio.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + url_scheme (str): the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[AsyncCloudRedisRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. """ # Run the base constructor super().__init__( @@ -542,16 +634,18 @@ def __init__(self, client_info=client_info, always_use_jwt_access=False, url_scheme=url_scheme, - api_audience=None + api_audience=None, ) self._session = AsyncAuthorizedSession(self._credentials) # type: ignore self._interceptor = interceptor or AsyncCloudRedisRestInterceptor() self._wrap_with_kind = True self._prep_wrapped_messages(client_info) - self._operations_client: Optional[operations_v1.AsyncOperationsRestClient] = None + self._operations_client: Optional[ + operations_v1.AsyncOperationsRestClient + ] = None def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { self.list_instances: self._wrap_method( self.list_instances, @@ -620,7 +714,9 @@ def _wrap_method(self, func, *args, **kwargs): kwargs["kind"] = self.kind return gapic_v1.method_async.wrap_method(func, *args, **kwargs) - class _CreateInstance(_BaseCloudRedisRestTransport._BaseCreateInstance, AsyncCloudRedisRestStub): + class _CreateInstance( + _BaseCloudRedisRestTransport._BaseCreateInstance, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.CreateInstance") @@ -632,27 +728,29 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - async def __call__(self, - request: cloud_redis.CreateInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + async def __call__( + self, + request: cloud_redis.CreateInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the create instance method over HTTP. Args: @@ -675,32 +773,50 @@ async def __call__(self, """ - http_options = _BaseCloudRedisRestTransport._BaseCreateInstance._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseCreateInstance._get_http_options() + ) - request, metadata = await self._interceptor.pre_create_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseCreateInstance._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_create_instance( + request, metadata + ) + transcoded_request = _BaseCloudRedisRestTransport._BaseCreateInstance._get_transcoded_request( + http_options, request + ) - body = _BaseCloudRedisRestTransport._BaseCreateInstance._get_request_body_json(transcoded_request) + body = ( + _BaseCloudRedisRestTransport._BaseCreateInstance._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseCreateInstance._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseCreateInstance._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.CreateInstance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "CreateInstance", "httpRequest": http_request, @@ -709,15 +825,25 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._CreateInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = await AsyncCloudRedisRestTransport._CreateInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore # Return the response @@ -727,20 +853,24 @@ async def __call__(self, json_format.Parse(content, pb_resp, ignore_unknown_fields=True) resp = await self._interceptor.post_create_instance(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = await self._interceptor.post_create_instance_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = await self._interceptor.post_create_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), - "status": "OK", # need to obtain this properly + "headers": dict(response.headers), + "status": "OK", # need to obtain this properly } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.create_instance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "CreateInstance", "metadata": http_response["headers"], @@ -750,7 +880,9 @@ async def __call__(self, return resp - class _DeleteInstance(_BaseCloudRedisRestTransport._BaseDeleteInstance, AsyncCloudRedisRestStub): + class _DeleteInstance( + _BaseCloudRedisRestTransport._BaseDeleteInstance, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.DeleteInstance") @@ -762,26 +894,28 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - async def __call__(self, - request: cloud_redis.DeleteInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + async def __call__( + self, + request: cloud_redis.DeleteInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the delete instance method over HTTP. Args: @@ -804,30 +938,44 @@ async def __call__(self, """ - http_options = _BaseCloudRedisRestTransport._BaseDeleteInstance._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseDeleteInstance._get_http_options() + ) - request, metadata = await self._interceptor.pre_delete_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseDeleteInstance._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_delete_instance( + request, metadata + ) + transcoded_request = _BaseCloudRedisRestTransport._BaseDeleteInstance._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseDeleteInstance._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseDeleteInstance._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.DeleteInstance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "DeleteInstance", "httpRequest": http_request, @@ -836,15 +984,24 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._DeleteInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = await AsyncCloudRedisRestTransport._DeleteInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore # Return the response @@ -854,20 +1011,24 @@ async def __call__(self, json_format.Parse(content, pb_resp, ignore_unknown_fields=True) resp = await self._interceptor.post_delete_instance(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = await self._interceptor.post_delete_instance_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = await self._interceptor.post_delete_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), - "status": "OK", # need to obtain this properly + "headers": dict(response.headers), + "status": "OK", # need to obtain this properly } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.delete_instance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "DeleteInstance", "metadata": http_response["headers"], @@ -877,7 +1038,9 @@ async def __call__(self, return resp - class _GetInstance(_BaseCloudRedisRestTransport._BaseGetInstance, AsyncCloudRedisRestStub): + class _GetInstance( + _BaseCloudRedisRestTransport._BaseGetInstance, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.GetInstance") @@ -889,26 +1052,28 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - async def __call__(self, - request: cloud_redis.GetInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> cloud_redis.Instance: + async def __call__( + self, + request: cloud_redis.GetInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_redis.Instance: r"""Call the get instance method over HTTP. Args: @@ -928,30 +1093,46 @@ async def __call__(self, A Memorystore for Redis instance. """ - http_options = _BaseCloudRedisRestTransport._BaseGetInstance._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseGetInstance._get_http_options() + ) - request, metadata = await self._interceptor.pre_get_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseGetInstance._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_get_instance( + request, metadata + ) + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseGetInstance._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseGetInstance._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseGetInstance._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.GetInstance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "GetInstance", "httpRequest": http_request, @@ -960,15 +1141,24 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._GetInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = await AsyncCloudRedisRestTransport._GetInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore # Return the response @@ -978,20 +1168,24 @@ async def __call__(self, json_format.Parse(content, pb_resp, ignore_unknown_fields=True) resp = await self._interceptor.post_get_instance(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = await self._interceptor.post_get_instance_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = await self._interceptor.post_get_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = cloud_redis.Instance.to_json(response) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), - "status": "OK", # need to obtain this properly + "headers": dict(response.headers), + "status": "OK", # need to obtain this properly } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.get_instance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "GetInstance", "metadata": http_response["headers"], @@ -1001,7 +1195,9 @@ async def __call__(self, return resp - class _ListInstances(_BaseCloudRedisRestTransport._BaseListInstances, AsyncCloudRedisRestStub): + class _ListInstances( + _BaseCloudRedisRestTransport._BaseListInstances, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.ListInstances") @@ -1013,26 +1209,28 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - async def __call__(self, - request: cloud_redis.ListInstancesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> cloud_redis.ListInstancesResponse: + async def __call__( + self, + request: cloud_redis.ListInstancesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cloud_redis.ListInstancesResponse: r"""Call the list instances method over HTTP. Args: @@ -1054,30 +1252,46 @@ async def __call__(self, """ - http_options = _BaseCloudRedisRestTransport._BaseListInstances._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseListInstances._get_http_options() + ) - request, metadata = await self._interceptor.pre_list_instances(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseListInstances._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_list_instances( + request, metadata + ) + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseListInstances._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseListInstances._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseListInstances._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.ListInstances", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ListInstances", "httpRequest": http_request, @@ -1086,15 +1300,24 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._ListInstances._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = await AsyncCloudRedisRestTransport._ListInstances._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore # Return the response @@ -1104,20 +1327,26 @@ async def __call__(self, json_format.Parse(content, pb_resp, ignore_unknown_fields=True) resp = await self._interceptor.post_list_instances(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = await self._interceptor.post_list_instances_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = await self._interceptor.post_list_instances_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = cloud_redis.ListInstancesResponse.to_json(response) + response_payload = cloud_redis.ListInstancesResponse.to_json( + response + ) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), - "status": "OK", # need to obtain this properly + "headers": dict(response.headers), + "status": "OK", # need to obtain this properly } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.list_instances", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ListInstances", "metadata": http_response["headers"], @@ -1127,7 +1356,9 @@ async def __call__(self, return resp - class _UpdateInstance(_BaseCloudRedisRestTransport._BaseUpdateInstance, AsyncCloudRedisRestStub): + class _UpdateInstance( + _BaseCloudRedisRestTransport._BaseUpdateInstance, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.UpdateInstance") @@ -1139,27 +1370,29 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - async def __call__(self, - request: cloud_redis.UpdateInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + async def __call__( + self, + request: cloud_redis.UpdateInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the update instance method over HTTP. Args: @@ -1182,32 +1415,50 @@ async def __call__(self, """ - http_options = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseUpdateInstance._get_http_options() + ) - request, metadata = await self._interceptor.pre_update_instance(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_update_instance( + request, metadata + ) + transcoded_request = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_transcoded_request( + http_options, request + ) - body = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_request_body_json(transcoded_request) + body = ( + _BaseCloudRedisRestTransport._BaseUpdateInstance._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseUpdateInstance._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.UpdateInstance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "UpdateInstance", "httpRequest": http_request, @@ -1216,15 +1467,25 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._UpdateInstance._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = await AsyncCloudRedisRestTransport._UpdateInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore # Return the response @@ -1234,20 +1495,24 @@ async def __call__(self, json_format.Parse(content, pb_resp, ignore_unknown_fields=True) resp = await self._interceptor.post_update_instance(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = await self._interceptor.post_update_instance_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = await self._interceptor.post_update_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), - "status": "OK", # need to obtain this properly + "headers": dict(response.headers), + "status": "OK", # need to obtain this properly } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.update_instance", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "UpdateInstance", "metadata": http_response["headers"], @@ -1267,87 +1532,93 @@ def operations_client(self) -> AsyncOperationsRestClient: # Only create a new client if we do not already have one. if self._operations_client is None: http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ + "google.longrunning.Operations.CancelOperation": [ { - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", }, ], - 'google.longrunning.Operations.DeleteOperation': [ + "google.longrunning.Operations.DeleteOperation": [ { - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", }, ], - 'google.longrunning.Operations.GetOperation': [ + "google.longrunning.Operations.GetOperation": [ { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", }, ], - 'google.longrunning.Operations.ListOperations': [ + "google.longrunning.Operations.ListOperations": [ { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", }, ], - 'google.longrunning.Operations.WaitOperation': [ + "google.longrunning.Operations.WaitOperation": [ { - 'method': 'post', - 'uri': '/v2/{name=projects/*/locations/*/operations/*}:wait', - 'body': '*', + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/operations/*}:wait", + "body": "*", }, ], } rest_transport = operations_v1.AsyncOperationsRestTransport( # type: ignore - host=self._host, - # use the credentials which are saved - credentials=self._credentials, # type: ignore - http_options=http_options, - path_prefix="v1" + host=self._host, + # use the credentials which are saved + credentials=self._credentials, # type: ignore + http_options=http_options, + path_prefix="v1", ) - self._operations_client = AsyncOperationsRestClient(transport=rest_transport) + self._operations_client = AsyncOperationsRestClient( + transport=rest_transport + ) # Return the client from cache. return self._operations_client @property - def create_instance(self) -> Callable[ - [cloud_redis.CreateInstanceRequest], - operations_pb2.Operation]: + def create_instance( + self, + ) -> Callable[[cloud_redis.CreateInstanceRequest], operations_pb2.Operation]: return self._CreateInstance(self._session, self._host, self._interceptor) # type: ignore @property - def delete_instance(self) -> Callable[ - [cloud_redis.DeleteInstanceRequest], - operations_pb2.Operation]: + def delete_instance( + self, + ) -> Callable[[cloud_redis.DeleteInstanceRequest], operations_pb2.Operation]: return self._DeleteInstance(self._session, self._host, self._interceptor) # type: ignore @property - def get_instance(self) -> Callable[ - [cloud_redis.GetInstanceRequest], - cloud_redis.Instance]: + def get_instance( + self, + ) -> Callable[[cloud_redis.GetInstanceRequest], cloud_redis.Instance]: return self._GetInstance(self._session, self._host, self._interceptor) # type: ignore @property - def list_instances(self) -> Callable[ - [cloud_redis.ListInstancesRequest], - cloud_redis.ListInstancesResponse]: + def list_instances( + self, + ) -> Callable[ + [cloud_redis.ListInstancesRequest], cloud_redis.ListInstancesResponse + ]: return self._ListInstances(self._session, self._host, self._interceptor) # type: ignore @property - def update_instance(self) -> Callable[ - [cloud_redis.UpdateInstanceRequest], - operations_pb2.Operation]: + def update_instance( + self, + ) -> Callable[[cloud_redis.UpdateInstanceRequest], operations_pb2.Operation]: return self._UpdateInstance(self._session, self._host, self._interceptor) # type: ignore @property def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - class _GetLocation(_BaseCloudRedisRestTransport._BaseGetLocation, AsyncCloudRedisRestStub): + class _GetLocation( + _BaseCloudRedisRestTransport._BaseGetLocation, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.GetLocation") @@ -1359,27 +1630,28 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - async def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> locations_pb2.Location: - + async def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: r"""Call the get location method over HTTP. Args: @@ -1397,30 +1669,46 @@ async def __call__(self, locations_pb2.Location: Response from GetLocation method. """ - http_options = _BaseCloudRedisRestTransport._BaseGetLocation._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseGetLocation._get_http_options() + ) - request, metadata = await self._interceptor.pre_get_location(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_get_location( + request, metadata + ) + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseGetLocation._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.GetLocation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "GetLocation", "httpRequest": http_request, @@ -1429,34 +1717,45 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = await AsyncCloudRedisRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore content = await response.read() resp = locations_pb2.Location() resp = json_format.Parse(content, resp) resp = await self._interceptor.post_get_location(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.GetLocation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "GetLocation", "httpResponse": http_response, @@ -1467,9 +1766,11 @@ async def __call__(self, @property def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - class _ListLocations(_BaseCloudRedisRestTransport._BaseListLocations, AsyncCloudRedisRestStub): + class _ListLocations( + _BaseCloudRedisRestTransport._BaseListLocations, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.ListLocations") @@ -1481,27 +1782,28 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - async def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> locations_pb2.ListLocationsResponse: - + async def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: r"""Call the list locations method over HTTP. Args: @@ -1519,30 +1821,46 @@ async def __call__(self, locations_pb2.ListLocationsResponse: Response from ListLocations method. """ - http_options = _BaseCloudRedisRestTransport._BaseListLocations._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseListLocations._get_http_options() + ) - request, metadata = await self._interceptor.pre_list_locations(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseListLocations._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_list_locations( + request, metadata + ) + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseListLocations._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseListLocations._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.ListLocations", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ListLocations", "httpRequest": http_request, @@ -1551,34 +1869,45 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = await AsyncCloudRedisRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore content = await response.read() resp = locations_pb2.ListLocationsResponse() resp = json_format.Parse(content, resp) resp = await self._interceptor.post_list_locations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.ListLocations", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ListLocations", "httpResponse": http_response, @@ -1589,9 +1918,11 @@ async def __call__(self, @property def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - class _CancelOperation(_BaseCloudRedisRestTransport._BaseCancelOperation, AsyncCloudRedisRestStub): + class _CancelOperation( + _BaseCloudRedisRestTransport._BaseCancelOperation, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.CancelOperation") @@ -1603,27 +1934,28 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - async def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> None: - + async def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Call the cancel operation method over HTTP. Args: @@ -1638,30 +1970,42 @@ async def __call__(self, be of type `bytes`. """ - http_options = _BaseCloudRedisRestTransport._BaseCancelOperation._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseCancelOperation._get_http_options() + ) - request, metadata = await self._interceptor.pre_cancel_operation(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = _BaseCloudRedisRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) + query_params = _BaseCloudRedisRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.CancelOperation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "CancelOperation", "httpRequest": http_request, @@ -1670,24 +2014,37 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._CancelOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = ( + await AsyncCloudRedisRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore return await self._interceptor.post_cancel_operation(None) @property def delete_operation(self): - return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - class _DeleteOperation(_BaseCloudRedisRestTransport._BaseDeleteOperation, AsyncCloudRedisRestStub): + class _DeleteOperation( + _BaseCloudRedisRestTransport._BaseDeleteOperation, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.DeleteOperation") @@ -1699,27 +2056,28 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - async def __call__(self, - request: operations_pb2.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> None: - + async def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Call the delete operation method over HTTP. Args: @@ -1734,30 +2092,42 @@ async def __call__(self, be of type `bytes`. """ - http_options = _BaseCloudRedisRestTransport._BaseDeleteOperation._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseDeleteOperation._get_http_options() + ) - request, metadata = await self._interceptor.pre_delete_operation(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_delete_operation( + request, metadata + ) + transcoded_request = _BaseCloudRedisRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) + query_params = _BaseCloudRedisRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.DeleteOperation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "DeleteOperation", "httpRequest": http_request, @@ -1766,24 +2136,37 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._DeleteOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = ( + await AsyncCloudRedisRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore return await self._interceptor.post_delete_operation(None) @property def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(_BaseCloudRedisRestTransport._BaseGetOperation, AsyncCloudRedisRestStub): + class _GetOperation( + _BaseCloudRedisRestTransport._BaseGetOperation, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.GetOperation") @@ -1795,27 +2178,28 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - async def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - + async def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the get operation method over HTTP. Args: @@ -1833,30 +2217,46 @@ async def __call__(self, operations_pb2.Operation: Response from GetOperation method. """ - http_options = _BaseCloudRedisRestTransport._BaseGetOperation._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseGetOperation._get_http_options() + ) - request, metadata = await self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_get_operation( + request, metadata + ) + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.GetOperation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "GetOperation", "httpRequest": http_request, @@ -1865,34 +2265,45 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = await AsyncCloudRedisRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore content = await response.read() resp = operations_pb2.Operation() resp = json_format.Parse(content, resp) resp = await self._interceptor.post_get_operation(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.GetOperation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "GetOperation", "httpResponse": http_response, @@ -1903,9 +2314,11 @@ async def __call__(self, @property def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(_BaseCloudRedisRestTransport._BaseListOperations, AsyncCloudRedisRestStub): + class _ListOperations( + _BaseCloudRedisRestTransport._BaseListOperations, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.ListOperations") @@ -1917,27 +2330,28 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - async def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.ListOperationsResponse: - + async def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: r"""Call the list operations method over HTTP. Args: @@ -1955,30 +2369,44 @@ async def __call__(self, operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options = _BaseCloudRedisRestTransport._BaseListOperations._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseListOperations._get_http_options() + ) - request, metadata = await self._interceptor.pre_list_operations(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseListOperations._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_list_operations( + request, metadata + ) + transcoded_request = _BaseCloudRedisRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseListOperations._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.ListOperations", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ListOperations", "httpRequest": http_request, @@ -1987,34 +2415,45 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = await AsyncCloudRedisRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore content = await response.read() resp = operations_pb2.ListOperationsResponse() resp = json_format.Parse(content, resp) resp = await self._interceptor.post_list_operations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.ListOperations", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "ListOperations", "httpResponse": http_response, @@ -2025,9 +2464,11 @@ async def __call__(self, @property def wait_operation(self): - return self._WaitOperation(self._session, self._host, self._interceptor) # type: ignore + return self._WaitOperation(self._session, self._host, self._interceptor) # type: ignore - class _WaitOperation(_BaseCloudRedisRestTransport._BaseWaitOperation, AsyncCloudRedisRestStub): + class _WaitOperation( + _BaseCloudRedisRestTransport._BaseWaitOperation, AsyncCloudRedisRestStub + ): def __hash__(self): return hash("AsyncCloudRedisRestTransport.WaitOperation") @@ -2039,28 +2480,29 @@ async def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = await getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - async def __call__(self, - request: operations_pb2.WaitOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - + async def __call__( + self, + request: operations_pb2.WaitOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the wait operation method over HTTP. Args: @@ -2078,32 +2520,52 @@ async def __call__(self, operations_pb2.Operation: Response from WaitOperation method. """ - http_options = _BaseCloudRedisRestTransport._BaseWaitOperation._get_http_options() + http_options = ( + _BaseCloudRedisRestTransport._BaseWaitOperation._get_http_options() + ) - request, metadata = await self._interceptor.pre_wait_operation(request, metadata) - transcoded_request = _BaseCloudRedisRestTransport._BaseWaitOperation._get_transcoded_request(http_options, request) + request, metadata = await self._interceptor.pre_wait_operation( + request, metadata + ) + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseWaitOperation._get_transcoded_request( + http_options, request + ) + ) - body = _BaseCloudRedisRestTransport._BaseWaitOperation._get_request_body_json(transcoded_request) + body = ( + _BaseCloudRedisRestTransport._BaseWaitOperation._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = _BaseCloudRedisRestTransport._BaseWaitOperation._get_query_params_json(transcoded_request) + query_params = ( + _BaseCloudRedisRestTransport._BaseWaitOperation._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.redis_v1.CloudRedisClient.WaitOperation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "WaitOperation", "httpRequest": http_request, @@ -2112,34 +2574,46 @@ async def __call__(self, ) # Send the request - response = await AsyncCloudRedisRestTransport._WaitOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = await AsyncCloudRedisRestTransport._WaitOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: content = await response.read() - payload = json.loads(content.decode('utf-8')) - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + payload = json.loads(content.decode("utf-8")) + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore content = await response.read() resp = operations_pb2.Operation() resp = json_format.Parse(content, resp) resp = await self._interceptor.post_wait_operation(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.redis_v1.CloudRedisAsyncClient.WaitOperation", - extra = { + extra={ "serviceName": "google.cloud.redis.v1.CloudRedis", "rpcName": "WaitOperation", "httpResponse": http_response, diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/setup.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/setup.py index 02095ef25809..0ddf593dccc7 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/setup.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/setup.py @@ -17,23 +17,23 @@ import os import re -import setuptools # type: ignore +import setuptools # type: ignore package_root = os.path.abspath(os.path.dirname(__file__)) -name = 'google-cloud-redis' +name = "google-cloud-redis" description = "Google Cloud Redis API client library" version = None -with open(os.path.join(package_root, 'google/cloud/redis/gapic_version.py')) as fp: +with open(os.path.join(package_root, "google/cloud/redis/gapic_version.py")) as fp: version_candidates = re.findall( r"(?<=\")\d+\.\d+\.\d+[^\"\s]*(?=\")", fp.read(), ) - assert (len(version_candidates) == 1) + assert len(version_candidates) == 1 version = version_candidates[0] if version[0] == "0": @@ -52,9 +52,7 @@ "protobuf >= 6.33.5, < 8.0.0", ] extras = { - "async_rest": [ - "google-auth[aiohttp] >= 2.35.0, <3.0.0" - ], + "async_rest": ["google-auth[aiohttp] >= 2.35.0, <3.0.0"], } url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-redis" diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/__init__.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/__init__.py index c1ad7c247ae0..e5ec6f96bffb 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/__init__.py @@ -55,10 +55,12 @@ from .types.storage_batch_operations_types import RewriteObject from .types.storage_batch_operations_types import UpdateObjectCustomContext -if hasattr(api_core, "check_python_version") and hasattr(api_core, "check_dependency_versions"): # pragma: NO COVER - api_core.check_python_version("google.cloud.storagebatchoperations_v1") # type: ignore - api_core.check_dependency_versions("google.cloud.storagebatchoperations_v1") # type: ignore -else: # pragma: NO COVER +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.cloud.storagebatchoperations_v1") # type: ignore + api_core.check_dependency_versions("google.cloud.storagebatchoperations_v1") # type: ignore +else: # pragma: NO COVER # An older version of api_core is installed which does not define the # functions above. We do equivalent checks manually. try: @@ -67,12 +69,14 @@ _py_version_str = sys.version.split()[0] _package_label = "google.cloud.storagebatchoperations_v1" if sys.version_info < (3, 10): - warnings.warn("You are using a non-supported Python version " + - f"({_py_version_str}). Google will not post any further " + - f"updates to {_package_label} supporting this Python version. " + - "Please upgrade to the latest Python version, or at " + - f"least to Python 3.10, and then update {_package_label}.", - FutureWarning) + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.10, and then update {_package_label}.", + FutureWarning, + ) def parse_version_to_tuple(version_string: str): """Safely converts a semantic version string to a comparable tuple of integers. @@ -110,55 +114,59 @@ def _get_version(dependency_name): _recommendation = " (we recommend 7.x)" (_version_used, _version_used_string) = _get_version(_dependency_package) if _version_used and _version_used < _next_supported_version_tuple: - warnings.warn(f"Package {_package_label} depends on " + - f"{_dependency_package}, currently installed at version " + - f"{_version_used_string}. Future updates to " + - f"{_package_label} will require {_dependency_package} at " + - f"version {_next_supported_version} or higher{_recommendation}." + - " Please ensure " + - "that either (a) your Python environment doesn't pin the " + - f"version of {_dependency_package}, so that updates to " + - f"{_package_label} can require the higher version, or " + - "(b) you manually update your Python environment to use at " + - f"least version {_next_supported_version} of " + - f"{_dependency_package}.", - FutureWarning) + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) except Exception: - warnings.warn("Could not determine the version of Python " + - "currently being used. To continue receiving " + - "updates for {_package_label}, ensure you are " + - "using a supported version of Python; see " + - "https://devguide.python.org/versions/") + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) __all__ = ( - 'StorageBatchOperationsAsyncClient', -'BucketList', -'BucketOperation', -'CancelJobRequest', -'CancelJobResponse', -'Counters', -'CreateJobRequest', -'CustomContextUpdates', -'DeleteJobRequest', -'DeleteObject', -'ErrorLogEntry', -'ErrorSummary', -'GetBucketOperationRequest', -'GetJobRequest', -'Job', -'ListBucketOperationsRequest', -'ListBucketOperationsResponse', -'ListJobsRequest', -'ListJobsResponse', -'LoggingConfig', -'Manifest', -'ObjectCustomContextPayload', -'ObjectRetention', -'OperationMetadata', -'PrefixList', -'PutMetadata', -'PutObjectHold', -'RewriteObject', -'StorageBatchOperationsClient', -'UpdateObjectCustomContext', + "StorageBatchOperationsAsyncClient", + "BucketList", + "BucketOperation", + "CancelJobRequest", + "CancelJobResponse", + "Counters", + "CreateJobRequest", + "CustomContextUpdates", + "DeleteJobRequest", + "DeleteObject", + "ErrorLogEntry", + "ErrorSummary", + "GetBucketOperationRequest", + "GetJobRequest", + "Job", + "ListBucketOperationsRequest", + "ListBucketOperationsResponse", + "ListJobsRequest", + "ListJobsResponse", + "LoggingConfig", + "Manifest", + "ObjectCustomContextPayload", + "ObjectRetention", + "OperationMetadata", + "PrefixList", + "PutMetadata", + "PutObjectHold", + "RewriteObject", + "StorageBatchOperationsClient", + "UpdateObjectCustomContext", ) diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/async_client.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/async_client.py index 6a8c312c992f..e0df004e4255 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/async_client.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/async_client.py @@ -16,7 +16,18 @@ import logging as std_logging from collections import OrderedDict import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union +from typing import ( + Dict, + Callable, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) import uuid from google.cloud.storagebatchoperations_v1 import gapic_version as package_version @@ -25,8 +36,8 @@ from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf @@ -35,11 +46,13 @@ except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.storagebatchoperations_v1.services.storage_batch_operations import pagers +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.storagebatchoperations_v1.services.storage_batch_operations import ( + pagers, +) from google.cloud.storagebatchoperations_v1.types import storage_batch_operations from google.cloud.storagebatchoperations_v1.types import storage_batch_operations_types -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.api_core.operation as operation # type: ignore import google.api_core.operation_async as operation_async # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore @@ -49,12 +62,14 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) + class StorageBatchOperationsAsyncClient: """Storage Batch Operations offers a managed experience to perform batch operations on millions of Cloud Storage objects in @@ -72,22 +87,44 @@ class StorageBatchOperationsAsyncClient: _DEFAULT_ENDPOINT_TEMPLATE = StorageBatchOperationsClient._DEFAULT_ENDPOINT_TEMPLATE _DEFAULT_UNIVERSE = StorageBatchOperationsClient._DEFAULT_UNIVERSE - bucket_operation_path = staticmethod(StorageBatchOperationsClient.bucket_operation_path) - parse_bucket_operation_path = staticmethod(StorageBatchOperationsClient.parse_bucket_operation_path) + bucket_operation_path = staticmethod( + StorageBatchOperationsClient.bucket_operation_path + ) + parse_bucket_operation_path = staticmethod( + StorageBatchOperationsClient.parse_bucket_operation_path + ) crypto_key_path = staticmethod(StorageBatchOperationsClient.crypto_key_path) - parse_crypto_key_path = staticmethod(StorageBatchOperationsClient.parse_crypto_key_path) + parse_crypto_key_path = staticmethod( + StorageBatchOperationsClient.parse_crypto_key_path + ) job_path = staticmethod(StorageBatchOperationsClient.job_path) parse_job_path = staticmethod(StorageBatchOperationsClient.parse_job_path) - common_billing_account_path = staticmethod(StorageBatchOperationsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(StorageBatchOperationsClient.parse_common_billing_account_path) + common_billing_account_path = staticmethod( + StorageBatchOperationsClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + StorageBatchOperationsClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(StorageBatchOperationsClient.common_folder_path) - parse_common_folder_path = staticmethod(StorageBatchOperationsClient.parse_common_folder_path) - common_organization_path = staticmethod(StorageBatchOperationsClient.common_organization_path) - parse_common_organization_path = staticmethod(StorageBatchOperationsClient.parse_common_organization_path) + parse_common_folder_path = staticmethod( + StorageBatchOperationsClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + StorageBatchOperationsClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + StorageBatchOperationsClient.parse_common_organization_path + ) common_project_path = staticmethod(StorageBatchOperationsClient.common_project_path) - parse_common_project_path = staticmethod(StorageBatchOperationsClient.parse_common_project_path) - common_location_path = staticmethod(StorageBatchOperationsClient.common_location_path) - parse_common_location_path = staticmethod(StorageBatchOperationsClient.parse_common_location_path) + parse_common_project_path = staticmethod( + StorageBatchOperationsClient.parse_common_project_path + ) + common_location_path = staticmethod( + StorageBatchOperationsClient.common_location_path + ) + parse_common_location_path = staticmethod( + StorageBatchOperationsClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -124,12 +161,16 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): sa_file_func = ( StorageBatchOperationsClient.from_service_account_file.__func__ # type: ignore ) - return sa_file_func(StorageBatchOperationsAsyncClient, filename, *args, **kwargs) + return sa_file_func( + StorageBatchOperationsAsyncClient, filename, *args, **kwargs + ) from_service_account_json = from_service_account_file @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): """Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -192,12 +233,20 @@ def universe_domain(self) -> str: get_transport_class = StorageBatchOperationsClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, StorageBatchOperationsTransport, Callable[..., StorageBatchOperationsTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + StorageBatchOperationsTransport, + Callable[..., StorageBatchOperationsTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the storage batch operations async client. Args: @@ -255,31 +304,39 @@ def __init__(self, *, transport=transport, client_options=client_options, client_info=client_info, - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.storagebatchoperations_v1.StorageBatchOperationsAsyncClient`.", - extra = { + extra={ "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "credentialsType": None, - } + }, ) - async def list_jobs(self, - request: Optional[Union[storage_batch_operations.ListJobsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListJobsAsyncPager: + async def list_jobs( + self, + request: Optional[Union[storage_batch_operations.ListJobsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListJobsAsyncPager: r"""Lists Jobs in a given project. .. code-block:: python @@ -340,10 +397,14 @@ async def sample_list_jobs(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -357,14 +418,14 @@ async def sample_list_jobs(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_jobs] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_jobs + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -392,14 +453,15 @@ async def sample_list_jobs(): # Done; return the response. return response - async def get_job(self, - request: Optional[Union[storage_batch_operations.GetJobRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> storage_batch_operations_types.Job: + async def get_job( + self, + request: Optional[Union[storage_batch_operations.GetJobRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_batch_operations_types.Job: r"""Gets a batch job. .. code-block:: python @@ -456,10 +518,14 @@ async def sample_get_job(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -478,9 +544,7 @@ async def sample_get_job(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -497,16 +561,19 @@ async def sample_get_job(): # Done; return the response. return response - async def create_job(self, - request: Optional[Union[storage_batch_operations.CreateJobRequest, dict]] = None, - *, - parent: Optional[str] = None, - job: Optional[storage_batch_operations_types.Job] = None, - job_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def create_job( + self, + request: Optional[ + Union[storage_batch_operations.CreateJobRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + job: Optional[storage_batch_operations_types.Job] = None, + job_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Creates a batch job. .. code-block:: python @@ -590,10 +657,14 @@ async def sample_create_job(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, job, job_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -611,17 +682,17 @@ async def sample_create_job(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_job] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_job + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) - self._client._setup_request_id(request, 'request_id', False) + self._client._setup_request_id(request, "request_id", False) # Validate the universe domain. self._client._validate_universe_domain() @@ -645,14 +716,17 @@ async def sample_create_job(): # Done; return the response. return response - async def delete_job(self, - request: Optional[Union[storage_batch_operations.DeleteJobRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + async def delete_job( + self, + request: Optional[ + Union[storage_batch_operations.DeleteJobRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a batch job. .. code-block:: python @@ -700,10 +774,14 @@ async def sample_delete_job(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -717,17 +795,17 @@ async def sample_delete_job(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_job] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_job + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) - self._client._setup_request_id(request, 'request_id', False) + self._client._setup_request_id(request, "request_id", False) # Validate the universe domain. self._client._validate_universe_domain() @@ -740,14 +818,17 @@ async def sample_delete_job(): metadata=metadata, ) - async def cancel_job(self, - request: Optional[Union[storage_batch_operations.CancelJobRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> storage_batch_operations.CancelJobResponse: + async def cancel_job( + self, + request: Optional[ + Union[storage_batch_operations.CancelJobRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_batch_operations.CancelJobResponse: r"""Cancels a batch job. .. code-block:: python @@ -802,10 +883,14 @@ async def sample_cancel_job(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -819,17 +904,17 @@ async def sample_cancel_job(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.cancel_job] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.cancel_job + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) - self._client._setup_request_id(request, 'request_id', False) + self._client._setup_request_id(request, "request_id", False) # Validate the universe domain. self._client._validate_universe_domain() @@ -845,14 +930,17 @@ async def sample_cancel_job(): # Done; return the response. return response - async def list_bucket_operations(self, - request: Optional[Union[storage_batch_operations.ListBucketOperationsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListBucketOperationsAsyncPager: + async def list_bucket_operations( + self, + request: Optional[ + Union[storage_batch_operations.ListBucketOperationsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBucketOperationsAsyncPager: r"""Lists BucketOperations in a given project and job. .. code-block:: python @@ -914,14 +1002,20 @@ async def sample_list_bucket_operations(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, storage_batch_operations.ListBucketOperationsRequest): + if not isinstance( + request, storage_batch_operations.ListBucketOperationsRequest + ): request = storage_batch_operations.ListBucketOperationsRequest(request) # If we have keyword arguments corresponding to fields on the @@ -931,14 +1025,14 @@ async def sample_list_bucket_operations(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_bucket_operations] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_bucket_operations + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -966,14 +1060,17 @@ async def sample_list_bucket_operations(): # Done; return the response. return response - async def get_bucket_operation(self, - request: Optional[Union[storage_batch_operations.GetBucketOperationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> storage_batch_operations_types.BucketOperation: + async def get_bucket_operation( + self, + request: Optional[ + Union[storage_batch_operations.GetBucketOperationRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_batch_operations_types.BucketOperation: r"""Gets a BucketOperation. .. code-block:: python @@ -1032,10 +1129,14 @@ async def sample_get_bucket_operation(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1049,14 +1150,14 @@ async def sample_get_bucket_operation(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_bucket_operation] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_bucket_operation + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1115,8 +1216,7 @@ async def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1124,7 +1224,11 @@ async def list_operations( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1171,8 +1275,7 @@ async def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1180,7 +1283,11 @@ async def get_operation( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1231,15 +1338,19 @@ async def delete_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) async def cancel_operation( self, @@ -1286,15 +1397,19 @@ async def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) async def get_location( self, @@ -1338,8 +1453,7 @@ async def get_location( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1347,7 +1461,11 @@ async def get_location( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1394,8 +1512,7 @@ async def list_locations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1403,7 +1520,11 @@ async def list_locations( # Send the request. response = await rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1414,12 +1535,13 @@ async def __aenter__(self) -> "StorageBatchOperationsAsyncClient": async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "StorageBatchOperationsAsyncClient", -) +__all__ = ("StorageBatchOperationsAsyncClient",) diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py index 628f7cfffc32..1f4120fd7d0e 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py @@ -19,7 +19,19 @@ import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +from typing import ( + Dict, + Callable, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) import uuid import warnings @@ -29,11 +41,11 @@ from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.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.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 import google.protobuf try: @@ -43,17 +55,20 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.storagebatchoperations_v1.services.storage_batch_operations import pagers +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.storagebatchoperations_v1.services.storage_batch_operations import ( + pagers, +) from google.cloud.storagebatchoperations_v1.types import storage_batch_operations from google.cloud.storagebatchoperations_v1.types import storage_batch_operations_types -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.api_core.operation as operation # type: ignore import google.api_core.operation_async as operation_async # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore @@ -70,14 +85,18 @@ class StorageBatchOperationsClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[StorageBatchOperationsTransport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[StorageBatchOperationsTransport]] _transport_registry["grpc"] = StorageBatchOperationsGrpcTransport _transport_registry["grpc_asyncio"] = StorageBatchOperationsGrpcAsyncIOTransport _transport_registry["rest"] = StorageBatchOperationsRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[StorageBatchOperationsTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[StorageBatchOperationsTransport]: """Returns an appropriate transport class. Args: @@ -158,14 +177,16 @@ def _use_client_cert_effective(): bool: whether client certificate should be used for mTLS Raises: ValueError: (If using a version of google-auth without should_use_client_cert and - GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) """ # check if google-auth version supports should_use_client_cert for automatic mTLS enablement if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER return mtls.should_use_client_cert() - else: # pragma: NO COVER + else: # pragma: NO COVER # if unsupported, fallback to reading from env var - use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() if use_client_cert_str not in ("true", "false"): raise ValueError( "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" @@ -204,8 +225,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: StorageBatchOperationsClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -222,95 +242,156 @@ def transport(self) -> StorageBatchOperationsTransport: return self._transport @staticmethod - def bucket_operation_path(project: str,location: str,job: str,bucket_operation: str,) -> str: + def bucket_operation_path( + project: str, + location: str, + job: str, + bucket_operation: str, + ) -> str: """Returns a fully-qualified bucket_operation string.""" - return "projects/{project}/locations/{location}/jobs/{job}/bucketOperations/{bucket_operation}".format(project=project, location=location, job=job, bucket_operation=bucket_operation, ) + return "projects/{project}/locations/{location}/jobs/{job}/bucketOperations/{bucket_operation}".format( + project=project, + location=location, + job=job, + bucket_operation=bucket_operation, + ) @staticmethod - def parse_bucket_operation_path(path: str) -> Dict[str,str]: + def parse_bucket_operation_path(path: str) -> Dict[str, str]: """Parses a bucket_operation path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/jobs/(?P.+?)/bucketOperations/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/jobs/(?P.+?)/bucketOperations/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def crypto_key_path(project: str,location: str,key_ring: str,crypto_key: str,) -> str: + def crypto_key_path( + project: str, + location: str, + key_ring: str, + crypto_key: str, + ) -> str: """Returns a fully-qualified crypto_key string.""" - return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + ) @staticmethod - def parse_crypto_key_path(path: str) -> Dict[str,str]: + def parse_crypto_key_path(path: str) -> Dict[str, str]: """Parses a crypto_key path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def job_path(project: str,location: str,job: str,) -> str: + def job_path( + project: str, + location: str, + job: str, + ) -> str: """Returns a fully-qualified job string.""" - return "projects/{project}/locations/{location}/jobs/{job}".format(project=project, location=location, job=job, ) + return "projects/{project}/locations/{location}/jobs/{job}".format( + project=project, + location=location, + job=job, + ) @staticmethod - def parse_job_path(path: str) -> Dict[str,str]: + def parse_job_path(path: str) -> Dict[str, str]: """Parses a job path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/jobs/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/jobs/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + def common_billing_account_path( + billing_account: str, + ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path(folder: str, ) -> str: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path(organization: str, ) -> str: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path(project: str, ) -> str: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path(project: str, location: str, ) -> str: + def common_location_path( + project: str, + location: str, + ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -342,14 +423,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = StorageBatchOperationsClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Figure out the client cert source to use. client_cert_source = None @@ -362,7 +447,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): api_endpoint = cls.DEFAULT_MTLS_ENDPOINT else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -387,7 +474,9 @@ def _read_environment_variables(): use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod @@ -410,7 +499,9 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: """Return the API endpoint used by the client. Args: @@ -426,17 +517,27 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): _default_universe = StorageBatchOperationsClient._DEFAULT_UNIVERSE if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) api_endpoint = StorageBatchOperationsClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = StorageBatchOperationsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = ( + StorageBatchOperationsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + ) return api_endpoint @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: """Return the universe domain used by the client. Args: @@ -502,15 +603,18 @@ def _setup_request_id(request, field_name: str, is_proto3_optional: bool): setattr(request, field_name, str(uuid.uuid4())) def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError + self, error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: return cred = self._transport._credentials @@ -543,12 +647,20 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, StorageBatchOperationsTransport, Callable[..., StorageBatchOperationsTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + StorageBatchOperationsTransport, + Callable[..., StorageBatchOperationsTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the storage batch operations client. Args: @@ -606,13 +718,23 @@ def __init__(self, *, self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = StorageBatchOperationsClient._read_environment_variables() - self._client_cert_source = StorageBatchOperationsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = StorageBatchOperationsClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = StorageBatchOperationsClient._read_environment_variables() + self._client_cert_source = StorageBatchOperationsClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = StorageBatchOperationsClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -624,7 +746,9 @@ def __init__(self, *, api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -633,8 +757,10 @@ def __init__(self, *, if transport_provided: # transport is a StorageBatchOperationsTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if self._client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes " @@ -643,20 +769,30 @@ def __init__(self, *, self._transport = cast(StorageBatchOperationsTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - StorageBatchOperationsClient._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or StorageBatchOperationsClient._get_api_endpoint( self._client_options.api_endpoint, self._client_cert_source, self._universe_domain, - self._use_mtls_endpoint)) + self._use_mtls_endpoint, + ) + ) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) - transport_init: Union[Type[StorageBatchOperationsTransport], Callable[..., StorageBatchOperationsTransport]] = ( + transport_init: Union[ + Type[StorageBatchOperationsTransport], + Callable[..., StorageBatchOperationsTransport], + ] = ( StorageBatchOperationsClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., StorageBatchOperationsTransport], transport) @@ -675,28 +811,37 @@ def __init__(self, *, ) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.storagebatchoperations_v1.StorageBatchOperationsClient`.", - extra = { + extra={ "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "credentialsType": None, - } + }, ) - def list_jobs(self, - request: Optional[Union[storage_batch_operations.ListJobsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListJobsPager: + def list_jobs( + self, + request: Optional[Union[storage_batch_operations.ListJobsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListJobsPager: r"""Lists Jobs in a given project. .. code-block:: python @@ -757,10 +902,14 @@ def sample_list_jobs(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -778,9 +927,7 @@ def sample_list_jobs(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -808,14 +955,15 @@ def sample_list_jobs(): # Done; return the response. return response - def get_job(self, - request: Optional[Union[storage_batch_operations.GetJobRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> storage_batch_operations_types.Job: + def get_job( + self, + request: Optional[Union[storage_batch_operations.GetJobRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_batch_operations_types.Job: r"""Gets a batch job. .. code-block:: python @@ -872,10 +1020,14 @@ def sample_get_job(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -893,9 +1045,7 @@ def sample_get_job(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -912,16 +1062,19 @@ def sample_get_job(): # Done; return the response. return response - def create_job(self, - request: Optional[Union[storage_batch_operations.CreateJobRequest, dict]] = None, - *, - parent: Optional[str] = None, - job: Optional[storage_batch_operations_types.Job] = None, - job_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_job( + self, + request: Optional[ + Union[storage_batch_operations.CreateJobRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + job: Optional[storage_batch_operations_types.Job] = None, + job_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Creates a batch job. .. code-block:: python @@ -1005,10 +1158,14 @@ def sample_create_job(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, job, job_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1030,12 +1187,10 @@ def sample_create_job(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) - self._setup_request_id(request, 'request_id', False) + self._setup_request_id(request, "request_id", False) # Validate the universe domain. self._validate_universe_domain() @@ -1059,14 +1214,17 @@ def sample_create_job(): # Done; return the response. return response - def delete_job(self, - request: Optional[Union[storage_batch_operations.DeleteJobRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def delete_job( + self, + request: Optional[ + Union[storage_batch_operations.DeleteJobRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Deletes a batch job. .. code-block:: python @@ -1114,10 +1272,14 @@ def sample_delete_job(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1135,12 +1297,10 @@ def sample_delete_job(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) - self._setup_request_id(request, 'request_id', False) + self._setup_request_id(request, "request_id", False) # Validate the universe domain. self._validate_universe_domain() @@ -1153,14 +1313,17 @@ def sample_delete_job(): metadata=metadata, ) - def cancel_job(self, - request: Optional[Union[storage_batch_operations.CancelJobRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> storage_batch_operations.CancelJobResponse: + def cancel_job( + self, + request: Optional[ + Union[storage_batch_operations.CancelJobRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_batch_operations.CancelJobResponse: r"""Cancels a batch job. .. code-block:: python @@ -1215,10 +1378,14 @@ def sample_cancel_job(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1236,12 +1403,10 @@ def sample_cancel_job(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) - self._setup_request_id(request, 'request_id', False) + self._setup_request_id(request, "request_id", False) # Validate the universe domain. self._validate_universe_domain() @@ -1257,14 +1422,17 @@ def sample_cancel_job(): # Done; return the response. return response - def list_bucket_operations(self, - request: Optional[Union[storage_batch_operations.ListBucketOperationsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListBucketOperationsPager: + def list_bucket_operations( + self, + request: Optional[ + Union[storage_batch_operations.ListBucketOperationsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBucketOperationsPager: r"""Lists BucketOperations in a given project and job. .. code-block:: python @@ -1326,14 +1494,20 @@ def sample_list_bucket_operations(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, storage_batch_operations.ListBucketOperationsRequest): + if not isinstance( + request, storage_batch_operations.ListBucketOperationsRequest + ): request = storage_batch_operations.ListBucketOperationsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -1347,9 +1521,7 @@ def sample_list_bucket_operations(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1377,14 +1549,17 @@ def sample_list_bucket_operations(): # Done; return the response. return response - def get_bucket_operation(self, - request: Optional[Union[storage_batch_operations.GetBucketOperationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> storage_batch_operations_types.BucketOperation: + def get_bucket_operation( + self, + request: Optional[ + Union[storage_batch_operations.GetBucketOperationRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_batch_operations_types.BucketOperation: r"""Gets a BucketOperation. .. code-block:: python @@ -1443,10 +1618,14 @@ def sample_get_bucket_operation(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1464,9 +1643,7 @@ def sample_get_bucket_operation(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1538,8 +1715,7 @@ def list_operations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1548,7 +1724,11 @@ def list_operations( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1598,8 +1778,7 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1608,7 +1787,11 @@ def get_operation( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1662,15 +1845,19 @@ def delete_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) def cancel_operation( self, @@ -1717,15 +1904,19 @@ def cancel_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request_pb, retry=retry, timeout=timeout, metadata=metadata,) + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) def get_location( self, @@ -1769,8 +1960,7 @@ def get_location( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1779,7 +1969,11 @@ def get_location( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1829,8 +2023,7 @@ def list_locations( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), ) # Validate the universe domain. @@ -1839,7 +2032,11 @@ def list_locations( try: # Send the request. response = rpc( - request_pb, retry=retry, timeout=timeout, metadata=metadata,) + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1848,11 +2045,11 @@ def list_locations( raise e -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "StorageBatchOperationsClient", -) +__all__ = ("StorageBatchOperationsClient",) diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/base.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/base.py index 79736feb8f55..85f44c32efe1 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/base.py @@ -25,16 +25,18 @@ from google.api_core import retry as retries from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf -from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.cloud.storagebatchoperations_v1.types import storage_batch_operations from google.cloud.storagebatchoperations_v1.types import storage_batch_operations_types -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import google.protobuf.empty_pb2 as empty_pb2 # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ @@ -43,24 +45,23 @@ class StorageBatchOperationsTransport(abc.ABC): """Abstract transport class for StorageBatchOperations.""" - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - DEFAULT_HOST: str = 'storagebatchoperations.googleapis.com' + DEFAULT_HOST: str = "storagebatchoperations.googleapis.com" def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -99,31 +100,43 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host self._wrapped_methods: Dict[Callable, Callable] = {} @@ -245,14 +258,14 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -262,66 +275,81 @@ def operations_client(self): raise NotImplementedError() @property - def list_jobs(self) -> Callable[ - [storage_batch_operations.ListJobsRequest], - Union[ - storage_batch_operations.ListJobsResponse, - Awaitable[storage_batch_operations.ListJobsResponse] - ]]: + def list_jobs( + self, + ) -> Callable[ + [storage_batch_operations.ListJobsRequest], + Union[ + storage_batch_operations.ListJobsResponse, + Awaitable[storage_batch_operations.ListJobsResponse], + ], + ]: raise NotImplementedError() @property - def get_job(self) -> Callable[ - [storage_batch_operations.GetJobRequest], - Union[ - storage_batch_operations_types.Job, - Awaitable[storage_batch_operations_types.Job] - ]]: + def get_job( + self, + ) -> Callable[ + [storage_batch_operations.GetJobRequest], + Union[ + storage_batch_operations_types.Job, + Awaitable[storage_batch_operations_types.Job], + ], + ]: raise NotImplementedError() @property - def create_job(self) -> Callable[ - [storage_batch_operations.CreateJobRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_job( + self, + ) -> Callable[ + [storage_batch_operations.CreateJobRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def delete_job(self) -> Callable[ - [storage_batch_operations.DeleteJobRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_job( + self, + ) -> Callable[ + [storage_batch_operations.DeleteJobRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property - def cancel_job(self) -> Callable[ - [storage_batch_operations.CancelJobRequest], - Union[ - storage_batch_operations.CancelJobResponse, - Awaitable[storage_batch_operations.CancelJobResponse] - ]]: + def cancel_job( + self, + ) -> Callable[ + [storage_batch_operations.CancelJobRequest], + Union[ + storage_batch_operations.CancelJobResponse, + Awaitable[storage_batch_operations.CancelJobResponse], + ], + ]: raise NotImplementedError() @property - def list_bucket_operations(self) -> Callable[ - [storage_batch_operations.ListBucketOperationsRequest], - Union[ - storage_batch_operations.ListBucketOperationsResponse, - Awaitable[storage_batch_operations.ListBucketOperationsResponse] - ]]: + def list_bucket_operations( + self, + ) -> Callable[ + [storage_batch_operations.ListBucketOperationsRequest], + Union[ + storage_batch_operations.ListBucketOperationsResponse, + Awaitable[storage_batch_operations.ListBucketOperationsResponse], + ], + ]: raise NotImplementedError() @property - def get_bucket_operation(self) -> Callable[ - [storage_batch_operations.GetBucketOperationRequest], - Union[ - storage_batch_operations_types.BucketOperation, - Awaitable[storage_batch_operations_types.BucketOperation] - ]]: + def get_bucket_operation( + self, + ) -> Callable[ + [storage_batch_operations.GetBucketOperationRequest], + Union[ + storage_batch_operations_types.BucketOperation, + Awaitable[storage_batch_operations_types.BucketOperation], + ], + ]: raise NotImplementedError() @property @@ -329,7 +357,10 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], ]: raise NotImplementedError() @@ -345,23 +376,18 @@ def get_operation( @property def cancel_operation( self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: raise NotImplementedError() @property def delete_operation( self, - ) -> Callable[ - [operations_pb2.DeleteOperationRequest], - None, - ]: + ) -> Callable[[operations_pb2.DeleteOperationRequest], None,]: raise NotImplementedError() @property - def get_location(self, + def get_location( + self, ) -> Callable[ [locations_pb2.GetLocationRequest], Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], @@ -369,10 +395,14 @@ def get_location(self, raise NotImplementedError() @property - def list_locations(self, + def list_locations( + self, ) -> Callable[ [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], ]: raise NotImplementedError() @@ -381,6 +411,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'StorageBatchOperationsTransport', -) +__all__ = ("StorageBatchOperationsTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/rest.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/rest.py index f251dc2f7107..688802182567 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/rest.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/rest.py @@ -27,7 +27,7 @@ from google.protobuf import json_format from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from requests import __version__ as requests_version import dataclasses @@ -51,6 +51,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -139,7 +140,15 @@ def post_list_jobs(self, response): """ - def pre_cancel_job(self, request: storage_batch_operations.CancelJobRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[storage_batch_operations.CancelJobRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_cancel_job( + self, + request: storage_batch_operations.CancelJobRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_batch_operations.CancelJobRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for cancel_job Override in a subclass to manipulate the request or metadata @@ -147,7 +156,9 @@ def pre_cancel_job(self, request: storage_batch_operations.CancelJobRequest, met """ return request, metadata - def post_cancel_job(self, response: storage_batch_operations.CancelJobResponse) -> storage_batch_operations.CancelJobResponse: + def post_cancel_job( + self, response: storage_batch_operations.CancelJobResponse + ) -> storage_batch_operations.CancelJobResponse: """Post-rpc interceptor for cancel_job DEPRECATED. Please use the `post_cancel_job_with_metadata` @@ -160,7 +171,14 @@ def post_cancel_job(self, response: storage_batch_operations.CancelJobResponse) """ return response - def post_cancel_job_with_metadata(self, response: storage_batch_operations.CancelJobResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[storage_batch_operations.CancelJobResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_cancel_job_with_metadata( + self, + response: storage_batch_operations.CancelJobResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_batch_operations.CancelJobResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for cancel_job Override in a subclass to read or manipulate the response or metadata after it @@ -175,7 +193,14 @@ def post_cancel_job_with_metadata(self, response: storage_batch_operations.Cance """ return response, metadata - def pre_create_job(self, request: storage_batch_operations.CreateJobRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[storage_batch_operations.CreateJobRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_create_job( + self, + request: storage_batch_operations.CreateJobRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_batch_operations.CreateJobRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for create_job Override in a subclass to manipulate the request or metadata @@ -183,7 +208,9 @@ def pre_create_job(self, request: storage_batch_operations.CreateJobRequest, met """ return request, metadata - def post_create_job(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_create_job( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for create_job DEPRECATED. Please use the `post_create_job_with_metadata` @@ -196,7 +223,11 @@ def post_create_job(self, response: operations_pb2.Operation) -> operations_pb2. """ return response - def post_create_job_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_create_job_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for create_job Override in a subclass to read or manipulate the response or metadata after it @@ -211,7 +242,14 @@ def post_create_job_with_metadata(self, response: operations_pb2.Operation, meta """ return response, metadata - def pre_delete_job(self, request: storage_batch_operations.DeleteJobRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[storage_batch_operations.DeleteJobRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_delete_job( + self, + request: storage_batch_operations.DeleteJobRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_batch_operations.DeleteJobRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for delete_job Override in a subclass to manipulate the request or metadata @@ -219,7 +257,14 @@ def pre_delete_job(self, request: storage_batch_operations.DeleteJobRequest, met """ return request, metadata - def pre_get_bucket_operation(self, request: storage_batch_operations.GetBucketOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[storage_batch_operations.GetBucketOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_get_bucket_operation( + self, + request: storage_batch_operations.GetBucketOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_batch_operations.GetBucketOperationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for get_bucket_operation Override in a subclass to manipulate the request or metadata @@ -227,7 +272,9 @@ def pre_get_bucket_operation(self, request: storage_batch_operations.GetBucketOp """ return request, metadata - def post_get_bucket_operation(self, response: storage_batch_operations_types.BucketOperation) -> storage_batch_operations_types.BucketOperation: + def post_get_bucket_operation( + self, response: storage_batch_operations_types.BucketOperation + ) -> storage_batch_operations_types.BucketOperation: """Post-rpc interceptor for get_bucket_operation DEPRECATED. Please use the `post_get_bucket_operation_with_metadata` @@ -240,7 +287,14 @@ def post_get_bucket_operation(self, response: storage_batch_operations_types.Buc """ return response - def post_get_bucket_operation_with_metadata(self, response: storage_batch_operations_types.BucketOperation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[storage_batch_operations_types.BucketOperation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_bucket_operation_with_metadata( + self, + response: storage_batch_operations_types.BucketOperation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_batch_operations_types.BucketOperation, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for get_bucket_operation Override in a subclass to read or manipulate the response or metadata after it @@ -255,7 +309,13 @@ def post_get_bucket_operation_with_metadata(self, response: storage_batch_operat """ return response, metadata - def pre_get_job(self, request: storage_batch_operations.GetJobRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[storage_batch_operations.GetJobRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_get_job( + self, + request: storage_batch_operations.GetJobRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_batch_operations.GetJobRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_job Override in a subclass to manipulate the request or metadata @@ -263,7 +323,9 @@ def pre_get_job(self, request: storage_batch_operations.GetJobRequest, metadata: """ return request, metadata - def post_get_job(self, response: storage_batch_operations_types.Job) -> storage_batch_operations_types.Job: + def post_get_job( + self, response: storage_batch_operations_types.Job + ) -> storage_batch_operations_types.Job: """Post-rpc interceptor for get_job DEPRECATED. Please use the `post_get_job_with_metadata` @@ -276,7 +338,13 @@ def post_get_job(self, response: storage_batch_operations_types.Job) -> storage_ """ return response - def post_get_job_with_metadata(self, response: storage_batch_operations_types.Job, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[storage_batch_operations_types.Job, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_job_with_metadata( + self, + response: storage_batch_operations_types.Job, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_batch_operations_types.Job, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for get_job Override in a subclass to read or manipulate the response or metadata after it @@ -291,7 +359,14 @@ def post_get_job_with_metadata(self, response: storage_batch_operations_types.Jo """ return response, metadata - def pre_list_bucket_operations(self, request: storage_batch_operations.ListBucketOperationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[storage_batch_operations.ListBucketOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_bucket_operations( + self, + request: storage_batch_operations.ListBucketOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_batch_operations.ListBucketOperationsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for list_bucket_operations Override in a subclass to manipulate the request or metadata @@ -299,7 +374,9 @@ def pre_list_bucket_operations(self, request: storage_batch_operations.ListBucke """ return request, metadata - def post_list_bucket_operations(self, response: storage_batch_operations.ListBucketOperationsResponse) -> storage_batch_operations.ListBucketOperationsResponse: + def post_list_bucket_operations( + self, response: storage_batch_operations.ListBucketOperationsResponse + ) -> storage_batch_operations.ListBucketOperationsResponse: """Post-rpc interceptor for list_bucket_operations DEPRECATED. Please use the `post_list_bucket_operations_with_metadata` @@ -312,7 +389,14 @@ def post_list_bucket_operations(self, response: storage_batch_operations.ListBuc """ return response - def post_list_bucket_operations_with_metadata(self, response: storage_batch_operations.ListBucketOperationsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[storage_batch_operations.ListBucketOperationsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_bucket_operations_with_metadata( + self, + response: storage_batch_operations.ListBucketOperationsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_batch_operations.ListBucketOperationsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for list_bucket_operations Override in a subclass to read or manipulate the response or metadata after it @@ -327,7 +411,14 @@ def post_list_bucket_operations_with_metadata(self, response: storage_batch_oper """ return response, metadata - def pre_list_jobs(self, request: storage_batch_operations.ListJobsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[storage_batch_operations.ListJobsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_jobs( + self, + request: storage_batch_operations.ListJobsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_batch_operations.ListJobsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for list_jobs Override in a subclass to manipulate the request or metadata @@ -335,7 +426,9 @@ def pre_list_jobs(self, request: storage_batch_operations.ListJobsRequest, metad """ return request, metadata - def post_list_jobs(self, response: storage_batch_operations.ListJobsResponse) -> storage_batch_operations.ListJobsResponse: + def post_list_jobs( + self, response: storage_batch_operations.ListJobsResponse + ) -> storage_batch_operations.ListJobsResponse: """Post-rpc interceptor for list_jobs DEPRECATED. Please use the `post_list_jobs_with_metadata` @@ -348,7 +441,14 @@ def post_list_jobs(self, response: storage_batch_operations.ListJobsResponse) -> """ return response - def post_list_jobs_with_metadata(self, response: storage_batch_operations.ListJobsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[storage_batch_operations.ListJobsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_jobs_with_metadata( + self, + response: storage_batch_operations.ListJobsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_batch_operations.ListJobsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for list_jobs Override in a subclass to read or manipulate the response or metadata after it @@ -364,8 +464,12 @@ def post_list_jobs_with_metadata(self, response: storage_batch_operations.ListJo return response, metadata def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_location Override in a subclass to manipulate the request or metadata @@ -385,8 +489,12 @@ def post_get_location( return response def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_locations Override in a subclass to manipulate the request or metadata @@ -406,8 +514,12 @@ def post_list_locations( return response def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for cancel_operation Override in a subclass to manipulate the request or metadata @@ -415,9 +527,7 @@ def pre_cancel_operation( """ return request, metadata - def post_cancel_operation( - self, response: None - ) -> None: + def post_cancel_operation(self, response: None) -> None: """Post-rpc interceptor for cancel_operation Override in a subclass to manipulate the response @@ -427,8 +537,12 @@ def post_cancel_operation( return response def pre_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for delete_operation Override in a subclass to manipulate the request or metadata @@ -436,9 +550,7 @@ def pre_delete_operation( """ return request, metadata - def post_delete_operation( - self, response: None - ) -> None: + def post_delete_operation(self, response: None) -> None: """Post-rpc interceptor for delete_operation Override in a subclass to manipulate the response @@ -448,8 +560,12 @@ def post_delete_operation( return response def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_operation Override in a subclass to manipulate the request or metadata @@ -469,8 +585,12 @@ def post_get_operation( return response def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_operations Override in a subclass to manipulate the request or metadata @@ -513,62 +633,63 @@ class StorageBatchOperationsRestTransport(_BaseStorageBatchOperationsRestTranspo It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__(self, *, - host: str = 'storagebatchoperations.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[StorageBatchOperationsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: + def __init__( + self, + *, + host: str = "storagebatchoperations.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[StorageBatchOperationsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. - NOTE: This REST transport functionality is currently in a beta - state (preview). We welcome your feedback via a GitHub issue in - this library's repository. Thank you! - - Args: - host (Optional[str]): - The hostname to connect to (default: 'storagebatchoperations.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. This argument will be - removed in the next major version of this library. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - interceptor (Optional[StorageBatchOperationsRestInterceptor]): Interceptor used - to manipulate requests, request metadata, and responses. - api_audience (Optional[str]): The intended audience for the API calls - to the service that will be set when using certain 3rd party - authentication flows. Audience is typically a resource identifier. - If not set, the host value will be used as a default. + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to (default: 'storagebatchoperations.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[StorageBatchOperationsRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. """ # Run the base constructor # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. @@ -580,10 +701,11 @@ def __init__(self, *, client_info=client_info, always_use_jwt_access=always_use_jwt_access, url_scheme=url_scheme, - api_audience=api_audience + api_audience=api_audience, ) self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) + self._credentials, default_host=self.DEFAULT_HOST + ) self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None if client_cert_source_for_mtls: self._session.configure_mtls_channel(client_cert_source_for_mtls) @@ -600,47 +722,53 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Only create a new client if we do not already have one. if self._operations_client is None: http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ + "google.longrunning.Operations.CancelOperation": [ { - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", }, ], - 'google.longrunning.Operations.DeleteOperation': [ + "google.longrunning.Operations.DeleteOperation": [ { - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", }, ], - 'google.longrunning.Operations.GetOperation': [ + "google.longrunning.Operations.GetOperation": [ { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", }, ], - 'google.longrunning.Operations.ListOperations': [ + "google.longrunning.Operations.ListOperations": [ { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", }, ], } rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) # Return the client from cache. return self._operations_client - class _CancelJob(_BaseStorageBatchOperationsRestTransport._BaseCancelJob, StorageBatchOperationsRestStub): + class _CancelJob( + _BaseStorageBatchOperationsRestTransport._BaseCancelJob, + StorageBatchOperationsRestStub, + ): def __hash__(self): return hash("StorageBatchOperationsRestTransport.CancelJob") @@ -652,27 +780,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: storage_batch_operations.CancelJobRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> storage_batch_operations.CancelJobResponse: + def __call__( + self, + request: storage_batch_operations.CancelJobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_batch_operations.CancelJobResponse: r"""Call the cancel job method over HTTP. Args: @@ -691,32 +821,44 @@ def __call__(self, Message for response to cancel Job. """ - http_options = _BaseStorageBatchOperationsRestTransport._BaseCancelJob._get_http_options() + http_options = ( + _BaseStorageBatchOperationsRestTransport._BaseCancelJob._get_http_options() + ) request, metadata = self._interceptor.pre_cancel_job(request, metadata) - transcoded_request = _BaseStorageBatchOperationsRestTransport._BaseCancelJob._get_transcoded_request(http_options, request) + transcoded_request = _BaseStorageBatchOperationsRestTransport._BaseCancelJob._get_transcoded_request( + http_options, request + ) - body = _BaseStorageBatchOperationsRestTransport._BaseCancelJob._get_request_body_json(transcoded_request) + body = _BaseStorageBatchOperationsRestTransport._BaseCancelJob._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseStorageBatchOperationsRestTransport._BaseCancelJob._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseStorageBatchOperationsRestTransport._BaseCancelJob._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.storagebatchoperations_v1.StorageBatchOperationsClient.CancelJob", - extra = { + extra={ "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "rpcName": "CancelJob", "httpRequest": http_request, @@ -725,7 +867,15 @@ def __call__(self, ) # Send the request - response = StorageBatchOperationsRestTransport._CancelJob._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = StorageBatchOperationsRestTransport._CancelJob._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -740,20 +890,26 @@ def __call__(self, resp = self._interceptor.post_cancel_job(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_cancel_job_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_cancel_job_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = storage_batch_operations.CancelJobResponse.to_json(response) + response_payload = ( + storage_batch_operations.CancelJobResponse.to_json(response) + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.storagebatchoperations_v1.StorageBatchOperationsClient.cancel_job", - extra = { + extra={ "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "rpcName": "CancelJob", "metadata": http_response["headers"], @@ -762,7 +918,10 @@ def __call__(self, ) return resp - class _CreateJob(_BaseStorageBatchOperationsRestTransport._BaseCreateJob, StorageBatchOperationsRestStub): + class _CreateJob( + _BaseStorageBatchOperationsRestTransport._BaseCreateJob, + StorageBatchOperationsRestStub, + ): def __hash__(self): return hash("StorageBatchOperationsRestTransport.CreateJob") @@ -774,27 +933,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: storage_batch_operations.CreateJobRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: storage_batch_operations.CreateJobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the create job method over HTTP. Args: @@ -816,32 +977,44 @@ def __call__(self, """ - http_options = _BaseStorageBatchOperationsRestTransport._BaseCreateJob._get_http_options() + http_options = ( + _BaseStorageBatchOperationsRestTransport._BaseCreateJob._get_http_options() + ) request, metadata = self._interceptor.pre_create_job(request, metadata) - transcoded_request = _BaseStorageBatchOperationsRestTransport._BaseCreateJob._get_transcoded_request(http_options, request) + transcoded_request = _BaseStorageBatchOperationsRestTransport._BaseCreateJob._get_transcoded_request( + http_options, request + ) - body = _BaseStorageBatchOperationsRestTransport._BaseCreateJob._get_request_body_json(transcoded_request) + body = _BaseStorageBatchOperationsRestTransport._BaseCreateJob._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseStorageBatchOperationsRestTransport._BaseCreateJob._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseStorageBatchOperationsRestTransport._BaseCreateJob._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.storagebatchoperations_v1.StorageBatchOperationsClient.CreateJob", - extra = { + extra={ "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "rpcName": "CreateJob", "httpRequest": http_request, @@ -850,7 +1023,15 @@ def __call__(self, ) # Send the request - response = StorageBatchOperationsRestTransport._CreateJob._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = StorageBatchOperationsRestTransport._CreateJob._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -863,20 +1044,24 @@ def __call__(self, resp = self._interceptor.post_create_job(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_job_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_create_job_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.storagebatchoperations_v1.StorageBatchOperationsClient.create_job", - extra = { + extra={ "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "rpcName": "CreateJob", "metadata": http_response["headers"], @@ -885,7 +1070,10 @@ def __call__(self, ) return resp - class _DeleteJob(_BaseStorageBatchOperationsRestTransport._BaseDeleteJob, StorageBatchOperationsRestStub): + class _DeleteJob( + _BaseStorageBatchOperationsRestTransport._BaseDeleteJob, + StorageBatchOperationsRestStub, + ): def __hash__(self): return hash("StorageBatchOperationsRestTransport.DeleteJob") @@ -897,26 +1085,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: storage_batch_operations.DeleteJobRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): + def __call__( + self, + request: storage_batch_operations.DeleteJobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): r"""Call the delete job method over HTTP. Args: @@ -931,30 +1121,40 @@ def __call__(self, be of type `bytes`. """ - http_options = _BaseStorageBatchOperationsRestTransport._BaseDeleteJob._get_http_options() + http_options = ( + _BaseStorageBatchOperationsRestTransport._BaseDeleteJob._get_http_options() + ) request, metadata = self._interceptor.pre_delete_job(request, metadata) - transcoded_request = _BaseStorageBatchOperationsRestTransport._BaseDeleteJob._get_transcoded_request(http_options, request) + transcoded_request = _BaseStorageBatchOperationsRestTransport._BaseDeleteJob._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseStorageBatchOperationsRestTransport._BaseDeleteJob._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseStorageBatchOperationsRestTransport._BaseDeleteJob._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.storagebatchoperations_v1.StorageBatchOperationsClient.DeleteJob", - extra = { + extra={ "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "rpcName": "DeleteJob", "httpRequest": http_request, @@ -963,14 +1163,24 @@ def __call__(self, ) # Send the request - response = StorageBatchOperationsRestTransport._DeleteJob._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = StorageBatchOperationsRestTransport._DeleteJob._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _GetBucketOperation(_BaseStorageBatchOperationsRestTransport._BaseGetBucketOperation, StorageBatchOperationsRestStub): + class _GetBucketOperation( + _BaseStorageBatchOperationsRestTransport._BaseGetBucketOperation, + StorageBatchOperationsRestStub, + ): def __hash__(self): return hash("StorageBatchOperationsRestTransport.GetBucketOperation") @@ -982,26 +1192,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: storage_batch_operations.GetBucketOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> storage_batch_operations_types.BucketOperation: + def __call__( + self, + request: storage_batch_operations.GetBucketOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_batch_operations_types.BucketOperation: r"""Call the get bucket operation method over HTTP. Args: @@ -1023,30 +1235,42 @@ def __call__(self, """ - http_options = _BaseStorageBatchOperationsRestTransport._BaseGetBucketOperation._get_http_options() + http_options = ( + _BaseStorageBatchOperationsRestTransport._BaseGetBucketOperation._get_http_options() + ) - request, metadata = self._interceptor.pre_get_bucket_operation(request, metadata) - transcoded_request = _BaseStorageBatchOperationsRestTransport._BaseGetBucketOperation._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_get_bucket_operation( + request, metadata + ) + transcoded_request = _BaseStorageBatchOperationsRestTransport._BaseGetBucketOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseStorageBatchOperationsRestTransport._BaseGetBucketOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseStorageBatchOperationsRestTransport._BaseGetBucketOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.storagebatchoperations_v1.StorageBatchOperationsClient.GetBucketOperation", - extra = { + extra={ "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "rpcName": "GetBucketOperation", "httpRequest": http_request, @@ -1055,7 +1279,16 @@ def __call__(self, ) # Send the request - response = StorageBatchOperationsRestTransport._GetBucketOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = ( + StorageBatchOperationsRestTransport._GetBucketOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1070,20 +1303,26 @@ def __call__(self, resp = self._interceptor.post_get_bucket_operation(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_bucket_operation_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_bucket_operation_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = storage_batch_operations_types.BucketOperation.to_json(response) + response_payload = ( + storage_batch_operations_types.BucketOperation.to_json(response) + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.storagebatchoperations_v1.StorageBatchOperationsClient.get_bucket_operation", - extra = { + extra={ "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "rpcName": "GetBucketOperation", "metadata": http_response["headers"], @@ -1092,7 +1331,10 @@ def __call__(self, ) return resp - class _GetJob(_BaseStorageBatchOperationsRestTransport._BaseGetJob, StorageBatchOperationsRestStub): + class _GetJob( + _BaseStorageBatchOperationsRestTransport._BaseGetJob, + StorageBatchOperationsRestStub, + ): def __hash__(self): return hash("StorageBatchOperationsRestTransport.GetJob") @@ -1104,26 +1346,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: storage_batch_operations.GetJobRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> storage_batch_operations_types.Job: + def __call__( + self, + request: storage_batch_operations.GetJobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_batch_operations_types.Job: r"""Call the get job method over HTTP. Args: @@ -1144,30 +1388,40 @@ def __call__(self, """ - http_options = _BaseStorageBatchOperationsRestTransport._BaseGetJob._get_http_options() + http_options = ( + _BaseStorageBatchOperationsRestTransport._BaseGetJob._get_http_options() + ) request, metadata = self._interceptor.pre_get_job(request, metadata) - transcoded_request = _BaseStorageBatchOperationsRestTransport._BaseGetJob._get_transcoded_request(http_options, request) + transcoded_request = _BaseStorageBatchOperationsRestTransport._BaseGetJob._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseStorageBatchOperationsRestTransport._BaseGetJob._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseStorageBatchOperationsRestTransport._BaseGetJob._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.storagebatchoperations_v1.StorageBatchOperationsClient.GetJob", - extra = { + extra={ "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "rpcName": "GetJob", "httpRequest": http_request, @@ -1176,7 +1430,14 @@ def __call__(self, ) # Send the request - response = StorageBatchOperationsRestTransport._GetJob._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = StorageBatchOperationsRestTransport._GetJob._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1191,20 +1452,26 @@ def __call__(self, resp = self._interceptor.post_get_job(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_job_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_job_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = storage_batch_operations_types.Job.to_json(response) + response_payload = storage_batch_operations_types.Job.to_json( + response + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.storagebatchoperations_v1.StorageBatchOperationsClient.get_job", - extra = { + extra={ "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "rpcName": "GetJob", "metadata": http_response["headers"], @@ -1213,7 +1480,10 @@ def __call__(self, ) return resp - class _ListBucketOperations(_BaseStorageBatchOperationsRestTransport._BaseListBucketOperations, StorageBatchOperationsRestStub): + class _ListBucketOperations( + _BaseStorageBatchOperationsRestTransport._BaseListBucketOperations, + StorageBatchOperationsRestStub, + ): def __hash__(self): return hash("StorageBatchOperationsRestTransport.ListBucketOperations") @@ -1225,26 +1495,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: storage_batch_operations.ListBucketOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> storage_batch_operations.ListBucketOperationsResponse: + def __call__( + self, + request: storage_batch_operations.ListBucketOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_batch_operations.ListBucketOperationsResponse: r"""Call the list bucket operations method over HTTP. Args: @@ -1266,30 +1538,42 @@ def __call__(self, """ - http_options = _BaseStorageBatchOperationsRestTransport._BaseListBucketOperations._get_http_options() + http_options = ( + _BaseStorageBatchOperationsRestTransport._BaseListBucketOperations._get_http_options() + ) - request, metadata = self._interceptor.pre_list_bucket_operations(request, metadata) - transcoded_request = _BaseStorageBatchOperationsRestTransport._BaseListBucketOperations._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_list_bucket_operations( + request, metadata + ) + transcoded_request = _BaseStorageBatchOperationsRestTransport._BaseListBucketOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseStorageBatchOperationsRestTransport._BaseListBucketOperations._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseStorageBatchOperationsRestTransport._BaseListBucketOperations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.storagebatchoperations_v1.StorageBatchOperationsClient.ListBucketOperations", - extra = { + extra={ "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "rpcName": "ListBucketOperations", "httpRequest": http_request, @@ -1298,7 +1582,16 @@ def __call__(self, ) # Send the request - response = StorageBatchOperationsRestTransport._ListBucketOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = ( + StorageBatchOperationsRestTransport._ListBucketOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1313,20 +1606,28 @@ def __call__(self, resp = self._interceptor.post_list_bucket_operations(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_bucket_operations_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_bucket_operations_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = storage_batch_operations.ListBucketOperationsResponse.to_json(response) + response_payload = ( + storage_batch_operations.ListBucketOperationsResponse.to_json( + response + ) + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.storagebatchoperations_v1.StorageBatchOperationsClient.list_bucket_operations", - extra = { + extra={ "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "rpcName": "ListBucketOperations", "metadata": http_response["headers"], @@ -1335,7 +1636,10 @@ def __call__(self, ) return resp - class _ListJobs(_BaseStorageBatchOperationsRestTransport._BaseListJobs, StorageBatchOperationsRestStub): + class _ListJobs( + _BaseStorageBatchOperationsRestTransport._BaseListJobs, + StorageBatchOperationsRestStub, + ): def __hash__(self): return hash("StorageBatchOperationsRestTransport.ListJobs") @@ -1347,26 +1651,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: storage_batch_operations.ListJobsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> storage_batch_operations.ListJobsResponse: + def __call__( + self, + request: storage_batch_operations.ListJobsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_batch_operations.ListJobsResponse: r"""Call the list jobs method over HTTP. Args: @@ -1385,30 +1691,40 @@ def __call__(self, Message for response to listing Jobs """ - http_options = _BaseStorageBatchOperationsRestTransport._BaseListJobs._get_http_options() + http_options = ( + _BaseStorageBatchOperationsRestTransport._BaseListJobs._get_http_options() + ) request, metadata = self._interceptor.pre_list_jobs(request, metadata) - transcoded_request = _BaseStorageBatchOperationsRestTransport._BaseListJobs._get_transcoded_request(http_options, request) + transcoded_request = _BaseStorageBatchOperationsRestTransport._BaseListJobs._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseStorageBatchOperationsRestTransport._BaseListJobs._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseStorageBatchOperationsRestTransport._BaseListJobs._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.storagebatchoperations_v1.StorageBatchOperationsClient.ListJobs", - extra = { + extra={ "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "rpcName": "ListJobs", "httpRequest": http_request, @@ -1417,7 +1733,14 @@ def __call__(self, ) # Send the request - response = StorageBatchOperationsRestTransport._ListJobs._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = StorageBatchOperationsRestTransport._ListJobs._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1432,20 +1755,26 @@ def __call__(self, resp = self._interceptor.post_list_jobs(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_jobs_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_jobs_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = storage_batch_operations.ListJobsResponse.to_json(response) + response_payload = ( + storage_batch_operations.ListJobsResponse.to_json(response) + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.storagebatchoperations_v1.StorageBatchOperationsClient.list_jobs", - extra = { + extra={ "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "rpcName": "ListJobs", "metadata": http_response["headers"], @@ -1455,66 +1784,85 @@ def __call__(self, return resp @property - def cancel_job(self) -> Callable[ - [storage_batch_operations.CancelJobRequest], - storage_batch_operations.CancelJobResponse]: + def cancel_job( + self, + ) -> Callable[ + [storage_batch_operations.CancelJobRequest], + storage_batch_operations.CancelJobResponse, + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._CancelJob(self._session, self._host, self._interceptor) # type: ignore + return self._CancelJob(self._session, self._host, self._interceptor) # type: ignore @property - def create_job(self) -> Callable[ - [storage_batch_operations.CreateJobRequest], - operations_pb2.Operation]: + def create_job( + self, + ) -> Callable[ + [storage_batch_operations.CreateJobRequest], operations_pb2.Operation + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._CreateJob(self._session, self._host, self._interceptor) # type: ignore + return self._CreateJob(self._session, self._host, self._interceptor) # type: ignore @property - def delete_job(self) -> Callable[ - [storage_batch_operations.DeleteJobRequest], - empty_pb2.Empty]: + def delete_job( + self, + ) -> Callable[[storage_batch_operations.DeleteJobRequest], empty_pb2.Empty]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._DeleteJob(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteJob(self._session, self._host, self._interceptor) # type: ignore @property - def get_bucket_operation(self) -> Callable[ - [storage_batch_operations.GetBucketOperationRequest], - storage_batch_operations_types.BucketOperation]: + def get_bucket_operation( + self, + ) -> Callable[ + [storage_batch_operations.GetBucketOperationRequest], + storage_batch_operations_types.BucketOperation, + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._GetBucketOperation(self._session, self._host, self._interceptor) # type: ignore + return self._GetBucketOperation(self._session, self._host, self._interceptor) # type: ignore @property - def get_job(self) -> Callable[ - [storage_batch_operations.GetJobRequest], - storage_batch_operations_types.Job]: + def get_job( + self, + ) -> Callable[ + [storage_batch_operations.GetJobRequest], storage_batch_operations_types.Job + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._GetJob(self._session, self._host, self._interceptor) # type: ignore + return self._GetJob(self._session, self._host, self._interceptor) # type: ignore @property - def list_bucket_operations(self) -> Callable[ - [storage_batch_operations.ListBucketOperationsRequest], - storage_batch_operations.ListBucketOperationsResponse]: + def list_bucket_operations( + self, + ) -> Callable[ + [storage_batch_operations.ListBucketOperationsRequest], + storage_batch_operations.ListBucketOperationsResponse, + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._ListBucketOperations(self._session, self._host, self._interceptor) # type: ignore + return self._ListBucketOperations(self._session, self._host, self._interceptor) # type: ignore @property - def list_jobs(self) -> Callable[ - [storage_batch_operations.ListJobsRequest], - storage_batch_operations.ListJobsResponse]: + def list_jobs( + self, + ) -> Callable[ + [storage_batch_operations.ListJobsRequest], + storage_batch_operations.ListJobsResponse, + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._ListJobs(self._session, self._host, self._interceptor) # type: ignore + return self._ListJobs(self._session, self._host, self._interceptor) # type: ignore @property def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - class _GetLocation(_BaseStorageBatchOperationsRestTransport._BaseGetLocation, StorageBatchOperationsRestStub): + class _GetLocation( + _BaseStorageBatchOperationsRestTransport._BaseGetLocation, + StorageBatchOperationsRestStub, + ): def __hash__(self): return hash("StorageBatchOperationsRestTransport.GetLocation") @@ -1526,27 +1874,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> locations_pb2.Location: - + def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: r"""Call the get location method over HTTP. Args: @@ -1564,30 +1913,40 @@ def __call__(self, locations_pb2.Location: Response from GetLocation method. """ - http_options = _BaseStorageBatchOperationsRestTransport._BaseGetLocation._get_http_options() + http_options = ( + _BaseStorageBatchOperationsRestTransport._BaseGetLocation._get_http_options() + ) request, metadata = self._interceptor.pre_get_location(request, metadata) - transcoded_request = _BaseStorageBatchOperationsRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) + transcoded_request = _BaseStorageBatchOperationsRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseStorageBatchOperationsRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseStorageBatchOperationsRestTransport._BaseGetLocation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.storagebatchoperations_v1.StorageBatchOperationsClient.GetLocation", - extra = { + extra={ "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "rpcName": "GetLocation", "httpRequest": http_request, @@ -1596,7 +1955,14 @@ def __call__(self, ) # Send the request - response = StorageBatchOperationsRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = StorageBatchOperationsRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1607,19 +1973,21 @@ def __call__(self, resp = locations_pb2.Location() resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_location(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.storagebatchoperations_v1.StorageBatchOperationsAsyncClient.GetLocation", - extra = { + extra={ "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "rpcName": "GetLocation", "httpResponse": http_response, @@ -1630,9 +1998,12 @@ def __call__(self, @property def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - class _ListLocations(_BaseStorageBatchOperationsRestTransport._BaseListLocations, StorageBatchOperationsRestStub): + class _ListLocations( + _BaseStorageBatchOperationsRestTransport._BaseListLocations, + StorageBatchOperationsRestStub, + ): def __hash__(self): return hash("StorageBatchOperationsRestTransport.ListLocations") @@ -1644,27 +2015,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> locations_pb2.ListLocationsResponse: - + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: r"""Call the list locations method over HTTP. Args: @@ -1682,30 +2054,40 @@ def __call__(self, locations_pb2.ListLocationsResponse: Response from ListLocations method. """ - http_options = _BaseStorageBatchOperationsRestTransport._BaseListLocations._get_http_options() + http_options = ( + _BaseStorageBatchOperationsRestTransport._BaseListLocations._get_http_options() + ) request, metadata = self._interceptor.pre_list_locations(request, metadata) - transcoded_request = _BaseStorageBatchOperationsRestTransport._BaseListLocations._get_transcoded_request(http_options, request) + transcoded_request = _BaseStorageBatchOperationsRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseStorageBatchOperationsRestTransport._BaseListLocations._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseStorageBatchOperationsRestTransport._BaseListLocations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.storagebatchoperations_v1.StorageBatchOperationsClient.ListLocations", - extra = { + extra={ "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "rpcName": "ListLocations", "httpRequest": http_request, @@ -1714,7 +2096,14 @@ def __call__(self, ) # Send the request - response = StorageBatchOperationsRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = StorageBatchOperationsRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1725,19 +2114,21 @@ def __call__(self, resp = locations_pb2.ListLocationsResponse() resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_locations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.storagebatchoperations_v1.StorageBatchOperationsAsyncClient.ListLocations", - extra = { + extra={ "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "rpcName": "ListLocations", "httpResponse": http_response, @@ -1748,9 +2139,12 @@ def __call__(self, @property def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - class _CancelOperation(_BaseStorageBatchOperationsRestTransport._BaseCancelOperation, StorageBatchOperationsRestStub): + class _CancelOperation( + _BaseStorageBatchOperationsRestTransport._BaseCancelOperation, + StorageBatchOperationsRestStub, + ): def __hash__(self): return hash("StorageBatchOperationsRestTransport.CancelOperation") @@ -1762,28 +2156,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> None: - + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Call the cancel operation method over HTTP. Args: @@ -1798,32 +2193,46 @@ def __call__(self, be of type `bytes`. """ - http_options = _BaseStorageBatchOperationsRestTransport._BaseCancelOperation._get_http_options() + http_options = ( + _BaseStorageBatchOperationsRestTransport._BaseCancelOperation._get_http_options() + ) - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - transcoded_request = _BaseStorageBatchOperationsRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = _BaseStorageBatchOperationsRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) - body = _BaseStorageBatchOperationsRestTransport._BaseCancelOperation._get_request_body_json(transcoded_request) + body = _BaseStorageBatchOperationsRestTransport._BaseCancelOperation._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseStorageBatchOperationsRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseStorageBatchOperationsRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.storagebatchoperations_v1.StorageBatchOperationsClient.CancelOperation", - extra = { + extra={ "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "rpcName": "CancelOperation", "httpRequest": http_request, @@ -1832,7 +2241,17 @@ def __call__(self, ) # Send the request - response = StorageBatchOperationsRestTransport._CancelOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = ( + StorageBatchOperationsRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1843,9 +2262,12 @@ def __call__(self, @property def delete_operation(self): - return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - class _DeleteOperation(_BaseStorageBatchOperationsRestTransport._BaseDeleteOperation, StorageBatchOperationsRestStub): + class _DeleteOperation( + _BaseStorageBatchOperationsRestTransport._BaseDeleteOperation, + StorageBatchOperationsRestStub, + ): def __hash__(self): return hash("StorageBatchOperationsRestTransport.DeleteOperation") @@ -1857,27 +2279,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: operations_pb2.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> None: - + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Call the delete operation method over HTTP. Args: @@ -1892,30 +2315,42 @@ def __call__(self, be of type `bytes`. """ - http_options = _BaseStorageBatchOperationsRestTransport._BaseDeleteOperation._get_http_options() + http_options = ( + _BaseStorageBatchOperationsRestTransport._BaseDeleteOperation._get_http_options() + ) - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - transcoded_request = _BaseStorageBatchOperationsRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + transcoded_request = _BaseStorageBatchOperationsRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseStorageBatchOperationsRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseStorageBatchOperationsRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.storagebatchoperations_v1.StorageBatchOperationsClient.DeleteOperation", - extra = { + extra={ "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "rpcName": "DeleteOperation", "httpRequest": http_request, @@ -1924,7 +2359,16 @@ def __call__(self, ) # Send the request - response = StorageBatchOperationsRestTransport._DeleteOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = ( + StorageBatchOperationsRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1935,9 +2379,12 @@ def __call__(self, @property def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(_BaseStorageBatchOperationsRestTransport._BaseGetOperation, StorageBatchOperationsRestStub): + class _GetOperation( + _BaseStorageBatchOperationsRestTransport._BaseGetOperation, + StorageBatchOperationsRestStub, + ): def __hash__(self): return hash("StorageBatchOperationsRestTransport.GetOperation") @@ -1949,27 +2396,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the get operation method over HTTP. Args: @@ -1987,30 +2435,40 @@ def __call__(self, operations_pb2.Operation: Response from GetOperation method. """ - http_options = _BaseStorageBatchOperationsRestTransport._BaseGetOperation._get_http_options() + http_options = ( + _BaseStorageBatchOperationsRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseStorageBatchOperationsRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + transcoded_request = _BaseStorageBatchOperationsRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseStorageBatchOperationsRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseStorageBatchOperationsRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.storagebatchoperations_v1.StorageBatchOperationsClient.GetOperation", - extra = { + extra={ "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "rpcName": "GetOperation", "httpRequest": http_request, @@ -2019,7 +2477,14 @@ def __call__(self, ) # Send the request - response = StorageBatchOperationsRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = StorageBatchOperationsRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2030,19 +2495,21 @@ def __call__(self, resp = operations_pb2.Operation() resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.storagebatchoperations_v1.StorageBatchOperationsAsyncClient.GetOperation", - extra = { + extra={ "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "rpcName": "GetOperation", "httpResponse": http_response, @@ -2053,9 +2520,12 @@ def __call__(self, @property def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(_BaseStorageBatchOperationsRestTransport._BaseListOperations, StorageBatchOperationsRestStub): + class _ListOperations( + _BaseStorageBatchOperationsRestTransport._BaseListOperations, + StorageBatchOperationsRestStub, + ): def __hash__(self): return hash("StorageBatchOperationsRestTransport.ListOperations") @@ -2067,27 +2537,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.ListOperationsResponse: - + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: r"""Call the list operations method over HTTP. Args: @@ -2105,30 +2576,40 @@ def __call__(self, operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options = _BaseStorageBatchOperationsRestTransport._BaseListOperations._get_http_options() + http_options = ( + _BaseStorageBatchOperationsRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - transcoded_request = _BaseStorageBatchOperationsRestTransport._BaseListOperations._get_transcoded_request(http_options, request) + transcoded_request = _BaseStorageBatchOperationsRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseStorageBatchOperationsRestTransport._BaseListOperations._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseStorageBatchOperationsRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.storagebatchoperations_v1.StorageBatchOperationsClient.ListOperations", - extra = { + extra={ "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "rpcName": "ListOperations", "httpRequest": http_request, @@ -2137,7 +2618,16 @@ def __call__(self, ) # Send the request - response = StorageBatchOperationsRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = ( + StorageBatchOperationsRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2148,19 +2638,21 @@ def __call__(self, resp = operations_pb2.ListOperationsResponse() resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.storagebatchoperations_v1.StorageBatchOperationsAsyncClient.ListOperations", - extra = { + extra={ "serviceName": "google.cloud.storagebatchoperations.v1.StorageBatchOperations", "rpcName": "ListOperations", "httpResponse": http_response, @@ -2177,6 +2669,4 @@ def close(self): self._session.close() -__all__=( - 'StorageBatchOperationsRestTransport', -) +__all__ = ("StorageBatchOperationsRestTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/setup.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/setup.py index 1250019e9117..f053549ad73e 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/setup.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/setup.py @@ -17,23 +17,25 @@ import os import re -import setuptools # type: ignore +import setuptools # type: ignore package_root = os.path.abspath(os.path.dirname(__file__)) -name = 'google-cloud-storagebatchoperations' +name = "google-cloud-storagebatchoperations" description = "Google Cloud Storagebatchoperations API client library" version = None -with open(os.path.join(package_root, 'google/cloud/storagebatchoperations/gapic_version.py')) as fp: +with open( + os.path.join(package_root, "google/cloud/storagebatchoperations/gapic_version.py") +) as fp: version_candidates = re.findall( r"(?<=\")\d+\.\d+\.\d+[^\"\s]*(?=\")", fp.read(), ) - assert (len(version_candidates) == 1) + assert len(version_candidates) == 1 version = version_candidates[0] if version[0] == "0": @@ -51,8 +53,7 @@ "proto-plus >= 1.26.1, <2.0.0", "protobuf >= 6.33.5, < 8.0.0", ] -extras = { -} +extras = {} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-storagebatchoperations" package_root = os.path.abspath(os.path.dirname(__file__)) diff --git a/packages/google-api-core/google/api_core/gapic_v1/__init__.py b/packages/google-api-core/google/api_core/gapic_v1/__init__.py index d5ee314d3946..3ffe78daaa07 100644 --- a/packages/google-api-core/google/api_core/gapic_v1/__init__.py +++ b/packages/google-api-core/google/api_core/gapic_v1/__init__.py @@ -12,10 +12,18 @@ # See the License for the specific language governing permissions and # limitations under the License. -from google.api_core.gapic_v1 import (_client_cert, _config_helpers, - _method_helpers, _routing, client_info, - config, config_async, method, - method_async, routing_header) +from google.api_core.gapic_v1 import ( + _client_cert, + _config_helpers, + _method_helpers, + _routing, + client_info, + config, + config_async, + method, + method_async, + routing_header, +) __all__ = [ "_client_cert", diff --git a/packages/google-api-core/tests/unit/gapic/test_client_helpers.py b/packages/google-api-core/tests/unit/gapic/test_client_helpers.py index 8f8bbd982e61..0fa935c752ce 100644 --- a/packages/google-api-core/tests/unit/gapic/test_client_helpers.py +++ b/packages/google-api-core/tests/unit/gapic/test_client_helpers.py @@ -25,13 +25,17 @@ from google.auth.exceptions import MutualTLSChannelError -from google.api_core.gapic_v1._client_cert import (get_client_cert_source, - use_client_cert_effective) +from google.api_core.gapic_v1._client_cert import ( + get_client_cert_source, + use_client_cert_effective, +) from google.api_core.gapic_v1._config_helpers import read_environment_variables from google.api_core.gapic_v1._method_helpers import setup_request_id -from google.api_core.gapic_v1._routing import (get_api_endpoint, - get_default_mtls_endpoint, - get_universe_domain) +from google.api_core.gapic_v1._routing import ( + get_api_endpoint, + get_default_mtls_endpoint, + get_universe_domain, +) def test_get_default_mtls_endpoint(): diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/client.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/client.py index cd72936dee09..038f0dcefeec 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/client.py +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/client.py @@ -913,9 +913,11 @@ def __init__( universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( - ChatServiceClient._read_environment_variables() - ) + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = ChatServiceClient._read_environment_variables() self._client_cert_source = ChatServiceClient._get_client_cert_source( self._client_options.client_cert_source, self._use_client_cert ) diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc.py index 7dcb48752050..69a58aaa8017 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc.py +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc.py @@ -2170,12 +2170,12 @@ def get_space_notification_setting( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_space_notification_setting" not in self._stubs: - self._stubs["get_space_notification_setting"] = ( - self._logged_channel.unary_unary( - "/google.chat.v1.ChatService/GetSpaceNotificationSetting", - request_serializer=space_notification_setting.GetSpaceNotificationSettingRequest.serialize, - response_deserializer=space_notification_setting.SpaceNotificationSetting.deserialize, - ) + self._stubs[ + "get_space_notification_setting" + ] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/GetSpaceNotificationSetting", + request_serializer=space_notification_setting.GetSpaceNotificationSettingRequest.serialize, + response_deserializer=space_notification_setting.SpaceNotificationSetting.deserialize, ) return self._stubs["get_space_notification_setting"] @@ -2211,12 +2211,12 @@ def update_space_notification_setting( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "update_space_notification_setting" not in self._stubs: - self._stubs["update_space_notification_setting"] = ( - self._logged_channel.unary_unary( - "/google.chat.v1.ChatService/UpdateSpaceNotificationSetting", - request_serializer=gc_space_notification_setting.UpdateSpaceNotificationSettingRequest.serialize, - response_deserializer=gc_space_notification_setting.SpaceNotificationSetting.deserialize, - ) + self._stubs[ + "update_space_notification_setting" + ] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/UpdateSpaceNotificationSetting", + request_serializer=gc_space_notification_setting.UpdateSpaceNotificationSettingRequest.serialize, + response_deserializer=gc_space_notification_setting.SpaceNotificationSetting.deserialize, ) return self._stubs["update_space_notification_setting"] diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc_asyncio.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc_asyncio.py index 33ac93647828..3e514fc17e66 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc_asyncio.py +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc_asyncio.py @@ -2207,12 +2207,12 @@ def get_space_notification_setting( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_space_notification_setting" not in self._stubs: - self._stubs["get_space_notification_setting"] = ( - self._logged_channel.unary_unary( - "/google.chat.v1.ChatService/GetSpaceNotificationSetting", - request_serializer=space_notification_setting.GetSpaceNotificationSettingRequest.serialize, - response_deserializer=space_notification_setting.SpaceNotificationSetting.deserialize, - ) + self._stubs[ + "get_space_notification_setting" + ] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/GetSpaceNotificationSetting", + request_serializer=space_notification_setting.GetSpaceNotificationSettingRequest.serialize, + response_deserializer=space_notification_setting.SpaceNotificationSetting.deserialize, ) return self._stubs["get_space_notification_setting"] @@ -2248,12 +2248,12 @@ def update_space_notification_setting( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "update_space_notification_setting" not in self._stubs: - self._stubs["update_space_notification_setting"] = ( - self._logged_channel.unary_unary( - "/google.chat.v1.ChatService/UpdateSpaceNotificationSetting", - request_serializer=gc_space_notification_setting.UpdateSpaceNotificationSettingRequest.serialize, - response_deserializer=gc_space_notification_setting.SpaceNotificationSetting.deserialize, - ) + self._stubs[ + "update_space_notification_setting" + ] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/UpdateSpaceNotificationSetting", + request_serializer=gc_space_notification_setting.UpdateSpaceNotificationSettingRequest.serialize, + response_deserializer=gc_space_notification_setting.SpaceNotificationSetting.deserialize, ) return self._stubs["update_space_notification_setting"] diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/rest.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/rest.py index 7cbcd89e7427..cc4fe14a782b 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/rest.py +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/rest.py @@ -2440,7 +2440,9 @@ def __call__( """ - http_options = _BaseChatServiceRestTransport._BaseCompleteImportSpace._get_http_options() + http_options = ( + _BaseChatServiceRestTransport._BaseCompleteImportSpace._get_http_options() + ) request, metadata = self._interceptor.pre_complete_import_space( request, metadata @@ -5437,7 +5439,9 @@ def __call__( """ - http_options = _BaseChatServiceRestTransport._BaseGetSpaceNotificationSetting._get_http_options() + http_options = ( + _BaseChatServiceRestTransport._BaseGetSpaceNotificationSetting._get_http_options() + ) request, metadata = self._interceptor.pre_get_space_notification_setting( request, metadata @@ -5503,10 +5507,11 @@ def __call__( resp = self._interceptor.post_get_space_notification_setting(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = ( - self._interceptor.post_get_space_notification_setting_with_metadata( - resp, response_metadata - ) + ( + resp, + _, + ) = self._interceptor.post_get_space_notification_setting_with_metadata( + resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG @@ -5743,7 +5748,9 @@ def __call__( """ - http_options = _BaseChatServiceRestTransport._BaseGetThreadReadState._get_http_options() + http_options = ( + _BaseChatServiceRestTransport._BaseGetThreadReadState._get_http_options() + ) request, metadata = self._interceptor.pre_get_thread_read_state( request, metadata @@ -8364,7 +8371,9 @@ def __call__( """ - http_options = _BaseChatServiceRestTransport._BaseUpdateSpaceNotificationSetting._get_http_options() + http_options = ( + _BaseChatServiceRestTransport._BaseUpdateSpaceNotificationSetting._get_http_options() + ) request, metadata = self._interceptor.pre_update_space_notification_setting( request, metadata @@ -8435,10 +8444,11 @@ def __call__( resp = self._interceptor.post_update_space_notification_setting(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = ( - self._interceptor.post_update_space_notification_setting_with_metadata( - resp, response_metadata - ) + ( + resp, + _, + ) = self._interceptor.post_update_space_notification_setting_with_metadata( + resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG @@ -8526,7 +8536,9 @@ def __call__( """ - http_options = _BaseChatServiceRestTransport._BaseUpdateSpaceReadState._get_http_options() + http_options = ( + _BaseChatServiceRestTransport._BaseUpdateSpaceReadState._get_http_options() + ) request, metadata = self._interceptor.pre_update_space_read_state( request, metadata diff --git a/packages/google-apps-chat/tests/unit/gapic/chat_v1/test_chat_service.py b/packages/google-apps-chat/tests/unit/gapic/chat_v1/test_chat_service.py index 833b2f207c53..d1f098b2d428 100644 --- a/packages/google-apps-chat/tests/unit/gapic/chat_v1/test_chat_service.py +++ b/packages/google-apps-chat/tests/unit/gapic/chat_v1/test_chat_service.py @@ -979,9 +979,10 @@ def test_chat_service_client_get_mtls_endpoint_and_cert_source(client_class): client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -1026,9 +1027,10 @@ def test_chat_service_client_get_mtls_endpoint_and_cert_source(client_class): client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -1064,9 +1066,10 @@ def test_chat_service_client_get_mtls_endpoint_and_cert_source(client_class): "google.auth.transport.mtls.default_client_cert_source", return_value=mock_client_cert_source, ): - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source() - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @@ -2342,9 +2345,9 @@ def test_list_memberships_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_memberships] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_memberships + ] = mock_rpc request = {} client.list_memberships(request) @@ -4551,9 +4554,9 @@ def test_upload_attachment_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.upload_attachment] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.upload_attachment + ] = mock_rpc request = {} client.upload_attachment(request) @@ -7166,9 +7169,9 @@ def test_complete_import_space_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.complete_import_space] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.complete_import_space + ] = mock_rpc request = {} client.complete_import_space(request) @@ -7449,9 +7452,9 @@ def test_find_direct_message_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.find_direct_message] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.find_direct_message + ] = mock_rpc request = {} client.find_direct_message(request) @@ -7661,9 +7664,9 @@ def test_find_group_chats_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.find_group_chats] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.find_group_chats + ] = mock_rpc request = {} client.find_group_chats(request) @@ -8039,9 +8042,9 @@ def test_create_membership_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_membership] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_membership + ] = mock_rpc request = {} client.create_membership(request) @@ -8393,9 +8396,9 @@ def test_update_membership_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_membership] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.update_membership + ] = mock_rpc request = {} client.update_membership(request) @@ -8751,9 +8754,9 @@ def test_delete_membership_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_membership] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_membership + ] = mock_rpc request = {} client.delete_membership(request) @@ -10263,9 +10266,9 @@ def test_create_custom_emoji_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_custom_emoji] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_custom_emoji + ] = mock_rpc request = {} client.create_custom_emoji(request) @@ -10546,9 +10549,9 @@ def test_get_custom_emoji_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_custom_emoji] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_custom_emoji + ] = mock_rpc request = {} client.get_custom_emoji(request) @@ -10886,9 +10889,9 @@ def test_list_custom_emojis_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_custom_emojis] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_custom_emojis + ] = mock_rpc request = {} client.list_custom_emojis(request) @@ -11269,9 +11272,9 @@ def test_delete_custom_emoji_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_custom_emoji] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_custom_emoji + ] = mock_rpc request = {} client.delete_custom_emoji(request) @@ -11602,9 +11605,9 @@ def test_get_space_read_state_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_space_read_state] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_space_read_state + ] = mock_rpc request = {} client.get_space_read_state(request) @@ -12298,9 +12301,9 @@ def test_get_thread_read_state_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_thread_read_state] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_thread_read_state + ] = mock_rpc request = {} client.get_thread_read_state(request) @@ -12972,9 +12975,9 @@ def test_list_space_events_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_space_events] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_space_events + ] = mock_rpc request = {} client.list_space_events(request) @@ -15771,9 +15774,9 @@ def test_position_section_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.position_section] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.position_section + ] = mock_rpc request = {} client.position_section(request) @@ -16022,9 +16025,9 @@ def test_list_section_items_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_section_items] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_section_items + ] = mock_rpc request = {} client.list_section_items(request) @@ -16559,9 +16562,9 @@ def test_move_section_item_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.move_section_item] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.move_section_item + ] = mock_rpc request = {} client.move_section_item(request) @@ -17300,9 +17303,9 @@ def test_list_memberships_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_memberships] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_memberships + ] = mock_rpc request = {} client.list_memberships(request) @@ -18458,9 +18461,9 @@ def test_upload_attachment_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.upload_attachment] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.upload_attachment + ] = mock_rpc request = {} client.upload_attachment(request) @@ -19725,9 +19728,9 @@ def test_complete_import_space_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.complete_import_space] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.complete_import_space + ] = mock_rpc request = {} client.complete_import_space(request) @@ -19850,9 +19853,9 @@ def test_find_direct_message_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.find_direct_message] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.find_direct_message + ] = mock_rpc request = {} client.find_direct_message(request) @@ -19983,9 +19986,9 @@ def test_find_group_chats_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.find_group_chats] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.find_group_chats + ] = mock_rpc request = {} client.find_group_chats(request) @@ -20082,9 +20085,9 @@ def test_create_membership_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_membership] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_membership + ] = mock_rpc request = {} client.create_membership(request) @@ -20273,9 +20276,9 @@ def test_update_membership_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_membership] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.update_membership + ] = mock_rpc request = {} client.update_membership(request) @@ -20470,9 +20473,9 @@ def test_delete_membership_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_membership] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_membership + ] = mock_rpc request = {} client.delete_membership(request) @@ -21267,9 +21270,9 @@ def test_create_custom_emoji_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_custom_emoji] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_custom_emoji + ] = mock_rpc request = {} client.create_custom_emoji(request) @@ -21441,9 +21444,9 @@ def test_get_custom_emoji_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_custom_emoji] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_custom_emoji + ] = mock_rpc request = {} client.get_custom_emoji(request) @@ -21621,9 +21624,9 @@ def test_list_custom_emojis_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_custom_emojis] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_custom_emojis + ] = mock_rpc request = {} client.list_custom_emojis(request) @@ -21722,9 +21725,9 @@ def test_delete_custom_emoji_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_custom_emoji] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_custom_emoji + ] = mock_rpc request = {} client.delete_custom_emoji(request) @@ -21897,9 +21900,9 @@ def test_get_space_read_state_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_space_read_state] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_space_read_state + ] = mock_rpc request = {} client.get_space_read_state(request) @@ -22272,9 +22275,9 @@ def test_get_thread_read_state_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_thread_read_state] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_thread_read_state + ] = mock_rpc request = {} client.get_thread_read_state(request) @@ -22630,9 +22633,9 @@ def test_list_space_events_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_space_events] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_space_events + ] = mock_rpc request = {} client.list_space_events(request) @@ -24096,9 +24099,9 @@ def test_position_section_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.position_section] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.position_section + ] = mock_rpc request = {} client.position_section(request) @@ -24221,9 +24224,9 @@ def test_list_section_items_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_section_items] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_section_items + ] = mock_rpc request = {} client.list_section_items(request) @@ -24477,9 +24480,9 @@ def test_move_section_item_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.move_section_item] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.move_section_item + ] = mock_rpc request = {} client.move_section_item(request) diff --git a/packages/google-auth/system_tests/noxfile.py b/packages/google-auth/system_tests/noxfile.py index 2cc4d122cf02..762eacd6e35c 100644 --- a/packages/google-auth/system_tests/noxfile.py +++ b/packages/google-auth/system_tests/noxfile.py @@ -58,7 +58,11 @@ if CLOUD_SDK_ROOT is not None: CLOUD_SDK_ROOT = pathlib.Path(CLOUD_SDK_ROOT) if not CLOUD_SDK_ROOT.exists() or not CLOUD_SDK_ROOT.is_dir(): - print("{} did not exist! Please set the CLOUD_SDK_ROOT environment variable to a directory that exists".format(CLOUD_SDK_ROOT)) + print( + "{} did not exist! Please set the CLOUD_SDK_ROOT environment variable to a directory that exists".format( + CLOUD_SDK_ROOT + ) + ) exit(1) else: CLOUD_SDK_ROOT = pathlib.Path(tempfile.mkdtemp()) @@ -172,9 +176,13 @@ def default(session, *test_paths): # replace 'session._runner.friendly_name' with # session.name once nox has released a new version # https://github.com/theacodes/nox/pull/386 - sponge_log = f"--junitxml=system_{str(session._runner.friendly_name)}_sponge_log.xml" + sponge_log = ( + f"--junitxml=system_{str(session._runner.friendly_name)}_sponge_log.xml" + ) session.run( - "pytest", sponge_log, *test_paths, + "pytest", + sponge_log, + *test_paths, ) @@ -362,6 +370,7 @@ def downscoping(session): # ASYNC SYSTEM TESTS + @nox.session(python=PYTHON_VERSIONS_ASYNC) def service_account_async(session): session.install(*(TEST_DEPENDENCIES_SYNC + TEST_DEPENDENCIES_ASYNC)) diff --git a/packages/google-cloud-biglake-hive/tests/unit/gapic/biglake_hive_v1beta/test_hive_metastore_service.py b/packages/google-cloud-biglake-hive/tests/unit/gapic/biglake_hive_v1beta/test_hive_metastore_service.py index 90081caf667f..1df79e25de7c 100644 --- a/packages/google-cloud-biglake-hive/tests/unit/gapic/biglake_hive_v1beta/test_hive_metastore_service.py +++ b/packages/google-cloud-biglake-hive/tests/unit/gapic/biglake_hive_v1beta/test_hive_metastore_service.py @@ -1014,9 +1014,10 @@ def test_hive_metastore_service_client_get_mtls_endpoint_and_cert_source(client_ client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -1061,9 +1062,10 @@ def test_hive_metastore_service_client_get_mtls_endpoint_and_cert_source(client_ client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -1099,9 +1101,10 @@ def test_hive_metastore_service_client_get_mtls_endpoint_and_cert_source(client_ "google.auth.transport.mtls.default_client_cert_source", return_value=mock_client_cert_source, ): - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source() - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @@ -1488,9 +1491,9 @@ def test_create_hive_catalog_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_hive_catalog] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_hive_catalog + ] = mock_rpc request = {} client.create_hive_catalog(request) @@ -1852,9 +1855,9 @@ def test_get_hive_catalog_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_hive_catalog] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_hive_catalog + ] = mock_rpc request = {} client.get_hive_catalog(request) @@ -2192,9 +2195,9 @@ def test_list_hive_catalogs_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_hive_catalogs] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_hive_catalogs + ] = mock_rpc request = {} client.list_hive_catalogs(request) @@ -2734,9 +2737,9 @@ def test_update_hive_catalog_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_hive_catalog] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.update_hive_catalog + ] = mock_rpc request = {} client.update_hive_catalog(request) @@ -3087,9 +3090,9 @@ def test_delete_hive_catalog_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_hive_catalog] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_hive_catalog + ] = mock_rpc request = {} client.delete_hive_catalog(request) @@ -3426,9 +3429,9 @@ def test_create_hive_database_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_hive_database] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_hive_database + ] = mock_rpc request = {} client.create_hive_database(request) @@ -3796,9 +3799,9 @@ def test_get_hive_database_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_hive_database] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_hive_database + ] = mock_rpc request = {} client.get_hive_database(request) @@ -4144,9 +4147,9 @@ def test_list_hive_databases_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_hive_databases] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_hive_databases + ] = mock_rpc request = {} client.list_hive_databases(request) @@ -4684,9 +4687,9 @@ def test_update_hive_database_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_hive_database] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.update_hive_database + ] = mock_rpc request = {} client.update_hive_database(request) @@ -5039,9 +5042,9 @@ def test_delete_hive_database_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_hive_database] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_hive_database + ] = mock_rpc request = {} client.delete_hive_database(request) @@ -5378,9 +5381,9 @@ def test_create_hive_table_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_hive_table] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_hive_table + ] = mock_rpc request = {} client.create_hive_table(request) @@ -6072,9 +6075,9 @@ def test_list_hive_tables_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_hive_tables] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_hive_tables + ] = mock_rpc request = {} client.list_hive_tables(request) @@ -6592,9 +6595,9 @@ def test_update_hive_table_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_hive_table] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.update_hive_table + ] = mock_rpc request = {} client.update_hive_table(request) @@ -6943,9 +6946,9 @@ def test_delete_hive_table_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_hive_table] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_hive_table + ] = mock_rpc request = {} client.delete_hive_table(request) @@ -8540,9 +8543,9 @@ def test_create_hive_catalog_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_hive_catalog] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_hive_catalog + ] = mock_rpc request = {} client.create_hive_catalog(request) @@ -8770,9 +8773,9 @@ def test_get_hive_catalog_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_hive_catalog] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_hive_catalog + ] = mock_rpc request = {} client.get_hive_catalog(request) @@ -8951,9 +8954,9 @@ def test_list_hive_catalogs_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_hive_catalogs] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_hive_catalogs + ] = mock_rpc request = {} client.list_hive_catalogs(request) @@ -9210,9 +9213,9 @@ def test_update_hive_catalog_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_hive_catalog] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.update_hive_catalog + ] = mock_rpc request = {} client.update_hive_catalog(request) @@ -9392,9 +9395,9 @@ def test_delete_hive_catalog_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_hive_catalog] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_hive_catalog + ] = mock_rpc request = {} client.delete_hive_catalog(request) @@ -9568,9 +9571,9 @@ def test_create_hive_database_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_hive_database] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_hive_database + ] = mock_rpc request = {} client.create_hive_database(request) @@ -9777,9 +9780,9 @@ def test_get_hive_database_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_hive_database] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_hive_database + ] = mock_rpc request = {} client.get_hive_database(request) @@ -9959,9 +9962,9 @@ def test_list_hive_databases_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_hive_databases] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_hive_databases + ] = mock_rpc request = {} client.list_hive_databases(request) @@ -10219,9 +10222,9 @@ def test_update_hive_database_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_hive_database] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.update_hive_database + ] = mock_rpc request = {} client.update_hive_database(request) @@ -10405,9 +10408,9 @@ def test_delete_hive_database_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_hive_database] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_hive_database + ] = mock_rpc request = {} client.delete_hive_database(request) @@ -10580,9 +10583,9 @@ def test_create_hive_table_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_hive_table] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_hive_table + ] = mock_rpc request = {} client.create_hive_table(request) @@ -10971,9 +10974,9 @@ def test_list_hive_tables_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_hive_tables] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_hive_tables + ] = mock_rpc request = {} client.list_hive_tables(request) @@ -11233,9 +11236,9 @@ def test_update_hive_table_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_hive_table] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.update_hive_table + ] = mock_rpc request = {} client.update_hive_table(request) @@ -11417,9 +11420,9 @@ def test_delete_hive_table_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_hive_table] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_hive_table + ] = mock_rpc request = {} client.delete_hive_table(request) diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/client.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/client.py index bb36f8bac9fb..89a3ffdd2845 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/client.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/client.py @@ -82,11 +82,13 @@ class BinauthzManagementServiceV1ClientMeta(type): objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[BinauthzManagementServiceV1Transport]] + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[BinauthzManagementServiceV1Transport]] _transport_registry["grpc"] = BinauthzManagementServiceV1GrpcTransport - _transport_registry["grpc_asyncio"] = ( - BinauthzManagementServiceV1GrpcAsyncIOTransport - ) + _transport_registry[ + "grpc_asyncio" + ] = BinauthzManagementServiceV1GrpcAsyncIOTransport _transport_registry["rest"] = BinauthzManagementServiceV1RestTransport def get_transport_class( @@ -653,9 +655,11 @@ def __init__( universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( - BinauthzManagementServiceV1Client._read_environment_variables() - ) + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = BinauthzManagementServiceV1Client._read_environment_variables() self._client_cert_source = ( BinauthzManagementServiceV1Client._get_client_cert_source( self._client_options.client_cert_source, self._use_client_cert diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/rest.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/rest.py index 2cb333187d5f..37c6bb892154 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/rest.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/rest.py @@ -572,7 +572,9 @@ def __call__( """ - http_options = _BaseBinauthzManagementServiceV1RestTransport._BaseCreateAttestor._get_http_options() + http_options = ( + _BaseBinauthzManagementServiceV1RestTransport._BaseCreateAttestor._get_http_options() + ) request, metadata = self._interceptor.pre_create_attestor(request, metadata) transcoded_request = _BaseBinauthzManagementServiceV1RestTransport._BaseCreateAttestor._get_transcoded_request( @@ -719,7 +721,9 @@ def __call__( be of type `bytes`. """ - http_options = _BaseBinauthzManagementServiceV1RestTransport._BaseDeleteAttestor._get_http_options() + http_options = ( + _BaseBinauthzManagementServiceV1RestTransport._BaseDeleteAttestor._get_http_options() + ) request, metadata = self._interceptor.pre_delete_attestor(request, metadata) transcoded_request = _BaseBinauthzManagementServiceV1RestTransport._BaseDeleteAttestor._get_transcoded_request( @@ -835,7 +839,9 @@ def __call__( """ - http_options = _BaseBinauthzManagementServiceV1RestTransport._BaseGetAttestor._get_http_options() + http_options = ( + _BaseBinauthzManagementServiceV1RestTransport._BaseGetAttestor._get_http_options() + ) request, metadata = self._interceptor.pre_get_attestor(request, metadata) transcoded_request = _BaseBinauthzManagementServiceV1RestTransport._BaseGetAttestor._get_transcoded_request( @@ -983,7 +989,9 @@ def __call__( """ - http_options = _BaseBinauthzManagementServiceV1RestTransport._BaseGetPolicy._get_http_options() + http_options = ( + _BaseBinauthzManagementServiceV1RestTransport._BaseGetPolicy._get_http_options() + ) request, metadata = self._interceptor.pre_get_policy(request, metadata) transcoded_request = _BaseBinauthzManagementServiceV1RestTransport._BaseGetPolicy._get_transcoded_request( @@ -1131,7 +1139,9 @@ def __call__( """ - http_options = _BaseBinauthzManagementServiceV1RestTransport._BaseListAttestors._get_http_options() + http_options = ( + _BaseBinauthzManagementServiceV1RestTransport._BaseListAttestors._get_http_options() + ) request, metadata = self._interceptor.pre_list_attestors(request, metadata) transcoded_request = _BaseBinauthzManagementServiceV1RestTransport._BaseListAttestors._get_transcoded_request( @@ -1282,7 +1292,9 @@ def __call__( """ - http_options = _BaseBinauthzManagementServiceV1RestTransport._BaseUpdateAttestor._get_http_options() + http_options = ( + _BaseBinauthzManagementServiceV1RestTransport._BaseUpdateAttestor._get_http_options() + ) request, metadata = self._interceptor.pre_update_attestor(request, metadata) transcoded_request = _BaseBinauthzManagementServiceV1RestTransport._BaseUpdateAttestor._get_transcoded_request( @@ -1436,7 +1448,9 @@ def __call__( """ - http_options = _BaseBinauthzManagementServiceV1RestTransport._BaseUpdatePolicy._get_http_options() + http_options = ( + _BaseBinauthzManagementServiceV1RestTransport._BaseUpdatePolicy._get_http_options() + ) request, metadata = self._interceptor.pre_update_policy(request, metadata) transcoded_request = _BaseBinauthzManagementServiceV1RestTransport._BaseUpdatePolicy._get_transcoded_request( diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/client.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/client.py index a91b9b515cb7..253fcb1cd92d 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/client.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/client.py @@ -79,7 +79,9 @@ class SystemPolicyV1ClientMeta(type): objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[SystemPolicyV1Transport]] + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[SystemPolicyV1Transport]] _transport_registry["grpc"] = SystemPolicyV1GrpcTransport _transport_registry["grpc_asyncio"] = SystemPolicyV1GrpcAsyncIOTransport _transport_registry["rest"] = SystemPolicyV1RestTransport @@ -616,9 +618,11 @@ def __init__( universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( - SystemPolicyV1Client._read_environment_variables() - ) + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = SystemPolicyV1Client._read_environment_variables() self._client_cert_source = SystemPolicyV1Client._get_client_cert_source( self._client_options.client_cert_source, self._use_client_cert ) diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/rest.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/rest.py index 7dbed3d73b11..db52e0c2442b 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/rest.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/rest.py @@ -281,7 +281,9 @@ def __call__( """ - http_options = _BaseSystemPolicyV1RestTransport._BaseGetSystemPolicy._get_http_options() + http_options = ( + _BaseSystemPolicyV1RestTransport._BaseGetSystemPolicy._get_http_options() + ) request, metadata = self._interceptor.pre_get_system_policy( request, metadata diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/client.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/client.py index 2c179ffe98de..3b2900fcd13e 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/client.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/client.py @@ -77,7 +77,9 @@ class ValidationHelperV1ClientMeta(type): objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[ValidationHelperV1Transport]] + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[ValidationHelperV1Transport]] _transport_registry["grpc"] = ValidationHelperV1GrpcTransport _transport_registry["grpc_asyncio"] = ValidationHelperV1GrpcAsyncIOTransport _transport_registry["rest"] = ValidationHelperV1RestTransport @@ -603,9 +605,11 @@ def __init__( universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( - ValidationHelperV1Client._read_environment_variables() - ) + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = ValidationHelperV1Client._read_environment_variables() self._client_cert_source = ValidationHelperV1Client._get_client_cert_source( self._client_options.client_cert_source, self._use_client_cert ) diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/grpc.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/grpc.py index bc94664e6278..e500acdab305 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/grpc.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/grpc.py @@ -349,12 +349,12 @@ def validate_attestation_occurrence( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "validate_attestation_occurrence" not in self._stubs: - self._stubs["validate_attestation_occurrence"] = ( - self._logged_channel.unary_unary( - "/google.cloud.binaryauthorization.v1.ValidationHelperV1/ValidateAttestationOccurrence", - request_serializer=service.ValidateAttestationOccurrenceRequest.serialize, - response_deserializer=service.ValidateAttestationOccurrenceResponse.deserialize, - ) + self._stubs[ + "validate_attestation_occurrence" + ] = self._logged_channel.unary_unary( + "/google.cloud.binaryauthorization.v1.ValidationHelperV1/ValidateAttestationOccurrence", + request_serializer=service.ValidateAttestationOccurrenceRequest.serialize, + response_deserializer=service.ValidateAttestationOccurrenceResponse.deserialize, ) return self._stubs["validate_attestation_occurrence"] diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/grpc_asyncio.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/grpc_asyncio.py index 8c873d94b89f..762a4e491fa6 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/grpc_asyncio.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/grpc_asyncio.py @@ -357,12 +357,12 @@ def validate_attestation_occurrence( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "validate_attestation_occurrence" not in self._stubs: - self._stubs["validate_attestation_occurrence"] = ( - self._logged_channel.unary_unary( - "/google.cloud.binaryauthorization.v1.ValidationHelperV1/ValidateAttestationOccurrence", - request_serializer=service.ValidateAttestationOccurrenceRequest.serialize, - response_deserializer=service.ValidateAttestationOccurrenceResponse.deserialize, - ) + self._stubs[ + "validate_attestation_occurrence" + ] = self._logged_channel.unary_unary( + "/google.cloud.binaryauthorization.v1.ValidationHelperV1/ValidateAttestationOccurrence", + request_serializer=service.ValidateAttestationOccurrenceRequest.serialize, + response_deserializer=service.ValidateAttestationOccurrenceResponse.deserialize, ) return self._stubs["validate_attestation_occurrence"] diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/rest.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/rest.py index 77f2f6616f4a..19c59ff6920c 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/rest.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/rest.py @@ -292,7 +292,9 @@ def __call__( """ - http_options = _BaseValidationHelperV1RestTransport._BaseValidateAttestationOccurrence._get_http_options() + http_options = ( + _BaseValidationHelperV1RestTransport._BaseValidateAttestationOccurrence._get_http_options() + ) request, metadata = self._interceptor.pre_validate_attestation_occurrence( request, metadata @@ -361,10 +363,11 @@ def __call__( resp = self._interceptor.post_validate_attestation_occurrence(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = ( - self._interceptor.post_validate_attestation_occurrence_with_metadata( - resp, response_metadata - ) + ( + resp, + _, + ) = self._interceptor.post_validate_attestation_occurrence_with_metadata( + resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/types/resources.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/types/resources.py index 170c74f24d93..daa1eed53f05 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/types/resources.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/types/resources.py @@ -120,12 +120,12 @@ class GlobalPolicyEvaluationMode(proto.Enum): number=7, enum=GlobalPolicyEvaluationMode, ) - admission_whitelist_patterns: MutableSequence["AdmissionWhitelistPattern"] = ( - proto.RepeatedField( - proto.MESSAGE, - number=2, - message="AdmissionWhitelistPattern", - ) + admission_whitelist_patterns: MutableSequence[ + "AdmissionWhitelistPattern" + ] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="AdmissionWhitelistPattern", ) cluster_admission_rules: MutableMapping[str, "AdmissionRule"] = proto.MapField( proto.STRING, @@ -133,29 +133,29 @@ class GlobalPolicyEvaluationMode(proto.Enum): number=3, message="AdmissionRule", ) - kubernetes_namespace_admission_rules: MutableMapping[str, "AdmissionRule"] = ( - proto.MapField( - proto.STRING, - proto.MESSAGE, - number=10, - message="AdmissionRule", - ) + kubernetes_namespace_admission_rules: MutableMapping[ + str, "AdmissionRule" + ] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=10, + message="AdmissionRule", ) - kubernetes_service_account_admission_rules: MutableMapping[str, "AdmissionRule"] = ( - proto.MapField( - proto.STRING, - proto.MESSAGE, - number=8, - message="AdmissionRule", - ) + kubernetes_service_account_admission_rules: MutableMapping[ + str, "AdmissionRule" + ] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=8, + message="AdmissionRule", ) - istio_service_identity_admission_rules: MutableMapping[str, "AdmissionRule"] = ( - proto.MapField( - proto.STRING, - proto.MESSAGE, - number=9, - message="AdmissionRule", - ) + istio_service_identity_admission_rules: MutableMapping[ + str, "AdmissionRule" + ] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=9, + message="AdmissionRule", ) default_admission_rule: "AdmissionRule" = proto.Field( proto.MESSAGE, diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/client.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/client.py index 754e329e30c3..7e14fe956868 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/client.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/client.py @@ -87,11 +87,13 @@ class BinauthzManagementServiceV1Beta1ClientMeta(type): objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[BinauthzManagementServiceV1Beta1Transport]] + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[BinauthzManagementServiceV1Beta1Transport]] _transport_registry["grpc"] = BinauthzManagementServiceV1Beta1GrpcTransport - _transport_registry["grpc_asyncio"] = ( - BinauthzManagementServiceV1Beta1GrpcAsyncIOTransport - ) + _transport_registry[ + "grpc_asyncio" + ] = BinauthzManagementServiceV1Beta1GrpcAsyncIOTransport _transport_registry["rest"] = BinauthzManagementServiceV1Beta1RestTransport def get_transport_class( @@ -660,9 +662,11 @@ def __init__( universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( - BinauthzManagementServiceV1Beta1Client._read_environment_variables() - ) + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = BinauthzManagementServiceV1Beta1Client._read_environment_variables() self._client_cert_source = ( BinauthzManagementServiceV1Beta1Client._get_client_cert_source( self._client_options.client_cert_source, self._use_client_cert diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/rest.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/rest.py index 865f042b4c4a..9e8fbce35d38 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/rest.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/rest.py @@ -574,7 +574,9 @@ def __call__( """ - http_options = _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseCreateAttestor._get_http_options() + http_options = ( + _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseCreateAttestor._get_http_options() + ) request, metadata = self._interceptor.pre_create_attestor(request, metadata) transcoded_request = _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseCreateAttestor._get_transcoded_request( @@ -719,7 +721,9 @@ def __call__( be of type `bytes`. """ - http_options = _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseDeleteAttestor._get_http_options() + http_options = ( + _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseDeleteAttestor._get_http_options() + ) request, metadata = self._interceptor.pre_delete_attestor(request, metadata) transcoded_request = _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseDeleteAttestor._get_transcoded_request( @@ -833,7 +837,9 @@ def __call__( """ - http_options = _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseGetAttestor._get_http_options() + http_options = ( + _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseGetAttestor._get_http_options() + ) request, metadata = self._interceptor.pre_get_attestor(request, metadata) transcoded_request = _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseGetAttestor._get_transcoded_request( @@ -980,7 +986,9 @@ def __call__( """ - http_options = _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseGetPolicy._get_http_options() + http_options = ( + _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseGetPolicy._get_http_options() + ) request, metadata = self._interceptor.pre_get_policy(request, metadata) transcoded_request = _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseGetPolicy._get_transcoded_request( @@ -1128,7 +1136,9 @@ def __call__( """ - http_options = _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseListAttestors._get_http_options() + http_options = ( + _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseListAttestors._get_http_options() + ) request, metadata = self._interceptor.pre_list_attestors(request, metadata) transcoded_request = _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseListAttestors._get_transcoded_request( @@ -1277,7 +1287,9 @@ def __call__( """ - http_options = _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseUpdateAttestor._get_http_options() + http_options = ( + _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseUpdateAttestor._get_http_options() + ) request, metadata = self._interceptor.pre_update_attestor(request, metadata) transcoded_request = _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseUpdateAttestor._get_transcoded_request( @@ -1430,7 +1442,9 @@ def __call__( """ - http_options = _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseUpdatePolicy._get_http_options() + http_options = ( + _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseUpdatePolicy._get_http_options() + ) request, metadata = self._interceptor.pre_update_policy(request, metadata) transcoded_request = _BaseBinauthzManagementServiceV1Beta1RestTransport._BaseUpdatePolicy._get_transcoded_request( diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/client.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/client.py index 675d75235c9b..3f3323337d6c 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/client.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/client.py @@ -79,7 +79,9 @@ class SystemPolicyV1Beta1ClientMeta(type): objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[SystemPolicyV1Beta1Transport]] + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[SystemPolicyV1Beta1Transport]] _transport_registry["grpc"] = SystemPolicyV1Beta1GrpcTransport _transport_registry["grpc_asyncio"] = SystemPolicyV1Beta1GrpcAsyncIOTransport _transport_registry["rest"] = SystemPolicyV1Beta1RestTransport @@ -620,9 +622,11 @@ def __init__( universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( - SystemPolicyV1Beta1Client._read_environment_variables() - ) + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = SystemPolicyV1Beta1Client._read_environment_variables() self._client_cert_source = SystemPolicyV1Beta1Client._get_client_cert_source( self._client_options.client_cert_source, self._use_client_cert ) diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/rest.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/rest.py index 2f790da11dce..aa7f4a138951 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/rest.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/rest.py @@ -283,7 +283,9 @@ def __call__( """ - http_options = _BaseSystemPolicyV1Beta1RestTransport._BaseGetSystemPolicy._get_http_options() + http_options = ( + _BaseSystemPolicyV1Beta1RestTransport._BaseGetSystemPolicy._get_http_options() + ) request, metadata = self._interceptor.pre_get_system_policy( request, metadata diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/types/resources.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/types/resources.py index 5875a8b1e8b1..ff5432f9448d 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/types/resources.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/types/resources.py @@ -118,12 +118,12 @@ class GlobalPolicyEvaluationMode(proto.Enum): number=7, enum=GlobalPolicyEvaluationMode, ) - admission_whitelist_patterns: MutableSequence["AdmissionWhitelistPattern"] = ( - proto.RepeatedField( - proto.MESSAGE, - number=2, - message="AdmissionWhitelistPattern", - ) + admission_whitelist_patterns: MutableSequence[ + "AdmissionWhitelistPattern" + ] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="AdmissionWhitelistPattern", ) cluster_admission_rules: MutableMapping[str, "AdmissionRule"] = proto.MapField( proto.STRING, @@ -131,29 +131,29 @@ class GlobalPolicyEvaluationMode(proto.Enum): number=3, message="AdmissionRule", ) - kubernetes_namespace_admission_rules: MutableMapping[str, "AdmissionRule"] = ( - proto.MapField( - proto.STRING, - proto.MESSAGE, - number=10, - message="AdmissionRule", - ) + kubernetes_namespace_admission_rules: MutableMapping[ + str, "AdmissionRule" + ] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=10, + message="AdmissionRule", ) - kubernetes_service_account_admission_rules: MutableMapping[str, "AdmissionRule"] = ( - proto.MapField( - proto.STRING, - proto.MESSAGE, - number=8, - message="AdmissionRule", - ) + kubernetes_service_account_admission_rules: MutableMapping[ + str, "AdmissionRule" + ] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=8, + message="AdmissionRule", ) - istio_service_identity_admission_rules: MutableMapping[str, "AdmissionRule"] = ( - proto.MapField( - proto.STRING, - proto.MESSAGE, - number=9, - message="AdmissionRule", - ) + istio_service_identity_admission_rules: MutableMapping[ + str, "AdmissionRule" + ] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=9, + message="AdmissionRule", ) default_admission_rule: "AdmissionRule" = proto.Field( proto.MESSAGE, diff --git a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_binauthz_management_service_v1.py b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_binauthz_management_service_v1.py index 450f321c6436..ea97bb7ab5c8 100644 --- a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_binauthz_management_service_v1.py +++ b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_binauthz_management_service_v1.py @@ -1053,9 +1053,10 @@ def test_binauthz_management_service_v1_client_get_mtls_endpoint_and_cert_source client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -1100,9 +1101,10 @@ def test_binauthz_management_service_v1_client_get_mtls_endpoint_and_cert_source client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -1138,9 +1140,10 @@ def test_binauthz_management_service_v1_client_get_mtls_endpoint_and_cert_source "google.auth.transport.mtls.default_client_cert_source", return_value=mock_client_cert_source, ): - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source() - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source diff --git a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_system_policy_v1.py b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_system_policy_v1.py index d87f29b79e3b..06b68d59dcbb 100644 --- a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_system_policy_v1.py +++ b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_system_policy_v1.py @@ -969,9 +969,10 @@ def test_system_policy_v1_client_get_mtls_endpoint_and_cert_source(client_class) client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -1016,9 +1017,10 @@ def test_system_policy_v1_client_get_mtls_endpoint_and_cert_source(client_class) client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -1054,9 +1056,10 @@ def test_system_policy_v1_client_get_mtls_endpoint_and_cert_source(client_class) "google.auth.transport.mtls.default_client_cert_source", return_value=mock_client_cert_source, ): - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source() - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @@ -1424,9 +1427,9 @@ def test_get_system_policy_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_system_policy] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_system_policy + ] = mock_rpc request = {} client.get_system_policy(request) @@ -1698,9 +1701,9 @@ def test_get_system_policy_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_system_policy] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_system_policy + ] = mock_rpc request = {} client.get_system_policy(request) diff --git a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_validation_helper_v1.py b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_validation_helper_v1.py index 9c8a41ce1cf5..99410698c219 100644 --- a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_validation_helper_v1.py +++ b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_validation_helper_v1.py @@ -1001,9 +1001,10 @@ def test_validation_helper_v1_client_get_mtls_endpoint_and_cert_source(client_cl client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -1048,9 +1049,10 @@ def test_validation_helper_v1_client_get_mtls_endpoint_and_cert_source(client_cl client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -1086,9 +1088,10 @@ def test_validation_helper_v1_client_get_mtls_endpoint_and_cert_source(client_cl "google.auth.transport.mtls.default_client_cert_source", return_value=mock_client_cert_source, ): - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source() - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source diff --git a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1beta1/test_binauthz_management_service_v1_beta1.py b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1beta1/test_binauthz_management_service_v1_beta1.py index e0bdc08172d1..784e15f17b6d 100644 --- a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1beta1/test_binauthz_management_service_v1_beta1.py +++ b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1beta1/test_binauthz_management_service_v1_beta1.py @@ -1085,9 +1085,10 @@ def test_binauthz_management_service_v1_beta1_client_get_mtls_endpoint_and_cert_ client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -1132,9 +1133,10 @@ def test_binauthz_management_service_v1_beta1_client_get_mtls_endpoint_and_cert_ client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -1170,9 +1172,10 @@ def test_binauthz_management_service_v1_beta1_client_get_mtls_endpoint_and_cert_ "google.auth.transport.mtls.default_client_cert_source", return_value=mock_client_cert_source, ): - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source() - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source diff --git a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1beta1/test_system_policy_v1_beta1.py b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1beta1/test_system_policy_v1_beta1.py index 1dff1352d34f..b60682c6263e 100644 --- a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1beta1/test_system_policy_v1_beta1.py +++ b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1beta1/test_system_policy_v1_beta1.py @@ -1012,9 +1012,10 @@ def test_system_policy_v1_beta1_client_get_mtls_endpoint_and_cert_source(client_ client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -1059,9 +1060,10 @@ def test_system_policy_v1_beta1_client_get_mtls_endpoint_and_cert_source(client_ client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -1097,9 +1099,10 @@ def test_system_policy_v1_beta1_client_get_mtls_endpoint_and_cert_source(client_ "google.auth.transport.mtls.default_client_cert_source", return_value=mock_client_cert_source, ): - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source() - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @@ -1480,9 +1483,9 @@ def test_get_system_policy_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_system_policy] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_system_policy + ] = mock_rpc request = {} client.get_system_policy(request) @@ -1754,9 +1757,9 @@ def test_get_system_policy_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_system_policy] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_system_policy + ] = mock_rpc request = {} client.get_system_policy(request) diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/async_client.py b/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/async_client.py index 5ce702197067..e3d91e288259 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/async_client.py +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/async_client.py @@ -156,9 +156,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): Returns: DataformAsyncClient: The constructed client. """ - sa_info_func = ( - DataformClient.from_service_account_info.__func__ # type: ignore - ) + sa_info_func = DataformClient.from_service_account_info.__func__ # type: ignore return sa_info_func(DataformAsyncClient, info, *args, **kwargs) @classmethod @@ -175,9 +173,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: DataformAsyncClient: The constructed client. """ - sa_file_func = ( - DataformClient.from_service_account_file.__func__ # type: ignore - ) + sa_file_func = DataformClient.from_service_account_file.__func__ # type: ignore return sa_file_func(DataformAsyncClient, filename, *args, **kwargs) from_service_account_json = from_service_account_file diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/client.py b/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/client.py index e73876f05ce1..7e8a1dcc0e93 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/client.py +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/client.py @@ -920,9 +920,11 @@ def __init__( universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( - DataformClient._read_environment_variables() - ) + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = DataformClient._read_environment_variables() self._client_cert_source = DataformClient._get_client_cert_source( self._client_options.client_cert_source, self._use_client_cert ) diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1/types/dataform.py b/packages/google-cloud-dataform/google/cloud/dataform_v1/types/dataform.py index 739dc3157363..f3f12e0c6a9d 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1/types/dataform.py +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1/types/dataform.py @@ -1484,12 +1484,12 @@ class State(proto.Enum): enum="FetchFileGitStatusesResponse.UncommittedFileChange.State", ) - uncommitted_file_changes: MutableSequence[UncommittedFileChange] = ( - proto.RepeatedField( - proto.MESSAGE, - number=1, - message=UncommittedFileChange, - ) + uncommitted_file_changes: MutableSequence[ + UncommittedFileChange + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=UncommittedFileChange, ) @@ -2280,12 +2280,12 @@ class ScheduledReleaseRecord(proto.Message): proto.STRING, number=7, ) - recent_scheduled_release_records: MutableSequence[ScheduledReleaseRecord] = ( - proto.RepeatedField( - proto.MESSAGE, - number=5, - message=ScheduledReleaseRecord, - ) + recent_scheduled_release_records: MutableSequence[ + ScheduledReleaseRecord + ] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=ScheduledReleaseRecord, ) release_compilation_result: str = proto.Field( proto.STRING, @@ -3702,12 +3702,12 @@ class QueryCompilationResultActionsResponse(proto.Message): def raw_page(self): return self - compilation_result_actions: MutableSequence["CompilationResultAction"] = ( - proto.RepeatedField( - proto.MESSAGE, - number=1, - message="CompilationResultAction", - ) + compilation_result_actions: MutableSequence[ + "CompilationResultAction" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="CompilationResultAction", ) next_page_token: str = proto.Field( proto.STRING, @@ -3830,12 +3830,12 @@ class ScheduledExecutionRecord(proto.Message): proto.STRING, number=7, ) - recent_scheduled_execution_records: MutableSequence[ScheduledExecutionRecord] = ( - proto.RepeatedField( - proto.MESSAGE, - number=5, - message=ScheduledExecutionRecord, - ) + recent_scheduled_execution_records: MutableSequence[ + ScheduledExecutionRecord + ] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=ScheduledExecutionRecord, ) disabled: bool = proto.Field( proto.BOOL, @@ -4805,12 +4805,12 @@ class QueryWorkflowInvocationActionsResponse(proto.Message): def raw_page(self): return self - workflow_invocation_actions: MutableSequence["WorkflowInvocationAction"] = ( - proto.RepeatedField( - proto.MESSAGE, - number=1, - message="WorkflowInvocationAction", - ) + workflow_invocation_actions: MutableSequence[ + "WorkflowInvocationAction" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="WorkflowInvocationAction", ) next_page_token: str = proto.Field( proto.STRING, diff --git a/packages/google-cloud-dataform/tests/unit/gapic/dataform_v1/test_dataform.py b/packages/google-cloud-dataform/tests/unit/gapic/dataform_v1/test_dataform.py index 81e4f50cb6f7..70c721996602 100644 --- a/packages/google-cloud-dataform/tests/unit/gapic/dataform_v1/test_dataform.py +++ b/packages/google-cloud-dataform/tests/unit/gapic/dataform_v1/test_dataform.py @@ -945,9 +945,10 @@ def test_dataform_client_get_mtls_endpoint_and_cert_source(client_class): client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -992,9 +993,10 @@ def test_dataform_client_get_mtls_endpoint_and_cert_source(client_class): client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -1030,9 +1032,10 @@ def test_dataform_client_get_mtls_endpoint_and_cert_source(client_class): "google.auth.transport.mtls.default_client_cert_source", return_value=mock_client_cert_source, ): - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source() - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @@ -1718,9 +1721,9 @@ def test_create_team_folder_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_team_folder] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_team_folder + ] = mock_rpc request = {} client.create_team_folder(request) @@ -2074,9 +2077,9 @@ def test_update_team_folder_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_team_folder] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.update_team_folder + ] = mock_rpc request = {} client.update_team_folder(request) @@ -2425,9 +2428,9 @@ def test_delete_team_folder_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_team_folder] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_team_folder + ] = mock_rpc request = {} client.delete_team_folder(request) @@ -3684,9 +3687,9 @@ def test_search_team_folders_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.search_team_folders] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.search_team_folders + ] = mock_rpc request = {} client.search_team_folders(request) @@ -5487,9 +5490,9 @@ def test_delete_folder_tree_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_folder_tree] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_folder_tree + ] = mock_rpc request = {} client.delete_folder_tree(request) @@ -5853,9 +5856,9 @@ def test_query_folder_contents_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.query_folder_contents] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.query_folder_contents + ] = mock_rpc request = {} client.query_folder_contents(request) @@ -7304,9 +7307,9 @@ def test_list_repositories_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_repositories] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_repositories + ] = mock_rpc request = {} client.list_repositories(request) @@ -8223,9 +8226,9 @@ def test_create_repository_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_repository] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_repository + ] = mock_rpc request = {} client.create_repository(request) @@ -8613,9 +8616,9 @@ def test_update_repository_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_repository] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.update_repository + ] = mock_rpc request = {} client.update_repository(request) @@ -8975,9 +8978,9 @@ def test_delete_repository_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_repository] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_repository + ] = mock_rpc request = {} client.delete_repository(request) @@ -9913,9 +9916,9 @@ def test_read_repository_file_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.read_repository_file] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.read_repository_file + ] = mock_rpc request = {} client.read_repository_file(request) @@ -11365,9 +11368,9 @@ def test_fetch_remote_branches_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.fetch_remote_branches] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.fetch_remote_branches + ] = mock_rpc request = {} client.fetch_remote_branches(request) @@ -12475,9 +12478,9 @@ def test_create_workspace_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_workspace] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_workspace + ] = mock_rpc request = {} client.create_workspace(request) @@ -12818,9 +12821,9 @@ def test_delete_workspace_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_workspace] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_workspace + ] = mock_rpc request = {} client.delete_workspace(request) @@ -13138,9 +13141,9 @@ def test_install_npm_packages_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.install_npm_packages] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.install_npm_packages + ] = mock_rpc request = {} client.install_npm_packages(request) @@ -13386,9 +13389,9 @@ def test_pull_git_commits_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.pull_git_commits] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.pull_git_commits + ] = mock_rpc request = {} client.pull_git_commits(request) @@ -13626,9 +13629,9 @@ def test_push_git_commits_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.push_git_commits] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.push_git_commits + ] = mock_rpc request = {} client.push_git_commits(request) @@ -14131,9 +14134,9 @@ def test_fetch_git_ahead_behind_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.fetch_git_ahead_behind] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.fetch_git_ahead_behind + ] = mock_rpc request = {} client.fetch_git_ahead_behind(request) @@ -16273,9 +16276,9 @@ def test_remove_directory_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.remove_directory] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.remove_directory + ] = mock_rpc request = {} client.remove_directory(request) @@ -17720,9 +17723,9 @@ def test_list_release_configs_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_release_configs] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_release_configs + ] = mock_rpc request = {} client.list_release_configs(request) @@ -18276,9 +18279,9 @@ def test_get_release_config_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_release_config] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_release_config + ] = mock_rpc request = {} client.get_release_config(request) @@ -18645,9 +18648,9 @@ def test_create_release_config_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_release_config] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_release_config + ] = mock_rpc request = {} client.create_release_config(request) @@ -19030,9 +19033,9 @@ def test_update_release_config_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_release_config] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.update_release_config + ] = mock_rpc request = {} client.update_release_config(request) @@ -19394,9 +19397,9 @@ def test_delete_release_config_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_release_config] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_release_config + ] = mock_rpc request = {} client.delete_release_config(request) @@ -20292,9 +20295,9 @@ def test_get_compilation_result_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_compilation_result] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_compilation_result + ] = mock_rpc request = {} client.get_compilation_result(request) @@ -21488,9 +21491,9 @@ def test_list_workflow_configs_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_workflow_configs] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_workflow_configs + ] = mock_rpc request = {} client.list_workflow_configs(request) @@ -22042,9 +22045,9 @@ def test_get_workflow_config_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_workflow_config] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_workflow_config + ] = mock_rpc request = {} client.get_workflow_config(request) @@ -22407,9 +22410,9 @@ def test_create_workflow_config_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_workflow_config] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_workflow_config + ] = mock_rpc request = {} client.create_workflow_config(request) @@ -22788,9 +22791,9 @@ def test_update_workflow_config_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_workflow_config] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.update_workflow_config + ] = mock_rpc request = {} client.update_workflow_config(request) @@ -23150,9 +23153,9 @@ def test_delete_workflow_config_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_workflow_config] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_workflow_config + ] = mock_rpc request = {} client.delete_workflow_config(request) @@ -27090,9 +27093,9 @@ def test_test_iam_permissions_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.test_iam_permissions] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.test_iam_permissions + ] = mock_rpc request = {} client.test_iam_permissions(request) @@ -27478,9 +27481,9 @@ def test_create_team_folder_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_team_folder] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_team_folder + ] = mock_rpc request = {} client.create_team_folder(request) @@ -27671,9 +27674,9 @@ def test_update_team_folder_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_team_folder] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.update_team_folder + ] = mock_rpc request = {} client.update_team_folder(request) @@ -27857,9 +27860,9 @@ def test_delete_team_folder_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_team_folder] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_team_folder + ] = mock_rpc request = {} client.delete_team_folder(request) @@ -28497,9 +28500,9 @@ def test_search_team_folders_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.search_team_folders] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.search_team_folders + ] = mock_rpc request = {} client.search_team_folders(request) @@ -29415,9 +29418,9 @@ def test_delete_folder_tree_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_folder_tree] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_folder_tree + ] = mock_rpc request = {} client.delete_folder_tree(request) @@ -29600,9 +29603,9 @@ def test_query_folder_contents_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.query_folder_contents] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.query_folder_contents + ] = mock_rpc request = {} client.query_folder_contents(request) @@ -30315,9 +30318,9 @@ def test_list_repositories_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_repositories] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_repositories + ] = mock_rpc request = {} client.list_repositories(request) @@ -30755,9 +30758,9 @@ def test_create_repository_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_repository] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_repository + ] = mock_rpc request = {} client.create_repository(request) @@ -30964,9 +30967,9 @@ def test_update_repository_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_repository] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.update_repository + ] = mock_rpc request = {} client.update_repository(request) @@ -31148,9 +31151,9 @@ def test_delete_repository_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_repository] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_repository + ] = mock_rpc request = {} client.delete_repository(request) @@ -31645,9 +31648,9 @@ def test_read_repository_file_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.read_repository_file] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.read_repository_file + ] = mock_rpc request = {} client.read_repository_file(request) @@ -32357,9 +32360,9 @@ def test_fetch_remote_branches_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.fetch_remote_branches] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.fetch_remote_branches + ] = mock_rpc request = {} client.fetch_remote_branches(request) @@ -32919,9 +32922,9 @@ def test_create_workspace_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_workspace] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_workspace + ] = mock_rpc request = {} client.create_workspace(request) @@ -33130,9 +33133,9 @@ def test_delete_workspace_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_workspace] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_workspace + ] = mock_rpc request = {} client.delete_workspace(request) @@ -33309,9 +33312,9 @@ def test_install_npm_packages_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.install_npm_packages] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.install_npm_packages + ] = mock_rpc request = {} client.install_npm_packages(request) @@ -33432,9 +33435,9 @@ def test_pull_git_commits_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.pull_git_commits] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.pull_git_commits + ] = mock_rpc request = {} client.pull_git_commits(request) @@ -33563,9 +33566,9 @@ def test_push_git_commits_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.push_git_commits] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.push_git_commits + ] = mock_rpc request = {} client.push_git_commits(request) @@ -33814,9 +33817,9 @@ def test_fetch_git_ahead_behind_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.fetch_git_ahead_behind] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.fetch_git_ahead_behind + ] = mock_rpc request = {} client.fetch_git_ahead_behind(request) @@ -34881,9 +34884,9 @@ def test_remove_directory_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.remove_directory] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.remove_directory + ] = mock_rpc request = {} client.remove_directory(request) @@ -35710,9 +35713,9 @@ def test_list_release_configs_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_release_configs] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_release_configs + ] = mock_rpc request = {} client.list_release_configs(request) @@ -35974,9 +35977,9 @@ def test_get_release_config_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_release_config] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_release_config + ] = mock_rpc request = {} client.get_release_config(request) @@ -36159,9 +36162,9 @@ def test_create_release_config_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_release_config] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_release_config + ] = mock_rpc request = {} client.create_release_config(request) @@ -36373,9 +36376,9 @@ def test_update_release_config_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_release_config] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.update_release_config + ] = mock_rpc request = {} client.update_release_config(request) @@ -36560,9 +36563,9 @@ def test_delete_release_config_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_release_config] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_release_config + ] = mock_rpc request = {} client.delete_release_config(request) @@ -37009,9 +37012,9 @@ def test_get_compilation_result_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_compilation_result] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_compilation_result + ] = mock_rpc request = {} client.get_compilation_result(request) @@ -37607,9 +37610,9 @@ def test_list_workflow_configs_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_workflow_configs] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_workflow_configs + ] = mock_rpc request = {} client.list_workflow_configs(request) @@ -37871,9 +37874,9 @@ def test_get_workflow_config_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_workflow_config] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_workflow_config + ] = mock_rpc request = {} client.get_workflow_config(request) @@ -38056,9 +38059,9 @@ def test_create_workflow_config_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_workflow_config] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_workflow_config + ] = mock_rpc request = {} client.create_workflow_config(request) @@ -38270,9 +38273,9 @@ def test_update_workflow_config_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_workflow_config] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.update_workflow_config + ] = mock_rpc request = {} client.update_workflow_config(request) @@ -38457,9 +38460,9 @@ def test_delete_workflow_config_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_workflow_config] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_workflow_config + ] = mock_rpc request = {} client.delete_workflow_config(request) @@ -40465,9 +40468,9 @@ def test_test_iam_permissions_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.test_iam_permissions] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.test_iam_permissions + ] = mock_rpc request = {} client.test_iam_permissions(request) diff --git a/packages/google-cloud-dataproc/google/cloud/dataproc_v1/types/clusters.py b/packages/google-cloud-dataproc/google/cloud/dataproc_v1/types/clusters.py index 8aff97ba7039..bbb1a9d9069b 100644 --- a/packages/google-cloud-dataproc/google/cloud/dataproc_v1/types/clusters.py +++ b/packages/google-cloud-dataproc/google/cloud/dataproc_v1/types/clusters.py @@ -367,12 +367,12 @@ class Engine(proto.Enum): number=13, message="SoftwareConfig", ) - initialization_actions: MutableSequence["NodeInitializationAction"] = ( - proto.RepeatedField( - proto.MESSAGE, - number=11, - message="NodeInitializationAction", - ) + initialization_actions: MutableSequence[ + "NodeInitializationAction" + ] = proto.RepeatedField( + proto.MESSAGE, + number=11, + message="NodeInitializationAction", ) encryption_config: "EncryptionConfig" = proto.Field( proto.MESSAGE, @@ -1356,12 +1356,12 @@ class InstanceSelectionResult(proto.Message): number=2, message=InstanceSelection, ) - instance_selection_results: MutableSequence[InstanceSelectionResult] = ( - proto.RepeatedField( - proto.MESSAGE, - number=3, - message=InstanceSelectionResult, - ) + instance_selection_results: MutableSequence[ + InstanceSelectionResult + ] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=InstanceSelectionResult, ) diff --git a/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_cluster_controller.py b/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_cluster_controller.py index 026ebf0a39ed..77e233d594a1 100644 --- a/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_cluster_controller.py +++ b/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_cluster_controller.py @@ -1013,9 +1013,10 @@ def test_cluster_controller_client_get_mtls_endpoint_and_cert_source(client_clas client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -1060,9 +1061,10 @@ def test_cluster_controller_client_get_mtls_endpoint_and_cert_source(client_clas client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -1098,9 +1100,10 @@ def test_cluster_controller_client_get_mtls_endpoint_and_cert_source(client_clas "google.auth.transport.mtls.default_client_cert_source", return_value=mock_client_cert_source, ): - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source() - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @@ -3976,9 +3979,9 @@ def test_diagnose_cluster_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.diagnose_cluster] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.diagnose_cluster + ] = mock_rpc request = {} client.diagnose_cluster(request) @@ -5654,9 +5657,9 @@ def test_diagnose_cluster_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.diagnose_cluster] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.diagnose_cluster + ] = mock_rpc request = {} client.diagnose_cluster(request) diff --git a/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_node_group_controller.py b/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_node_group_controller.py index 1b2ebd91131f..f31f87a479f5 100644 --- a/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_node_group_controller.py +++ b/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_node_group_controller.py @@ -1022,9 +1022,10 @@ def test_node_group_controller_client_get_mtls_endpoint_and_cert_source(client_c client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -1069,9 +1070,10 @@ def test_node_group_controller_client_get_mtls_endpoint_and_cert_source(client_c client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -1107,9 +1109,10 @@ def test_node_group_controller_client_get_mtls_endpoint_and_cert_source(client_c "google.auth.transport.mtls.default_client_cert_source", return_value=mock_client_cert_source, ): - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source() - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @@ -1484,9 +1487,9 @@ def test_create_node_group_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_node_group] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_node_group + ] = mock_rpc request = {} client.create_node_group(request) @@ -1850,9 +1853,9 @@ def test_resize_node_group_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.resize_node_group] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.resize_node_group + ] = mock_rpc request = {} client.resize_node_group(request) @@ -2462,9 +2465,9 @@ def test_create_node_group_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_node_group] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_node_group + ] = mock_rpc request = {} client.create_node_group(request) @@ -2666,9 +2669,9 @@ def test_resize_node_group_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.resize_node_group] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.resize_node_group + ] = mock_rpc request = {} client.resize_node_group(request) diff --git a/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_workflow_template_service.py b/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_workflow_template_service.py index eba33660ce14..6bc04019c3d0 100644 --- a/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_workflow_template_service.py +++ b/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_workflow_template_service.py @@ -1031,9 +1031,10 @@ def test_workflow_template_service_client_get_mtls_endpoint_and_cert_source( client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -1078,9 +1079,10 @@ def test_workflow_template_service_client_get_mtls_endpoint_and_cert_source( client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -1116,9 +1118,10 @@ def test_workflow_template_service_client_get_mtls_endpoint_and_cert_source( "google.auth.transport.mtls.default_client_cert_source", return_value=mock_client_cert_source, ): - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source() - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @@ -1862,9 +1865,9 @@ def test_get_workflow_template_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_workflow_template] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_workflow_template + ] = mock_rpc request = {} client.get_workflow_template(request) @@ -4291,9 +4294,9 @@ def test_get_workflow_template_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_workflow_template] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_workflow_template + ] = mock_rpc request = {} client.get_workflow_template(request) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/conversation.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/conversation.py index 5be10d3de70f..fcbd445a32cc 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/conversation.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/conversation.py @@ -726,13 +726,13 @@ class IngestContextReferencesRequest(proto.Message): proto.STRING, number=1, ) - context_references: MutableMapping[str, "Conversation.ContextReference"] = ( - proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message="Conversation.ContextReference", - ) + context_references: MutableMapping[ + str, "Conversation.ContextReference" + ] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message="Conversation.ContextReference", ) @@ -1114,13 +1114,13 @@ class GenerateStatelessSuggestionRequest(proto.Message): number=3, oneof="generator_resource", ) - context_references: MutableMapping[str, "Conversation.ContextReference"] = ( - proto.MapField( - proto.STRING, - proto.MESSAGE, - number=4, - message="Conversation.ContextReference", - ) + context_references: MutableMapping[ + str, "Conversation.ContextReference" + ] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=4, + message="Conversation.ContextReference", ) conversation_context: gcd_generator.ConversationContext = proto.Field( proto.MESSAGE, diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/session.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/session.py index eb576456d28c..13fa88c2fd6e 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/session.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/session.py @@ -271,12 +271,12 @@ class QueryParameters(proto.Message): proto.BOOL, number=4, ) - session_entity_types: MutableSequence[session_entity_type.SessionEntityType] = ( - proto.RepeatedField( - proto.MESSAGE, - number=5, - message=session_entity_type.SessionEntityType, - ) + session_entity_types: MutableSequence[ + session_entity_type.SessionEntityType + ] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=session_entity_type.SessionEntityType, ) payload: struct_pb2.Struct = proto.Field( proto.MESSAGE, @@ -504,12 +504,12 @@ class QueryResult(proto.Message): proto.STRING, number=6, ) - fulfillment_messages: MutableSequence[gcd_intent.Intent.Message] = ( - proto.RepeatedField( - proto.MESSAGE, - number=7, - message=gcd_intent.Intent.Message, - ) + fulfillment_messages: MutableSequence[ + gcd_intent.Intent.Message + ] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=gcd_intent.Intent.Message, ) webhook_source: str = proto.Field( proto.STRING, @@ -771,19 +771,19 @@ class CloudConversationDebuggingInfo(proto.Message): proto.BOOL, number=5, ) - speech_partial_results_end_times: MutableSequence[duration_pb2.Duration] = ( - proto.RepeatedField( - proto.MESSAGE, - number=6, - message=duration_pb2.Duration, - ) + speech_partial_results_end_times: MutableSequence[ + duration_pb2.Duration + ] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, ) - speech_final_results_end_times: MutableSequence[duration_pb2.Duration] = ( - proto.RepeatedField( - proto.MESSAGE, - number=7, - message=duration_pb2.Duration, - ) + speech_final_results_end_times: MutableSequence[ + duration_pb2.Duration + ] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=duration_pb2.Duration, ) partial_responses: int = proto.Field( proto.INT32, @@ -801,19 +801,19 @@ class CloudConversationDebuggingInfo(proto.Message): proto.BOOL, number=11, ) - dtmf_partial_results_times: MutableSequence[duration_pb2.Duration] = ( - proto.RepeatedField( - proto.MESSAGE, - number=12, - message=duration_pb2.Duration, - ) + dtmf_partial_results_times: MutableSequence[ + duration_pb2.Duration + ] = proto.RepeatedField( + proto.MESSAGE, + number=12, + message=duration_pb2.Duration, ) - dtmf_final_results_times: MutableSequence[duration_pb2.Duration] = ( - proto.RepeatedField( - proto.MESSAGE, - number=13, - message=duration_pb2.Duration, - ) + dtmf_final_results_times: MutableSequence[ + duration_pb2.Duration + ] = proto.RepeatedField( + proto.MESSAGE, + number=13, + message=duration_pb2.Duration, ) single_utterance_end_time_offset: duration_pb2.Duration = proto.Field( proto.MESSAGE, @@ -1054,12 +1054,12 @@ class MessageType(proto.Enum): proto.FLOAT, number=4, ) - speech_word_info: MutableSequence[gcd_audio_config.SpeechWordInfo] = ( - proto.RepeatedField( - proto.MESSAGE, - number=7, - message=gcd_audio_config.SpeechWordInfo, - ) + speech_word_info: MutableSequence[ + gcd_audio_config.SpeechWordInfo + ] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=gcd_audio_config.SpeechWordInfo, ) speech_end_offset: duration_pb2.Duration = proto.Field( proto.MESSAGE, diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/conversation.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/conversation.py index e55fbb023042..6e6256fc9664 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/conversation.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/conversation.py @@ -798,13 +798,13 @@ class IngestContextReferencesRequest(proto.Message): proto.STRING, number=1, ) - context_references: MutableMapping[str, "Conversation.ContextReference"] = ( - proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message="Conversation.ContextReference", - ) + context_references: MutableMapping[ + str, "Conversation.ContextReference" + ] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message="Conversation.ContextReference", ) @@ -1185,13 +1185,13 @@ class GenerateStatelessSuggestionRequest(proto.Message): number=3, oneof="generator_resource", ) - context_references: MutableMapping[str, "Conversation.ContextReference"] = ( - proto.MapField( - proto.STRING, - proto.MESSAGE, - number=4, - message="Conversation.ContextReference", - ) + context_references: MutableMapping[ + str, "Conversation.ContextReference" + ] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=4, + message="Conversation.ContextReference", ) conversation_context: gcd_generator.ConversationContext = proto.Field( proto.MESSAGE, diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/session.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/session.py index f70d908473bd..c95f74cd4b0b 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/session.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/session.py @@ -303,12 +303,12 @@ class QueryParameters(proto.Message): proto.BOOL, number=4, ) - session_entity_types: MutableSequence[session_entity_type.SessionEntityType] = ( - proto.RepeatedField( - proto.MESSAGE, - number=5, - message=session_entity_type.SessionEntityType, - ) + session_entity_types: MutableSequence[ + session_entity_type.SessionEntityType + ] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=session_entity_type.SessionEntityType, ) payload: struct_pb2.Struct = proto.Field( proto.MESSAGE, @@ -559,12 +559,12 @@ class QueryResult(proto.Message): proto.STRING, number=6, ) - fulfillment_messages: MutableSequence[gcd_intent.Intent.Message] = ( - proto.RepeatedField( - proto.MESSAGE, - number=7, - message=gcd_intent.Intent.Message, - ) + fulfillment_messages: MutableSequence[ + gcd_intent.Intent.Message + ] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=gcd_intent.Intent.Message, ) webhook_source: str = proto.Field( proto.STRING, @@ -931,19 +931,19 @@ class CloudConversationDebuggingInfo(proto.Message): proto.BOOL, number=5, ) - speech_partial_results_end_times: MutableSequence[duration_pb2.Duration] = ( - proto.RepeatedField( - proto.MESSAGE, - number=6, - message=duration_pb2.Duration, - ) + speech_partial_results_end_times: MutableSequence[ + duration_pb2.Duration + ] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, ) - speech_final_results_end_times: MutableSequence[duration_pb2.Duration] = ( - proto.RepeatedField( - proto.MESSAGE, - number=7, - message=duration_pb2.Duration, - ) + speech_final_results_end_times: MutableSequence[ + duration_pb2.Duration + ] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=duration_pb2.Duration, ) partial_responses: int = proto.Field( proto.INT32, @@ -961,19 +961,19 @@ class CloudConversationDebuggingInfo(proto.Message): proto.BOOL, number=11, ) - dtmf_partial_results_times: MutableSequence[duration_pb2.Duration] = ( - proto.RepeatedField( - proto.MESSAGE, - number=12, - message=duration_pb2.Duration, - ) + dtmf_partial_results_times: MutableSequence[ + duration_pb2.Duration + ] = proto.RepeatedField( + proto.MESSAGE, + number=12, + message=duration_pb2.Duration, ) - dtmf_final_results_times: MutableSequence[duration_pb2.Duration] = ( - proto.RepeatedField( - proto.MESSAGE, - number=13, - message=duration_pb2.Duration, - ) + dtmf_final_results_times: MutableSequence[ + duration_pb2.Duration + ] = proto.RepeatedField( + proto.MESSAGE, + number=13, + message=duration_pb2.Duration, ) single_utterance_end_time_offset: duration_pb2.Duration = proto.Field( proto.MESSAGE, @@ -1261,12 +1261,12 @@ class MessageType(proto.Enum): proto.FLOAT, number=6, ) - speech_word_info: MutableSequence[gcd_audio_config.SpeechWordInfo] = ( - proto.RepeatedField( - proto.MESSAGE, - number=7, - message=gcd_audio_config.SpeechWordInfo, - ) + speech_word_info: MutableSequence[ + gcd_audio_config.SpeechWordInfo + ] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=gcd_audio_config.SpeechWordInfo, ) speech_end_offset: duration_pb2.Duration = proto.Field( proto.MESSAGE, diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py index 61224eacb11a..f26f891c36b5 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py @@ -92,7 +92,9 @@ class KeyManagementServiceClientMeta(type): objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[KeyManagementServiceTransport]] + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[KeyManagementServiceTransport]] _transport_registry["grpc"] = KeyManagementServiceGrpcTransport _transport_registry["grpc_asyncio"] = KeyManagementServiceGrpcAsyncIOTransport _transport_registry["rest"] = KeyManagementServiceRestTransport @@ -774,9 +776,11 @@ def __init__( universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( - KeyManagementServiceClient._read_environment_variables() - ) + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = KeyManagementServiceClient._read_environment_variables() self._client_cert_source = KeyManagementServiceClient._get_client_cert_source( self._client_options.client_cert_source, self._use_client_cert ) diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/types/service.py b/packages/google-cloud-kms/google/cloud/kms_v1/types/service.py index 9665096ac2ac..2ad0745754a4 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/types/service.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/types/service.py @@ -458,12 +458,12 @@ class ListCryptoKeyVersionsResponse(proto.Message): def raw_page(self): return self - crypto_key_versions: MutableSequence[resources.CryptoKeyVersion] = ( - proto.RepeatedField( - proto.MESSAGE, - number=1, - message=resources.CryptoKeyVersion, - ) + crypto_key_versions: MutableSequence[ + resources.CryptoKeyVersion + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.CryptoKeyVersion, ) next_page_token: str = proto.Field( proto.STRING, diff --git a/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_key_management_service.py b/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_key_management_service.py index 4d20ac04502b..fb96bedfc739 100644 --- a/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_key_management_service.py +++ b/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_key_management_service.py @@ -1028,9 +1028,10 @@ def test_key_management_service_client_get_mtls_endpoint_and_cert_source(client_ client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -1075,9 +1076,10 @@ def test_key_management_service_client_get_mtls_endpoint_and_cert_source(client_ client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -1113,9 +1115,10 @@ def test_key_management_service_client_get_mtls_endpoint_and_cert_source(client_ "google.auth.transport.mtls.default_client_cert_source", return_value=mock_client_cert_source, ): - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source() - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @@ -2020,9 +2023,9 @@ def test_list_crypto_keys_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_crypto_keys] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_crypto_keys + ] = mock_rpc request = {} client.list_crypto_keys(request) @@ -3101,9 +3104,9 @@ def test_list_import_jobs_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_import_jobs] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_import_jobs + ] = mock_rpc request = {} client.list_import_jobs(request) @@ -3630,9 +3633,9 @@ def test_list_retired_resources_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_retired_resources] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_retired_resources + ] = mock_rpc request = {} client.list_retired_resources(request) @@ -4852,9 +4855,9 @@ def test_get_crypto_key_version_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_crypto_key_version] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_crypto_key_version + ] = mock_rpc request = {} client.get_crypto_key_version(request) @@ -5909,9 +5912,9 @@ def test_get_retired_resource_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_retired_resource] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_retired_resource + ] = mock_rpc request = {} client.get_retired_resource(request) @@ -6605,9 +6608,9 @@ def test_create_crypto_key_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_crypto_key] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_crypto_key + ] = mock_rpc request = {} client.create_crypto_key(request) @@ -7369,9 +7372,9 @@ def test_delete_crypto_key_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_crypto_key] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_crypto_key + ] = mock_rpc request = {} client.delete_crypto_key(request) @@ -8391,9 +8394,9 @@ def test_create_import_job_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_import_job] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_import_job + ] = mock_rpc request = {} client.create_import_job(request) @@ -8760,9 +8763,9 @@ def test_update_crypto_key_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_crypto_key] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.update_crypto_key + ] = mock_rpc request = {} client.update_crypto_key(request) @@ -12240,9 +12243,9 @@ def test_asymmetric_decrypt_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.asymmetric_decrypt] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.asymmetric_decrypt + ] = mock_rpc request = {} client.asymmetric_decrypt(request) @@ -13561,9 +13564,9 @@ def test_generate_random_bytes_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.generate_random_bytes] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.generate_random_bytes + ] = mock_rpc request = {} client.generate_random_bytes(request) @@ -14109,9 +14112,9 @@ def test_list_crypto_keys_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_crypto_keys] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_crypto_keys + ] = mock_rpc request = {} client.list_crypto_keys(request) @@ -14646,9 +14649,9 @@ def test_list_import_jobs_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_import_jobs] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_import_jobs + ] = mock_rpc request = {} client.list_import_jobs(request) @@ -14913,9 +14916,9 @@ def test_list_retired_resources_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_retired_resources] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_retired_resources + ] = mock_rpc request = {} client.list_retired_resources(request) @@ -15527,9 +15530,9 @@ def test_get_crypto_key_version_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_crypto_key_version] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_crypto_key_version + ] = mock_rpc request = {} client.get_crypto_key_version(request) @@ -16069,9 +16072,9 @@ def test_get_retired_resource_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_retired_resource] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_retired_resource + ] = mock_rpc request = {} client.get_retired_resource(request) @@ -16457,9 +16460,9 @@ def test_create_crypto_key_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_crypto_key] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_crypto_key + ] = mock_rpc request = {} client.create_crypto_key(request) @@ -16874,9 +16877,9 @@ def test_delete_crypto_key_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_crypto_key] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_crypto_key + ] = mock_rpc request = {} client.delete_crypto_key(request) @@ -17378,9 +17381,9 @@ def test_create_import_job_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_import_job] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_import_job + ] = mock_rpc request = {} client.create_import_job(request) @@ -17589,9 +17592,9 @@ def test_update_crypto_key_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_crypto_key] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.update_crypto_key + ] = mock_rpc request = {} client.update_crypto_key(request) @@ -19390,9 +19393,9 @@ def test_asymmetric_decrypt_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.asymmetric_decrypt] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.asymmetric_decrypt + ] = mock_rpc request = {} client.asymmetric_decrypt(request) @@ -20114,9 +20117,9 @@ def test_generate_random_bytes_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.generate_random_bytes] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.generate_random_bytes + ] = mock_rpc request = {} client.generate_random_bytes(request) diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/client.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/client.py index 7c2b01c91f6f..582e0f5054ed 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/client.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/client.py @@ -853,9 +853,11 @@ def __init__( universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( - MemorystoreClient._read_environment_variables() - ) + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = MemorystoreClient._read_environment_variables() self._client_cert_source = MemorystoreClient._get_client_cert_source( self._client_options.client_cert_source, self._use_client_cert ) diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/base.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/base.py index f12d13ed397d..57ae5f199744 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/base.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/base.py @@ -465,19 +465,13 @@ def get_operation( @property def cancel_operation( self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: raise NotImplementedError() @property def delete_operation( self, - ) -> Callable[ - [operations_pb2.DeleteOperationRequest], - None, - ]: + ) -> Callable[[operations_pb2.DeleteOperationRequest], None,]: raise NotImplementedError() @property diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/grpc.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/grpc.py index 67118babd9be..eb018c6d8c36 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/grpc.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/grpc.py @@ -530,12 +530,12 @@ def get_shared_regional_certificate_authority( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_shared_regional_certificate_authority" not in self._stubs: - self._stubs["get_shared_regional_certificate_authority"] = ( - self._logged_channel.unary_unary( - "/google.cloud.memorystore.v1.Memorystore/GetSharedRegionalCertificateAuthority", - request_serializer=memorystore.GetSharedRegionalCertificateAuthorityRequest.serialize, - response_deserializer=memorystore.SharedRegionalCertificateAuthority.deserialize, - ) + self._stubs[ + "get_shared_regional_certificate_authority" + ] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1.Memorystore/GetSharedRegionalCertificateAuthority", + request_serializer=memorystore.GetSharedRegionalCertificateAuthorityRequest.serialize, + response_deserializer=memorystore.SharedRegionalCertificateAuthority.deserialize, ) return self._stubs["get_shared_regional_certificate_authority"] diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/grpc_asyncio.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/grpc_asyncio.py index d4ecd7dc2f10..cdd05b769518 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/grpc_asyncio.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/grpc_asyncio.py @@ -545,12 +545,12 @@ def get_shared_regional_certificate_authority( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_shared_regional_certificate_authority" not in self._stubs: - self._stubs["get_shared_regional_certificate_authority"] = ( - self._logged_channel.unary_unary( - "/google.cloud.memorystore.v1.Memorystore/GetSharedRegionalCertificateAuthority", - request_serializer=memorystore.GetSharedRegionalCertificateAuthorityRequest.serialize, - response_deserializer=memorystore.SharedRegionalCertificateAuthority.deserialize, - ) + self._stubs[ + "get_shared_regional_certificate_authority" + ] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1.Memorystore/GetSharedRegionalCertificateAuthority", + request_serializer=memorystore.GetSharedRegionalCertificateAuthorityRequest.serialize, + response_deserializer=memorystore.SharedRegionalCertificateAuthority.deserialize, ) return self._stubs["get_shared_regional_certificate_authority"] diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/rest.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/rest.py index 1ae3eaaa9717..6f1de1bec574 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/rest.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/transports/rest.py @@ -2172,7 +2172,9 @@ def __call__( BackupCollection of an instance. """ - http_options = _BaseMemorystoreRestTransport._BaseGetBackupCollection._get_http_options() + http_options = ( + _BaseMemorystoreRestTransport._BaseGetBackupCollection._get_http_options() + ) request, metadata = self._interceptor.pre_get_backup_collection( request, metadata @@ -2318,7 +2320,9 @@ def __call__( """ - http_options = _BaseMemorystoreRestTransport._BaseGetCertificateAuthority._get_http_options() + http_options = ( + _BaseMemorystoreRestTransport._BaseGetCertificateAuthority._get_http_options() + ) request, metadata = self._interceptor.pre_get_certificate_authority( request, metadata @@ -2619,12 +2623,15 @@ def __call__( """ - http_options = _BaseMemorystoreRestTransport._BaseGetSharedRegionalCertificateAuthority._get_http_options() + http_options = ( + _BaseMemorystoreRestTransport._BaseGetSharedRegionalCertificateAuthority._get_http_options() + ) - request, metadata = ( - self._interceptor.pre_get_shared_regional_certificate_authority( - request, metadata - ) + ( + request, + metadata, + ) = self._interceptor.pre_get_shared_regional_certificate_authority( + request, metadata ) transcoded_request = _BaseMemorystoreRestTransport._BaseGetSharedRegionalCertificateAuthority._get_transcoded_request( http_options, request @@ -2687,10 +2694,11 @@ def __call__( resp ) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = ( - self._interceptor.post_get_shared_regional_certificate_authority_with_metadata( - resp, response_metadata - ) + ( + resp, + _, + ) = self._interceptor.post_get_shared_regional_certificate_authority_with_metadata( + resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG @@ -2771,7 +2779,9 @@ def __call__( Response for [ListBackupCollections]. """ - http_options = _BaseMemorystoreRestTransport._BaseListBackupCollections._get_http_options() + http_options = ( + _BaseMemorystoreRestTransport._BaseListBackupCollections._get_http_options() + ) request, metadata = self._interceptor.pre_list_backup_collections( request, metadata @@ -3218,7 +3228,9 @@ def __call__( """ - http_options = _BaseMemorystoreRestTransport._BaseRescheduleMaintenance._get_http_options() + http_options = ( + _BaseMemorystoreRestTransport._BaseRescheduleMaintenance._get_http_options() + ) request, metadata = self._interceptor.pre_reschedule_maintenance( request, metadata diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/types/memorystore.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/types/memorystore.py index f17458a7cdc7..0420f5d0d978 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/types/memorystore.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/types/memorystore.py @@ -720,12 +720,12 @@ class ConnectionDetail(proto.Message): number=20, message="PscAutoConnection", ) - psc_attachment_details: MutableSequence["PscAttachmentDetail"] = ( - proto.RepeatedField( - proto.MESSAGE, - number=21, - message="PscAttachmentDetail", - ) + psc_attachment_details: MutableSequence[ + "PscAttachmentDetail" + ] = proto.RepeatedField( + proto.MESSAGE, + number=21, + message="PscAttachmentDetail", ) endpoints: MutableSequence[InstanceEndpoint] = proto.RepeatedField( proto.MESSAGE, @@ -1339,12 +1339,12 @@ class MaintenancePolicy(proto.Message): number=2, message=timestamp_pb2.Timestamp, ) - weekly_maintenance_window: MutableSequence["WeeklyMaintenanceWindow"] = ( - proto.RepeatedField( - proto.MESSAGE, - number=3, - message="WeeklyMaintenanceWindow", - ) + weekly_maintenance_window: MutableSequence[ + "WeeklyMaintenanceWindow" + ] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="WeeklyMaintenanceWindow", ) diff --git a/packages/google-cloud-memorystore/tests/unit/gapic/memorystore_v1/test_memorystore.py b/packages/google-cloud-memorystore/tests/unit/gapic/memorystore_v1/test_memorystore.py index dbd31326d61e..6e3b147cd9ca 100644 --- a/packages/google-cloud-memorystore/tests/unit/gapic/memorystore_v1/test_memorystore.py +++ b/packages/google-cloud-memorystore/tests/unit/gapic/memorystore_v1/test_memorystore.py @@ -953,9 +953,10 @@ def test_memorystore_client_get_mtls_endpoint_and_cert_source(client_class): client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -1000,9 +1001,10 @@ def test_memorystore_client_get_mtls_endpoint_and_cert_source(client_class): client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -1038,9 +1040,10 @@ def test_memorystore_client_get_mtls_endpoint_and_cert_source(client_class): "google.auth.transport.mtls.default_client_cert_source", return_value=mock_client_cert_source, ): - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source() - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @@ -4085,9 +4088,9 @@ def test_reschedule_maintenance_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.reschedule_maintenance] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.reschedule_maintenance + ] = mock_rpc request = {} client.reschedule_maintenance(request) @@ -5018,9 +5021,9 @@ def test_get_backup_collection_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_backup_collection] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_backup_collection + ] = mock_rpc request = {} client.get_backup_collection(request) @@ -8501,9 +8504,9 @@ def test_reschedule_maintenance_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.reschedule_maintenance] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.reschedule_maintenance + ] = mock_rpc request = {} client.reschedule_maintenance(request) @@ -8959,9 +8962,9 @@ def test_get_backup_collection_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_backup_collection] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_backup_collection + ] = mock_rpc request = {} client.get_backup_collection(request) diff --git a/packages/google-cloud-modelarmor/google/cloud/modelarmor_v1/types/service.py b/packages/google-cloud-modelarmor/google/cloud/modelarmor_v1/types/service.py index 7187ce979be8..c24be098ba37 100644 --- a/packages/google-cloud-modelarmor/google/cloud/modelarmor_v1/types/service.py +++ b/packages/google-cloud-modelarmor/google/cloud/modelarmor_v1/types/service.py @@ -1880,12 +1880,12 @@ class MaliciousUriMatchedItem(proto.Message): number=3, enum="FilterMatchState", ) - malicious_uri_matched_items: MutableSequence[MaliciousUriMatchedItem] = ( - proto.RepeatedField( - proto.MESSAGE, - number=4, - message=MaliciousUriMatchedItem, - ) + malicious_uri_matched_items: MutableSequence[ + MaliciousUriMatchedItem + ] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=MaliciousUriMatchedItem, ) diff --git a/packages/google-cloud-modelarmor/tests/unit/gapic/modelarmor_v1/test_model_armor.py b/packages/google-cloud-modelarmor/tests/unit/gapic/modelarmor_v1/test_model_armor.py index 871aa451e671..d01bb9c96c10 100644 --- a/packages/google-cloud-modelarmor/tests/unit/gapic/modelarmor_v1/test_model_armor.py +++ b/packages/google-cloud-modelarmor/tests/unit/gapic/modelarmor_v1/test_model_armor.py @@ -940,9 +940,10 @@ def test_model_armor_client_get_mtls_endpoint_and_cert_source(client_class): client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -987,9 +988,10 @@ def test_model_armor_client_get_mtls_endpoint_and_cert_source(client_class): client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -1025,9 +1027,10 @@ def test_model_armor_client_get_mtls_endpoint_and_cert_source(client_class): "google.auth.transport.mtls.default_client_cert_source", return_value=mock_client_cert_source, ): - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source() - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @@ -3204,9 +3207,9 @@ def test_get_floor_setting_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_floor_setting] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_floor_setting + ] = mock_rpc request = {} client.get_floor_setting(request) @@ -3556,9 +3559,9 @@ def test_update_floor_setting_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_floor_setting] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.update_floor_setting + ] = mock_rpc request = {} client.update_floor_setting(request) @@ -3915,9 +3918,9 @@ def test_sanitize_user_prompt_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.sanitize_user_prompt] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.sanitize_user_prompt + ] = mock_rpc request = {} client.sanitize_user_prompt(request) @@ -5696,9 +5699,9 @@ def test_get_floor_setting_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_floor_setting] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_floor_setting + ] = mock_rpc request = {} client.get_floor_setting(request) @@ -5877,9 +5880,9 @@ def test_update_floor_setting_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_floor_setting] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.update_floor_setting + ] = mock_rpc request = {} client.update_floor_setting(request) @@ -6061,9 +6064,9 @@ def test_sanitize_user_prompt_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.sanitize_user_prompt] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.sanitize_user_prompt + ] = mock_rpc request = {} client.sanitize_user_prompt(request) diff --git a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/client.py b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/client.py index 8db9de78a079..7c62cf0357cd 100644 --- a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/client.py +++ b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/client.py @@ -92,7 +92,9 @@ class SecureSourceManagerClientMeta(type): objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[SecureSourceManagerTransport]] + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[SecureSourceManagerTransport]] _transport_registry["grpc"] = SecureSourceManagerGrpcTransport _transport_registry["grpc_asyncio"] = SecureSourceManagerGrpcAsyncIOTransport _transport_registry["rest"] = SecureSourceManagerRestTransport @@ -884,9 +886,11 @@ def __init__( universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( - SecureSourceManagerClient._read_environment_variables() - ) + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = SecureSourceManagerClient._read_environment_variables() self._client_cert_source = SecureSourceManagerClient._get_client_cert_source( self._client_options.client_cert_source, self._use_client_cert ) diff --git a/packages/google-cloud-securesourcemanager/tests/unit/gapic/securesourcemanager_v1/test_secure_source_manager.py b/packages/google-cloud-securesourcemanager/tests/unit/gapic/securesourcemanager_v1/test_secure_source_manager.py index 3faca52052c5..c519608ef8a6 100644 --- a/packages/google-cloud-securesourcemanager/tests/unit/gapic/securesourcemanager_v1/test_secure_source_manager.py +++ b/packages/google-cloud-securesourcemanager/tests/unit/gapic/securesourcemanager_v1/test_secure_source_manager.py @@ -1030,9 +1030,10 @@ def test_secure_source_manager_client_get_mtls_endpoint_and_cert_source(client_c client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -1077,9 +1078,10 @@ def test_secure_source_manager_client_get_mtls_endpoint_and_cert_source(client_c client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint, ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is expected_cert_source @@ -1115,9 +1117,10 @@ def test_secure_source_manager_client_get_mtls_endpoint_and_cert_source(client_c "google.auth.transport.mtls.default_client_cert_source", return_value=mock_client_cert_source, ): - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source() - ) + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @@ -3041,9 +3044,9 @@ def test_list_repositories_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_repositories] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_repositories + ] = mock_rpc request = {} client.list_repositories(request) @@ -3918,9 +3921,9 @@ def test_create_repository_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_repository] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_repository + ] = mock_rpc request = {} client.create_repository(request) @@ -4278,9 +4281,9 @@ def test_update_repository_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_repository] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.update_repository + ] = mock_rpc request = {} client.update_repository(request) @@ -4632,9 +4635,9 @@ def test_delete_repository_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_repository] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_repository + ] = mock_rpc request = {} client.delete_repository(request) @@ -6851,9 +6854,9 @@ def test_get_iam_policy_repo_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_iam_policy_repo] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_iam_policy_repo + ] = mock_rpc request = {} client.get_iam_policy_repo(request) @@ -7212,9 +7215,9 @@ def test_set_iam_policy_repo_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.set_iam_policy_repo] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.set_iam_policy_repo + ] = mock_rpc request = {} client.set_iam_policy_repo(request) @@ -7935,9 +7938,9 @@ def test_create_branch_rule_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_branch_rule] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_branch_rule + ] = mock_rpc request = {} client.create_branch_rule(request) @@ -8304,9 +8307,9 @@ def test_list_branch_rules_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_branch_rules] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_branch_rules + ] = mock_rpc request = {} client.list_branch_rules(request) @@ -9205,9 +9208,9 @@ def test_update_branch_rule_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_branch_rule] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.update_branch_rule + ] = mock_rpc request = {} client.update_branch_rule(request) @@ -9561,9 +9564,9 @@ def test_delete_branch_rule_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_branch_rule] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_branch_rule + ] = mock_rpc request = {} client.delete_branch_rule(request) @@ -9907,9 +9910,9 @@ def test_create_pull_request_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_pull_request] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_pull_request + ] = mock_rpc request = {} client.create_pull_request(request) @@ -10266,9 +10269,9 @@ def test_get_pull_request_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_pull_request] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_pull_request + ] = mock_rpc request = {} client.get_pull_request(request) @@ -10606,9 +10609,9 @@ def test_list_pull_requests_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_pull_requests] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_pull_requests + ] = mock_rpc request = {} client.list_pull_requests(request) @@ -11139,9 +11142,9 @@ def test_update_pull_request_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_pull_request] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.update_pull_request + ] = mock_rpc request = {} client.update_pull_request(request) @@ -11495,9 +11498,9 @@ def test_merge_pull_request_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.merge_pull_request] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.merge_pull_request + ] = mock_rpc request = {} client.merge_pull_request(request) @@ -11839,9 +11842,9 @@ def test_open_pull_request_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.open_pull_request] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.open_pull_request + ] = mock_rpc request = {} client.open_pull_request(request) @@ -12185,9 +12188,9 @@ def test_close_pull_request_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.close_pull_request] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.close_pull_request + ] = mock_rpc request = {} client.close_pull_request(request) @@ -19348,9 +19351,9 @@ def test_create_issue_comment_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_issue_comment] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_issue_comment + ] = mock_rpc request = {} client.create_issue_comment(request) @@ -19709,9 +19712,9 @@ def test_get_issue_comment_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_issue_comment] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_issue_comment + ] = mock_rpc request = {} client.get_issue_comment(request) @@ -20055,9 +20058,9 @@ def test_list_issue_comments_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_issue_comments] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_issue_comments + ] = mock_rpc request = {} client.list_issue_comments(request) @@ -20588,9 +20591,9 @@ def test_update_issue_comment_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_issue_comment] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.update_issue_comment + ] = mock_rpc request = {} client.update_issue_comment(request) @@ -20946,9 +20949,9 @@ def test_delete_issue_comment_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_issue_comment] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_issue_comment + ] = mock_rpc request = {} client.delete_issue_comment(request) @@ -22072,9 +22075,9 @@ def test_list_repositories_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_repositories] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_repositories + ] = mock_rpc request = {} client.list_repositories(request) @@ -22516,9 +22519,9 @@ def test_create_repository_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_repository] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_repository + ] = mock_rpc request = {} client.create_repository(request) @@ -22724,9 +22727,9 @@ def test_update_repository_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_repository] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.update_repository + ] = mock_rpc request = {} client.update_repository(request) @@ -22920,9 +22923,9 @@ def test_delete_repository_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_repository] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_repository + ] = mock_rpc request = {} client.delete_repository(request) @@ -24113,9 +24116,9 @@ def test_get_iam_policy_repo_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_iam_policy_repo] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_iam_policy_repo + ] = mock_rpc request = {} client.get_iam_policy_repo(request) @@ -24295,9 +24298,9 @@ def test_set_iam_policy_repo_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.set_iam_policy_repo] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.set_iam_policy_repo + ] = mock_rpc request = {} client.set_iam_policy_repo(request) @@ -24678,9 +24681,9 @@ def test_create_branch_rule_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_branch_rule] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_branch_rule + ] = mock_rpc request = {} client.create_branch_rule(request) @@ -24888,9 +24891,9 @@ def test_list_branch_rules_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_branch_rules] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_branch_rules + ] = mock_rpc request = {} client.list_branch_rules(request) @@ -25334,9 +25337,9 @@ def test_update_branch_rule_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_branch_rule] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.update_branch_rule + ] = mock_rpc request = {} client.update_branch_rule(request) @@ -25532,9 +25535,9 @@ def test_delete_branch_rule_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_branch_rule] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_branch_rule + ] = mock_rpc request = {} client.delete_branch_rule(request) @@ -25717,9 +25720,9 @@ def test_create_pull_request_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_pull_request] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_pull_request + ] = mock_rpc request = {} client.create_pull_request(request) @@ -25909,9 +25912,9 @@ def test_get_pull_request_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_pull_request] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_pull_request + ] = mock_rpc request = {} client.get_pull_request(request) @@ -26093,9 +26096,9 @@ def test_list_pull_requests_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_pull_requests] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_pull_requests + ] = mock_rpc request = {} client.list_pull_requests(request) @@ -26359,9 +26362,9 @@ def test_update_pull_request_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_pull_request] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.update_pull_request + ] = mock_rpc request = {} client.update_pull_request(request) @@ -26544,9 +26547,9 @@ def test_merge_pull_request_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.merge_pull_request] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.merge_pull_request + ] = mock_rpc request = {} client.merge_pull_request(request) @@ -26726,9 +26729,9 @@ def test_open_pull_request_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.open_pull_request] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.open_pull_request + ] = mock_rpc request = {} client.open_pull_request(request) @@ -26910,9 +26913,9 @@ def test_close_pull_request_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.close_pull_request] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.close_pull_request + ] = mock_rpc request = {} client.close_pull_request(request) @@ -30704,9 +30707,9 @@ def test_create_issue_comment_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_issue_comment] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_issue_comment + ] = mock_rpc request = {} client.create_issue_comment(request) @@ -30896,9 +30899,9 @@ def test_get_issue_comment_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_issue_comment] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_issue_comment + ] = mock_rpc request = {} client.get_issue_comment(request) @@ -31080,9 +31083,9 @@ def test_list_issue_comments_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_issue_comments] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_issue_comments + ] = mock_rpc request = {} client.list_issue_comments(request) @@ -31346,9 +31349,9 @@ def test_update_issue_comment_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_issue_comment] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.update_issue_comment + ] = mock_rpc request = {} client.update_issue_comment(request) @@ -31531,9 +31534,9 @@ def test_delete_issue_comment_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_issue_comment] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_issue_comment + ] = mock_rpc request = {} client.delete_issue_comment(request) diff --git a/packages/google-cloud-support/google/cloud/support_v2/types/case_service.py b/packages/google-cloud-support/google/cloud/support_v2/types/case_service.py index 3e61466f6d7d..ba22851490f7 100644 --- a/packages/google-cloud-support/google/cloud/support_v2/types/case_service.py +++ b/packages/google-cloud-support/google/cloud/support_v2/types/case_service.py @@ -382,12 +382,12 @@ class SearchCaseClassificationsResponse(proto.Message): def raw_page(self): return self - case_classifications: MutableSequence[gcs_case.CaseClassification] = ( - proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_case.CaseClassification, - ) + case_classifications: MutableSequence[ + gcs_case.CaseClassification + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_case.CaseClassification, ) next_page_token: str = proto.Field( proto.STRING, diff --git a/packages/google-cloud-support/google/cloud/support_v2beta/types/case_service.py b/packages/google-cloud-support/google/cloud/support_v2beta/types/case_service.py index eebd687320fd..42b881235702 100644 --- a/packages/google-cloud-support/google/cloud/support_v2beta/types/case_service.py +++ b/packages/google-cloud-support/google/cloud/support_v2beta/types/case_service.py @@ -404,12 +404,12 @@ class SearchCaseClassificationsResponse(proto.Message): def raw_page(self): return self - case_classifications: MutableSequence[gcs_case.CaseClassification] = ( - proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_case.CaseClassification, - ) + case_classifications: MutableSequence[ + gcs_case.CaseClassification + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_case.CaseClassification, ) next_page_token: str = proto.Field( proto.STRING, From 3e9393adf860b2d40e1f2ec3481f6bad5eccba9e Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Fri, 10 Jul 2026 09:14:21 +0000 Subject: [PATCH 23/23] test: split test_client_helpers.py into domain-specific test files --- .../tests/unit/gapic/test_client_cert.py | 85 ++++++++++++ .../tests/unit/gapic/test_config_helpers.py | 52 ++++++++ .../tests/unit/gapic/test_method_helpers.py | 60 +++++++++ ...test_client_helpers.py => test_routing.py} | 124 ------------------ 4 files changed, 197 insertions(+), 124 deletions(-) create mode 100644 packages/google-api-core/tests/unit/gapic/test_client_cert.py create mode 100644 packages/google-api-core/tests/unit/gapic/test_config_helpers.py create mode 100644 packages/google-api-core/tests/unit/gapic/test_method_helpers.py rename packages/google-api-core/tests/unit/gapic/{test_client_helpers.py => test_routing.py} (53%) diff --git a/packages/google-api-core/tests/unit/gapic/test_client_cert.py b/packages/google-api-core/tests/unit/gapic/test_client_cert.py new file mode 100644 index 000000000000..be563fb58b12 --- /dev/null +++ b/packages/google-api-core/tests/unit/gapic/test_client_cert.py @@ -0,0 +1,85 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +from unittest import mock + +import pytest + +try: + import grpc # noqa: F401 +except ImportError: + pytest.skip("No GRPC", allow_module_level=True) + +from google.api_core.gapic_v1._client_cert import ( + get_client_cert_source, + use_client_cert_effective, +) + + +@mock.patch("google.auth.transport.mtls.should_use_client_cert", create=True) +def test_use_client_cert_effective_with_google_auth(mock_method): + # Test when google-auth supports the method + mock_method.return_value = True + assert use_client_cert_effective() is True + + mock_method.return_value = False + assert use_client_cert_effective() is False + + +@mock.patch.dict(os.environ, {}, clear=True) +def test_use_client_cert_effective_fallback(): + # We must patch hasattr to simulate google-auth lacking the method + with mock.patch( + "google.api_core.gapic_v1._client_cert.hasattr", return_value=False + ): + # Default is false + assert use_client_cert_effective() is False + + env_true = {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"} + with mock.patch.dict(os.environ, env_true): + assert use_client_cert_effective() is True + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} + ): + assert use_client_cert_effective() is False + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "invalid"} + ): + match_str = "must be either `true` or `false`" + with pytest.raises(ValueError, match=match_str): + use_client_cert_effective() + + +@mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", create=True +) # noqa: E501 +@mock.patch( + "google.auth.transport.mtls.default_client_cert_source", create=True +) # noqa: E501 +def test_get_client_cert_source(mock_default, mock_has_default): + mock_default.return_value = b"default_cert" + mock_has_default.return_value = True + + # When use_cert_flag is False, return None + assert get_client_cert_source(b"provided", False) is None + + # When provided_cert_source is given, return provided + assert get_client_cert_source(b"provided", True) == b"provided" # noqa: E501 + + # When no provided cert but default is available + assert get_client_cert_source(None, True) == b"default_cert" diff --git a/packages/google-api-core/tests/unit/gapic/test_config_helpers.py b/packages/google-api-core/tests/unit/gapic/test_config_helpers.py new file mode 100644 index 000000000000..0d3ae61dc353 --- /dev/null +++ b/packages/google-api-core/tests/unit/gapic/test_config_helpers.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +from unittest import mock + +import pytest + +try: + import grpc # noqa: F401 +except ImportError: + pytest.skip("No GRPC", allow_module_level=True) + +from google.auth.exceptions import MutualTLSChannelError + +from google.api_core.gapic_v1._config_helpers import read_environment_variables + + +@mock.patch( + "google.api_core.gapic_v1._config_helpers.use_client_cert_effective" +) # noqa: E501 +@mock.patch.dict(os.environ, clear=True) +def test_read_environment_variables(mock_effective): + mock_effective.return_value = True + os.environ["GOOGLE_API_USE_MTLS_ENDPOINT"] = "always" + os.environ["GOOGLE_CLOUD_UNIVERSE_DOMAIN"] = "custom.com" + + cert, mtls, domain = read_environment_variables() + assert cert is True + assert mtls == "always" + assert domain == "custom.com" + + +@mock.patch.dict(os.environ, clear=True) +def test_read_environment_variables_invalid_mtls(): + os.environ["GOOGLE_API_USE_MTLS_ENDPOINT"] = "invalid" + with pytest.raises( + MutualTLSChannelError, match="must be `never`, `auto` or `always`" + ): + read_environment_variables() diff --git a/packages/google-api-core/tests/unit/gapic/test_method_helpers.py b/packages/google-api-core/tests/unit/gapic/test_method_helpers.py new file mode 100644 index 000000000000..aabd027c5a19 --- /dev/null +++ b/packages/google-api-core/tests/unit/gapic/test_method_helpers.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pytest + +try: + import grpc # noqa: F401 +except ImportError: + pytest.skip("No GRPC", allow_module_level=True) + +from google.api_core.gapic_v1._method_helpers import setup_request_id + + +def test_setup_request_id(): + import uuid + + # test dict request + req = {} + setup_request_id(req, "request_id", True) + assert "request_id" in req + uuid_str = req["request_id"] + uuid.UUID(uuid_str) # verify it is a valid UUID + + # test dict request when already set + req = {"request_id": "existing"} + setup_request_id(req, "request_id", True) + assert req["request_id"] == "existing" + + class DummyRequest: + def __init__(self): + self.request_id = "" + + def HasField(self, field_name): + if not hasattr(self, field_name): + raise ValueError() + return bool(getattr(self, field_name)) + + # test object request proto3 optional true + req_obj = DummyRequest() + setup_request_id(req_obj, "request_id", True) + assert req_obj.request_id != "" + uuid.UUID(req_obj.request_id) + + # test object request proto3 optional false + req_obj2 = DummyRequest() + setup_request_id(req_obj2, "request_id", False) + assert req_obj2.request_id != "" + uuid.UUID(req_obj2.request_id) diff --git a/packages/google-api-core/tests/unit/gapic/test_client_helpers.py b/packages/google-api-core/tests/unit/gapic/test_routing.py similarity index 53% rename from packages/google-api-core/tests/unit/gapic/test_client_helpers.py rename to packages/google-api-core/tests/unit/gapic/test_routing.py index 0fa935c752ce..b3d2561cb13e 100644 --- a/packages/google-api-core/tests/unit/gapic/test_client_helpers.py +++ b/packages/google-api-core/tests/unit/gapic/test_routing.py @@ -13,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. -import os from unittest import mock import pytest @@ -25,12 +24,6 @@ from google.auth.exceptions import MutualTLSChannelError -from google.api_core.gapic_v1._client_cert import ( - get_client_cert_source, - use_client_cert_effective, -) -from google.api_core.gapic_v1._config_helpers import read_environment_variables -from google.api_core.gapic_v1._method_helpers import setup_request_id from google.api_core.gapic_v1._routing import ( get_api_endpoint, get_default_mtls_endpoint, @@ -58,42 +51,6 @@ def test_get_default_mtls_endpoint(): assert get_default_mtls_endpoint(None) is None -@mock.patch("google.auth.transport.mtls.should_use_client_cert", create=True) -def test_use_client_cert_effective_with_google_auth(mock_method): - # Test when google-auth supports the method - mock_method.return_value = True - assert use_client_cert_effective() is True - - mock_method.return_value = False - assert use_client_cert_effective() is False - - -@mock.patch.dict(os.environ, {}, clear=True) -def test_use_client_cert_effective_fallback(): - # We must patch hasattr to simulate google-auth lacking the method - with mock.patch( - "google.api_core.gapic_v1._client_cert.hasattr", return_value=False - ): - # Default is false - assert use_client_cert_effective() is False - - env_true = {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"} - with mock.patch.dict(os.environ, env_true): - assert use_client_cert_effective() is True - - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} - ): - assert use_client_cert_effective() is False - - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "invalid"} - ): - match_str = "must be either `true` or `false`" - with pytest.raises(ValueError, match=match_str): - use_client_cert_effective() - - def test_get_api_endpoint_override(): # If api_override is provided, it should be returned # regardless of other args @@ -165,50 +122,6 @@ def test_get_api_endpoint_mtls_universe_mismatch(): ) -@mock.patch( - "google.api_core.gapic_v1._config_helpers.use_client_cert_effective" -) # noqa: E501 -@mock.patch.dict(os.environ, clear=True) -def test_read_environment_variables(mock_effective): - mock_effective.return_value = True - os.environ["GOOGLE_API_USE_MTLS_ENDPOINT"] = "always" - os.environ["GOOGLE_CLOUD_UNIVERSE_DOMAIN"] = "custom.com" - - cert, mtls, domain = read_environment_variables() - assert cert is True - assert mtls == "always" - assert domain == "custom.com" - - -@mock.patch.dict(os.environ, clear=True) -def test_read_environment_variables_invalid_mtls(): - os.environ["GOOGLE_API_USE_MTLS_ENDPOINT"] = "invalid" - with pytest.raises( - MutualTLSChannelError, match="must be `never`, `auto` or `always`" - ): - read_environment_variables() - - -@mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", create=True -) # noqa: E501 -@mock.patch( - "google.auth.transport.mtls.default_client_cert_source", create=True -) # noqa: E501 -def test_get_client_cert_source(mock_default, mock_has_default): - mock_default.return_value = b"default_cert" - mock_has_default.return_value = True - - # When use_cert_flag is False, return None - assert get_client_cert_source(b"provided", False) is None - - # When provided_cert_source is given, return provided - assert get_client_cert_source(b"provided", True) == b"provided" # noqa: E501 - - # When no provided cert but default is available - assert get_client_cert_source(None, True) == b"default_cert" - - def test_get_universe_domain(): # client_universe_domain takes precedence assert ( @@ -228,40 +141,3 @@ def test_get_universe_domain(): def test_get_universe_domain_empty(): with pytest.raises(ValueError, match="cannot be an empty string"): get_universe_domain("", None, "default.com") - - -def test_setup_request_id(): - import uuid - - # test dict request - req = {} - setup_request_id(req, "request_id", True) - assert "request_id" in req - uuid_str = req["request_id"] - uuid.UUID(uuid_str) # verify it is a valid UUID - - # test dict request when already set - req = {"request_id": "existing"} - setup_request_id(req, "request_id", True) - assert req["request_id"] == "existing" - - class DummyRequest: - def __init__(self): - self.request_id = "" - - def HasField(self, field_name): - if not hasattr(self, field_name): - raise ValueError() - return bool(getattr(self, field_name)) - - # test object request proto3 optional true - req_obj = DummyRequest() - setup_request_id(req_obj, "request_id", True) - assert req_obj.request_id != "" - uuid.UUID(req_obj.request_id) - - # test object request proto3 optional false - req_obj2 = DummyRequest() - setup_request_id(req_obj2, "request_id", False) - assert req_obj2.request_id != "" - uuid.UUID(req_obj2.request_id)