From 8e00d80b19618d42e79833cff20e2f62c08fcede Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Wed, 23 Dec 2020 16:12:55 -0800 Subject: [PATCH] feat: add common resource helper methods; expose client transport (#34) --- docs/dashboard_v1/types.rst | 1 + .../dashboards_service/async_client.py | 80 +- .../services/dashboards_service/client.py | 204 +++- .../dashboards_service/transports/base.py | 27 +- .../dashboards_service/transports/grpc.py | 72 +- .../transports/grpc_asyncio.py | 65 +- .../monitoring_dashboard_v1/types/text.py | 4 +- noxfile.py | 2 +- scripts/fixup_dashboard_v1_keywords.py | 1 + synth.metadata | 109 ++- .../dashboard_v1/test_dashboards_service.py | 898 +++++++++++------- 11 files changed, 1003 insertions(+), 460 deletions(-) diff --git a/docs/dashboard_v1/types.rst b/docs/dashboard_v1/types.rst index d9c96b5..4029818 100644 --- a/docs/dashboard_v1/types.rst +++ b/docs/dashboard_v1/types.rst @@ -3,3 +3,4 @@ Types for Google Monitoring Dashboard v1 API .. automodule:: google.cloud.monitoring_dashboard_v1.types :members: + :show-inheritance: diff --git a/google/cloud/monitoring_dashboard_v1/services/dashboards_service/async_client.py b/google/cloud/monitoring_dashboard_v1/services/dashboards_service/async_client.py index 0d6f9fe..5f404d7 100644 --- a/google/cloud/monitoring_dashboard_v1/services/dashboards_service/async_client.py +++ b/google/cloud/monitoring_dashboard_v1/services/dashboards_service/async_client.py @@ -33,7 +33,7 @@ from google.cloud.monitoring_dashboard_v1.types import dashboards_service from google.cloud.monitoring_dashboard_v1.types import layouts -from .transports.base import DashboardsServiceTransport +from .transports.base import DashboardsServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import DashboardsServiceGrpcAsyncIOTransport from .client import DashboardsServiceClient @@ -49,10 +49,49 @@ class DashboardsServiceAsyncClient: DEFAULT_MTLS_ENDPOINT = DashboardsServiceClient.DEFAULT_MTLS_ENDPOINT dashboard_path = staticmethod(DashboardsServiceClient.dashboard_path) + parse_dashboard_path = staticmethod(DashboardsServiceClient.parse_dashboard_path) + + common_billing_account_path = staticmethod( + DashboardsServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + DashboardsServiceClient.parse_common_billing_account_path + ) + + common_folder_path = staticmethod(DashboardsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + DashboardsServiceClient.parse_common_folder_path + ) + + common_organization_path = staticmethod( + DashboardsServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + DashboardsServiceClient.parse_common_organization_path + ) + + common_project_path = staticmethod(DashboardsServiceClient.common_project_path) + parse_common_project_path = staticmethod( + DashboardsServiceClient.parse_common_project_path + ) + + common_location_path = staticmethod(DashboardsServiceClient.common_location_path) + parse_common_location_path = staticmethod( + DashboardsServiceClient.parse_common_location_path + ) from_service_account_file = DashboardsServiceClient.from_service_account_file from_service_account_json = from_service_account_file + @property + def transport(self) -> DashboardsServiceTransport: + """Return the transport used by the client instance. + + Returns: + DashboardsServiceTransport: The transport used by the client instance. + """ + return self._client.transport + get_transport_class = functools.partial( type(DashboardsServiceClient).get_transport_class, type(DashboardsServiceClient) ) @@ -63,6 +102,7 @@ def __init__( credentials: credentials.Credentials = None, transport: Union[str, DashboardsServiceTransport] = "grpc_asyncio", client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the dashboards service client. @@ -78,16 +118,19 @@ def __init__( client_options (ClientOptions): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT environment variable can also be used to override the endpoint: "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint, this is the default value for - the environment variable) and "auto" (auto switch to the default - mTLS endpoint if client SSL credentials is present). However, - the ``api_endpoint`` property takes precedence if provided. - (2) The ``client_cert_source`` property is used to provide client - SSL credentials for mutual TLS transport. If not provided, the - default SSL credentials will be used if present. + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. Raises: google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport @@ -95,7 +138,10 @@ def __init__( """ self._client = DashboardsServiceClient( - credentials=credentials, transport=transport, client_options=client_options, + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, ) async def create_dashboard( @@ -139,7 +185,7 @@ async def create_dashboard( rpc = gapic_v1.method_async.wrap_method( self._client._transport.create_dashboard, default_timeout=30.0, - client_info=_client_info, + client_info=DEFAULT_CLIENT_INFO, ) # Certain fields should be provided within the metadata header; @@ -195,7 +241,7 @@ async def list_dashboards( rpc = gapic_v1.method_async.wrap_method( self._client._transport.list_dashboards, default_timeout=None, - client_info=_client_info, + client_info=DEFAULT_CLIENT_INFO, ) # Certain fields should be provided within the metadata header; @@ -257,7 +303,7 @@ async def get_dashboard( rpc = gapic_v1.method_async.wrap_method( self._client._transport.get_dashboard, default_timeout=None, - client_info=_client_info, + client_info=DEFAULT_CLIENT_INFO, ) # Certain fields should be provided within the metadata header; @@ -305,7 +351,7 @@ async def delete_dashboard( rpc = gapic_v1.method_async.wrap_method( self._client._transport.delete_dashboard, default_timeout=30.0, - client_info=_client_info, + client_info=DEFAULT_CLIENT_INFO, ) # Certain fields should be provided within the metadata header; @@ -360,7 +406,7 @@ async def update_dashboard( rpc = gapic_v1.method_async.wrap_method( self._client._transport.update_dashboard, default_timeout=30.0, - client_info=_client_info, + client_info=DEFAULT_CLIENT_INFO, ) # Certain fields should be provided within the metadata header; @@ -379,13 +425,13 @@ async def update_dashboard( try: - _client_info = gapic_v1.client_info.ClientInfo( + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( "google-monitoring-dashboard", ).version, ) except pkg_resources.DistributionNotFound: - _client_info = gapic_v1.client_info.ClientInfo() + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() __all__ = ("DashboardsServiceAsyncClient",) diff --git a/google/cloud/monitoring_dashboard_v1/services/dashboards_service/client.py b/google/cloud/monitoring_dashboard_v1/services/dashboards_service/client.py index e0ea14e..80db959 100644 --- a/google/cloud/monitoring_dashboard_v1/services/dashboards_service/client.py +++ b/google/cloud/monitoring_dashboard_v1/services/dashboards_service/client.py @@ -16,17 +16,19 @@ # from collections import OrderedDict +from distutils import util import os import re -from typing import Callable, Dict, Sequence, Tuple, Type, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources -import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import client_options as client_options_lib # type: ignore from google.api_core import exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.auth import 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 @@ -35,7 +37,7 @@ from google.cloud.monitoring_dashboard_v1.types import dashboards_service from google.cloud.monitoring_dashboard_v1.types import layouts -from .transports.base import DashboardsServiceTransport +from .transports.base import DashboardsServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import DashboardsServiceGrpcTransport from .transports.grpc_asyncio import DashboardsServiceGrpcAsyncIOTransport @@ -134,6 +136,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file + @property + def transport(self) -> DashboardsServiceTransport: + """Return the transport used by the client instance. + + Returns: + DashboardsServiceTransport: The transport used by the client instance. + """ + return self._transport + @staticmethod def dashboard_path(project: str, dashboard: str,) -> str: """Return a fully-qualified dashboard string.""" @@ -147,12 +158,72 @@ def parse_dashboard_path(path: str) -> Dict[str, str]: m = re.match(r"^projects/(?P.+?)/dashboards/(?P.+?)$", path) return m.groupdict() if m else {} + @staticmethod + def common_billing_account_path(billing_account: str,) -> str: + """Return a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str,) -> str: + """Return a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder,) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str,) -> str: + """Return a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization,) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str,) -> str: + """Return a fully-qualified project string.""" + return "projects/{project}".format(project=project,) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str,) -> str: + """Return a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + def __init__( self, *, - credentials: credentials.Credentials = None, - transport: Union[str, DashboardsServiceTransport] = None, - client_options: ClientOptions = None, + credentials: Optional[credentials.Credentials] = None, + transport: Union[str, DashboardsServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the dashboards service client. @@ -165,48 +236,74 @@ def __init__( transport (Union[str, ~.DashboardsServiceTransport]): The transport to use. If set to None, a transport is chosen automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. + client_options (client_options_lib.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT environment variable can also be used to override the endpoint: "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint, this is the default value for - the environment variable) and "auto" (auto switch to the default - mTLS endpoint if client SSL credentials is present). However, - the ``api_endpoint`` property takes precedence if provided. - (2) The ``client_cert_source`` property is used to provide client - SSL credentials for mutual TLS transport. If not provided, the - default SSL credentials will be used if present. + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. """ if isinstance(client_options, dict): - client_options = ClientOptions.from_dict(client_options) + client_options = client_options_lib.from_dict(client_options) if client_options is None: - client_options = ClientOptions.ClientOptions() + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) - if client_options.api_endpoint is None: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") + ssl_credentials = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + import grpc # type: ignore + + cert, key = client_options.client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + is_mtls = True + else: + creds = SslCredentials() + is_mtls = creds.is_mtls + ssl_credentials = creds.ssl_credentials if is_mtls else None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_env == "never": - client_options.api_endpoint = self.DEFAULT_ENDPOINT + api_endpoint = self.DEFAULT_ENDPOINT elif use_mtls_env == "always": - client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT + api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - has_client_cert_source = ( - client_options.client_cert_source is not None - or mtls.has_default_client_cert_source() - ) - client_options.api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT - if has_client_cert_source - else self.DEFAULT_ENDPOINT + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT ) else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" ) # Save or instantiate the transport. @@ -230,11 +327,11 @@ def __init__( self._transport = Transport( credentials=credentials, credentials_file=client_options.credentials_file, - host=client_options.api_endpoint, + host=api_endpoint, scopes=client_options.scopes, - api_mtls_endpoint=client_options.api_endpoint, - client_cert_source=client_options.client_cert_source, + ssl_channel_credentials=ssl_credentials, quota_project_id=client_options.quota_project_id, + client_info=client_info, ) def create_dashboard( @@ -271,7 +368,12 @@ def create_dashboard( """ # Create or coerce a protobuf request object. - request = dashboards_service.CreateDashboardRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a dashboards_service.CreateDashboardRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, dashboards_service.CreateDashboardRequest): + request = dashboards_service.CreateDashboardRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -323,7 +425,12 @@ def list_dashboards( """ # Create or coerce a protobuf request object. - request = dashboards_service.ListDashboardsRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a dashboards_service.ListDashboardsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, dashboards_service.ListDashboardsRequest): + request = dashboards_service.ListDashboardsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -381,7 +488,12 @@ def get_dashboard( """ # Create or coerce a protobuf request object. - request = dashboards_service.GetDashboardRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a dashboards_service.GetDashboardRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, dashboards_service.GetDashboardRequest): + request = dashboards_service.GetDashboardRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -425,7 +537,12 @@ def delete_dashboard( """ # Create or coerce a protobuf request object. - request = dashboards_service.DeleteDashboardRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a dashboards_service.DeleteDashboardRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, dashboards_service.DeleteDashboardRequest): + request = dashboards_service.DeleteDashboardRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -476,7 +593,12 @@ def update_dashboard( """ # Create or coerce a protobuf request object. - request = dashboards_service.UpdateDashboardRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a dashboards_service.UpdateDashboardRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, dashboards_service.UpdateDashboardRequest): + request = dashboards_service.UpdateDashboardRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -498,13 +620,13 @@ def update_dashboard( try: - _client_info = gapic_v1.client_info.ClientInfo( + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( "google-monitoring-dashboard", ).version, ) except pkg_resources.DistributionNotFound: - _client_info = gapic_v1.client_info.ClientInfo() + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() __all__ = ("DashboardsServiceClient",) diff --git a/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/base.py b/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/base.py index 45a4a7a..f2c092f 100644 --- a/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/base.py +++ b/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/base.py @@ -19,9 +19,10 @@ import typing import pkg_resources -from google import auth +from google import auth # type: ignore from google.api_core import exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore from google.auth import credentials # type: ignore from google.cloud.monitoring_dashboard_v1.types import dashboard @@ -30,13 +31,13 @@ try: - _client_info = gapic_v1.client_info.ClientInfo( + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( "google-monitoring-dashboard", ).version, ) except pkg_resources.DistributionNotFound: - _client_info = gapic_v1.client_info.ClientInfo() + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() class DashboardsServiceTransport(abc.ABC): @@ -57,6 +58,7 @@ def __init__( credentials_file: typing.Optional[str] = None, scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. @@ -74,6 +76,11 @@ def __init__( scope (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -101,25 +108,25 @@ def __init__( self._credentials = credentials # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages() + self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self): + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { self.create_dashboard: gapic_v1.method.wrap_method( - self.create_dashboard, default_timeout=30.0, client_info=_client_info, + self.create_dashboard, default_timeout=30.0, client_info=client_info, ), self.list_dashboards: gapic_v1.method.wrap_method( - self.list_dashboards, default_timeout=None, client_info=_client_info, + self.list_dashboards, default_timeout=None, client_info=client_info, ), self.get_dashboard: gapic_v1.method.wrap_method( - self.get_dashboard, default_timeout=None, client_info=_client_info, + self.get_dashboard, default_timeout=None, client_info=client_info, ), self.delete_dashboard: gapic_v1.method.wrap_method( - self.delete_dashboard, default_timeout=30.0, client_info=_client_info, + self.delete_dashboard, default_timeout=30.0, client_info=client_info, ), self.update_dashboard: gapic_v1.method.wrap_method( - self.update_dashboard, default_timeout=30.0, client_info=_client_info, + self.update_dashboard, default_timeout=30.0, client_info=client_info, ), } diff --git a/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/grpc.py b/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/grpc.py index 3c79d99..add8318 100644 --- a/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/grpc.py +++ b/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/grpc.py @@ -15,21 +15,22 @@ # limitations under the License. # +import warnings from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore from google import auth # type: ignore from google.auth import credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore - import grpc # type: ignore from google.cloud.monitoring_dashboard_v1.types import dashboard from google.cloud.monitoring_dashboard_v1.types import dashboards_service from google.protobuf import empty_pb2 as empty # type: ignore -from .base import DashboardsServiceTransport +from .base import DashboardsServiceTransport, DEFAULT_CLIENT_INFO class DashboardsServiceGrpcTransport(DashboardsServiceTransport): @@ -58,7 +59,9 @@ def __init__( channel: grpc.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the transport. @@ -77,16 +80,23 @@ def __init__( ignored if ``channel`` is provided. channel (Optional[grpc.Channel]): A ``Channel`` instance through which to make calls. - api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If - provided, it overrides the ``host`` argument and tries to create + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A - callback to provide client SSL certificate bytes and private key - bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` - is None. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -94,6 +104,8 @@ def __init__( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ + self._ssl_channel_credentials = ssl_channel_credentials + if channel: # Sanity check: Ensure that channel and credentials are not both # provided. @@ -101,7 +113,13 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel + self._ssl_channel_credentials = None elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + host = ( api_mtls_endpoint if ":" in api_mtls_endpoint @@ -132,6 +150,24 @@ def __init__( scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) self._stubs = {} # type: Dict[str, Callable] @@ -142,6 +178,7 @@ def __init__( credentials_file=credentials_file, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + client_info=client_info, ) @classmethod @@ -152,7 +189,7 @@ def create_channel( credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, - **kwargs + **kwargs, ) -> grpc.Channel: """Create and return a gRPC channel object. Args: @@ -186,24 +223,13 @@ def create_channel( credentials_file=credentials_file, scopes=scopes, quota_project_id=quota_project_id, - **kwargs + **kwargs, ) @property def grpc_channel(self) -> grpc.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. + """Return the channel designed to connect to this service. """ - # Sanity check: Only create a new channel if we do not already - # have one. - if not hasattr(self, "_grpc_channel"): - self._grpc_channel = self.create_channel( - self._host, credentials=self._credentials, - ) - - # Return the channel from cache. return self._grpc_channel @property diff --git a/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/grpc_asyncio.py b/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/grpc_asyncio.py index 56d63f6..cc0763f 100644 --- a/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/grpc_asyncio.py +++ b/google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/grpc_asyncio.py @@ -15,9 +15,12 @@ # limitations under the License. # +import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore +from google import auth # type: ignore from google.auth import credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -28,7 +31,7 @@ from google.cloud.monitoring_dashboard_v1.types import dashboards_service from google.protobuf import empty_pb2 as empty # type: ignore -from .base import DashboardsServiceTransport +from .base import DashboardsServiceTransport, DEFAULT_CLIENT_INFO from .grpc import DashboardsServiceGrpcTransport @@ -100,7 +103,9 @@ def __init__( channel: aio.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the transport. @@ -120,16 +125,23 @@ def __init__( are passed to :func:`google.auth.default`. channel (Optional[aio.Channel]): A ``Channel`` instance through which to make calls. - api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If - provided, it overrides the ``host`` argument and tries to create + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A - callback to provide client SSL certificate bytes and private key - bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` - is None. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. Raises: google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport @@ -137,6 +149,8 @@ def __init__( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ + self._ssl_channel_credentials = ssl_channel_credentials + if channel: # Sanity check: Ensure that channel and credentials are not both # provided. @@ -144,13 +158,24 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel + self._ssl_channel_credentials = None elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + host = ( api_mtls_endpoint if ":" in api_mtls_endpoint else api_mtls_endpoint + ":443" ) + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + # Create SSL credentials with client_cert_source or application # default SSL credentials. if client_cert_source: @@ -170,6 +195,24 @@ def __init__( scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) # Run the base constructor. super().__init__( @@ -178,6 +221,7 @@ def __init__( credentials_file=credentials_file, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + client_info=client_info, ) self._stubs = {} @@ -189,13 +233,6 @@ def grpc_channel(self) -> aio.Channel: This property caches on the instance; repeated calls return the same channel. """ - # Sanity check: Only create a new channel if we do not already - # have one. - if not hasattr(self, "_grpc_channel"): - self._grpc_channel = self.create_channel( - self._host, credentials=self._credentials, - ) - # Return the channel from cache. return self._grpc_channel diff --git a/google/cloud/monitoring_dashboard_v1/types/text.py b/google/cloud/monitoring_dashboard_v1/types/text.py index df10f69..33e4da4 100644 --- a/google/cloud/monitoring_dashboard_v1/types/text.py +++ b/google/cloud/monitoring_dashboard_v1/types/text.py @@ -29,7 +29,7 @@ class Text(proto.Message): Attributes: content (str): The text content to be displayed. - format (~.text.Text.Format): + format_ (~.text.Text.Format): How the text content is formatted. """ @@ -41,7 +41,7 @@ class Format(proto.Enum): content = proto.Field(proto.STRING, number=1) - format = proto.Field(proto.ENUM, number=2, enum=Format,) + format_ = proto.Field(proto.ENUM, number=2, enum=Format,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/noxfile.py b/noxfile.py index aa9e3da..31f884f 100644 --- a/noxfile.py +++ b/noxfile.py @@ -28,7 +28,7 @@ DEFAULT_PYTHON_VERSION = "3.8" SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"] -UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8"] +UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8", "3.9"] @nox.session(python=DEFAULT_PYTHON_VERSION) diff --git a/scripts/fixup_dashboard_v1_keywords.py b/scripts/fixup_dashboard_v1_keywords.py index e0d2372..fd8c736 100644 --- a/scripts/fixup_dashboard_v1_keywords.py +++ b/scripts/fixup_dashboard_v1_keywords.py @@ -1,3 +1,4 @@ +#! /usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2020 Google LLC diff --git a/synth.metadata b/synth.metadata index 5914933..8aa425a 100644 --- a/synth.metadata +++ b/synth.metadata @@ -3,16 +3,16 @@ { "git": { "name": ".", - "remote": "git@github.com:googleapis/python-monitoring-dashboards.git", - "sha": "bee992e45a3500dfe44089e7e594a906fd675c8d" + "remote": "https://github.com/googleapis/python-monitoring-dashboards.git", + "sha": "cb6a89f29579af6e03c34e9594d3d15d2439c716" } }, { "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "d399c754bdea83297877ab49e5f66b257a957a78", - "internalRef": "323860336" + "sha": "07d41a7e5cade45aba6f0d277c89722b48f2c956", + "internalRef": "339292950" } }, { @@ -40,5 +40,106 @@ "generator": "bazel" } } + ], + "generatedFiles": [ + ".flake8", + ".github/CONTRIBUTING.md", + ".github/ISSUE_TEMPLATE/bug_report.md", + ".github/ISSUE_TEMPLATE/feature_request.md", + ".github/ISSUE_TEMPLATE/support_request.md", + ".github/PULL_REQUEST_TEMPLATE.md", + ".github/release-please.yml", + ".gitignore", + ".kokoro/build.sh", + ".kokoro/continuous/common.cfg", + ".kokoro/continuous/continuous.cfg", + ".kokoro/docs/common.cfg", + ".kokoro/docs/docs.cfg", + ".kokoro/presubmit/common.cfg", + ".kokoro/presubmit/presubmit.cfg", + ".kokoro/publish-docs.sh", + ".kokoro/release.sh", + ".kokoro/release/common.cfg", + ".kokoro/release/release.cfg", + ".kokoro/samples/lint/common.cfg", + ".kokoro/samples/lint/continuous.cfg", + ".kokoro/samples/lint/periodic.cfg", + ".kokoro/samples/lint/presubmit.cfg", + ".kokoro/samples/python3.6/common.cfg", + ".kokoro/samples/python3.6/continuous.cfg", + ".kokoro/samples/python3.6/periodic.cfg", + ".kokoro/samples/python3.6/presubmit.cfg", + ".kokoro/samples/python3.7/common.cfg", + ".kokoro/samples/python3.7/continuous.cfg", + ".kokoro/samples/python3.7/periodic.cfg", + ".kokoro/samples/python3.7/presubmit.cfg", + ".kokoro/samples/python3.8/common.cfg", + ".kokoro/samples/python3.8/continuous.cfg", + ".kokoro/samples/python3.8/periodic.cfg", + ".kokoro/samples/python3.8/presubmit.cfg", + ".kokoro/test-samples.sh", + ".kokoro/trampoline.sh", + "CODE_OF_CONDUCT.md", + "CONTRIBUTING.rst", + "LICENSE", + "MANIFEST.in", + "docs/_static/custom.css", + "docs/_templates/layout.html", + "docs/conf.py", + "docs/dashboard_v1/services.rst", + "docs/dashboard_v1/types.rst", + "docs/multiprocessing.rst", + "google/cloud/monitoring_dashboard/__init__.py", + "google/cloud/monitoring_dashboard/py.typed", + "google/cloud/monitoring_dashboard_v1/__init__.py", + "google/cloud/monitoring_dashboard_v1/proto/common.proto", + "google/cloud/monitoring_dashboard_v1/proto/dashboard.proto", + "google/cloud/monitoring_dashboard_v1/proto/dashboards_service.proto", + "google/cloud/monitoring_dashboard_v1/proto/drilldowns.proto", + "google/cloud/monitoring_dashboard_v1/proto/layouts.proto", + "google/cloud/monitoring_dashboard_v1/proto/metrics.proto", + "google/cloud/monitoring_dashboard_v1/proto/scorecard.proto", + "google/cloud/monitoring_dashboard_v1/proto/service.proto", + "google/cloud/monitoring_dashboard_v1/proto/text.proto", + "google/cloud/monitoring_dashboard_v1/proto/widget.proto", + "google/cloud/monitoring_dashboard_v1/proto/xychart.proto", + "google/cloud/monitoring_dashboard_v1/py.typed", + "google/cloud/monitoring_dashboard_v1/services/__init__.py", + "google/cloud/monitoring_dashboard_v1/services/dashboards_service/__init__.py", + "google/cloud/monitoring_dashboard_v1/services/dashboards_service/async_client.py", + "google/cloud/monitoring_dashboard_v1/services/dashboards_service/client.py", + "google/cloud/monitoring_dashboard_v1/services/dashboards_service/pagers.py", + "google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/__init__.py", + "google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/base.py", + "google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/grpc.py", + "google/cloud/monitoring_dashboard_v1/services/dashboards_service/transports/grpc_asyncio.py", + "google/cloud/monitoring_dashboard_v1/types/__init__.py", + "google/cloud/monitoring_dashboard_v1/types/common.py", + "google/cloud/monitoring_dashboard_v1/types/dashboard.py", + "google/cloud/monitoring_dashboard_v1/types/dashboards_service.py", + "google/cloud/monitoring_dashboard_v1/types/drilldowns.py", + "google/cloud/monitoring_dashboard_v1/types/layouts.py", + "google/cloud/monitoring_dashboard_v1/types/metrics.py", + "google/cloud/monitoring_dashboard_v1/types/scorecard.py", + "google/cloud/monitoring_dashboard_v1/types/service.py", + "google/cloud/monitoring_dashboard_v1/types/text.py", + "google/cloud/monitoring_dashboard_v1/types/widget.py", + "google/cloud/monitoring_dashboard_v1/types/xychart.py", + "noxfile.py", + "renovate.json", + "samples/AUTHORING_GUIDE.md", + "samples/CONTRIBUTING.md", + "scripts/decrypt-secrets.sh", + "scripts/fixup_dashboard_v1_keywords.py", + "scripts/readme-gen/readme_gen.py", + "scripts/readme-gen/templates/README.tmpl.rst", + "scripts/readme-gen/templates/auth.tmpl.rst", + "scripts/readme-gen/templates/auth_api_key.tmpl.rst", + "scripts/readme-gen/templates/install_deps.tmpl.rst", + "scripts/readme-gen/templates/install_portaudio.tmpl.rst", + "setup.cfg", + "testing/.gitignore", + "tests/unit/gapic/dashboard_v1/__init__.py", + "tests/unit/gapic/dashboard_v1/test_dashboards_service.py" ] } \ No newline at end of file diff --git a/tests/unit/gapic/dashboard_v1/test_dashboards_service.py b/tests/unit/gapic/dashboard_v1/test_dashboards_service.py index 5a7e1a2..2a35c96 100644 --- a/tests/unit/gapic/dashboard_v1/test_dashboards_service.py +++ b/tests/unit/gapic/dashboard_v1/test_dashboards_service.py @@ -46,9 +46,7 @@ from google.cloud.monitoring_dashboard_v1.types import layouts from google.cloud.monitoring_dashboard_v1.types import metrics from google.cloud.monitoring_dashboard_v1.types import scorecard -from google.cloud.monitoring_dashboard_v1.types import scorecard as gmd_scorecard from google.cloud.monitoring_dashboard_v1.types import text -from google.cloud.monitoring_dashboard_v1.types import text as gmd_text from google.cloud.monitoring_dashboard_v1.types import widget from google.cloud.monitoring_dashboard_v1.types import xychart from google.oauth2 import service_account @@ -110,12 +108,12 @@ def test_dashboards_service_client_from_service_account_file(client_class): ) as factory: factory.return_value = creds client = client_class.from_service_account_file("dummy/file/path.json") - assert client._transport._credentials == creds + assert client.transport._credentials == creds client = client_class.from_service_account_json("dummy/file/path.json") - assert client._transport._credentials == creds + assert client.transport._credentials == creds - assert client._transport._host == "monitoring.googleapis.com:443" + assert client.transport._host == "monitoring.googleapis.com:443" def test_dashboards_service_client_get_transport_class(): @@ -171,14 +169,14 @@ def test_dashboards_service_client_client_options( credentials_file=None, host="squid.clam.whelk", scopes=None, - api_mtls_endpoint="squid.clam.whelk", - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, ) - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "never"}): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class() @@ -187,14 +185,14 @@ def test_dashboards_service_client_client_options( credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=None, - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, ) - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "always"}): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class() @@ -203,90 +201,185 @@ def test_dashboards_service_client_client_options( credentials_file=None, host=client.DEFAULT_MTLS_ENDPOINT, scopes=None, - api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, ) - # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is - # "auto", and client_cert_source is provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + DashboardsServiceClient, + transports.DashboardsServiceGrpcTransport, + "grpc", + "true", + ), + ( + DashboardsServiceAsyncClient, + transports.DashboardsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + DashboardsServiceClient, + transports.DashboardsServiceGrpcTransport, + "grpc", + "false", + ), + ( + DashboardsServiceAsyncClient, + transports.DashboardsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + DashboardsServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(DashboardsServiceClient), +) +@mock.patch.object( + DashboardsServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(DashboardsServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_dashboards_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): options = client_options.ClientOptions( client_cert_source=client_cert_source_callback ) with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, - client_cert_source=client_cert_source_callback, - quota_project_id=None, - ) - - # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is - # "auto", and default_client_cert_source is provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): - with mock.patch.object(transport_class, "__init__") as patched: + ssl_channel_creds = mock.Mock() with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds ): patched.return_value = None - client = client_class() + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_ssl_channel_creds = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_ssl_channel_creds = ssl_channel_creds + expected_host = client.DEFAULT_MTLS_ENDPOINT + patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, + host=expected_host, scopes=None, - api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, - client_cert_source=None, + ssl_channel_credentials=expected_ssl_channel_creds, quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, ) - # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is - # "auto", but client_cert_source and default_client_cert_source are None. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): with mock.patch.object(transport_class, "__init__") as patched: with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None ): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, - quota_project_id=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, - quota_project_id="octopus", - ) + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.ssl_credentials", + new_callable=mock.PropertyMock, + ) as ssl_credentials_mock: + if use_client_cert_env == "false": + is_mtls_mock.return_value = False + ssl_credentials_mock.return_value = None + expected_host = client.DEFAULT_ENDPOINT + expected_ssl_channel_creds = None + else: + is_mtls_mock.return_value = True + ssl_credentials_mock.return_value = mock.Mock() + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_ssl_channel_creds = ( + ssl_credentials_mock.return_value + ) + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + is_mtls_mock.return_value = False + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) @pytest.mark.parametrize( @@ -313,9 +406,9 @@ def test_dashboards_service_client_client_options_scopes( credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=["1", "2"], - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -343,9 +436,9 @@ def test_dashboards_service_client_client_options_credentials_file( credentials_file="credentials.json", host=client.DEFAULT_ENDPOINT, scopes=None, - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -362,25 +455,25 @@ def test_dashboards_service_client_client_options_from_dict(): credentials_file=None, host="squid.clam.whelk", scopes=None, - api_mtls_endpoint="squid.clam.whelk", - client_cert_source=None, + ssl_channel_credentials=None, quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, ) -def test_create_dashboard(transport: str = "grpc"): +def test_create_dashboard( + transport: str = "grpc", request_type=dashboards_service.CreateDashboardRequest +): client = DashboardsServiceClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = dashboards_service.CreateDashboardRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._transport.create_dashboard), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_dashboard), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = dashboard.Dashboard( name="name_value", @@ -395,9 +488,10 @@ def test_create_dashboard(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == dashboards_service.CreateDashboardRequest() # Establish that the response is the type that we expect. + assert isinstance(response, dashboard.Dashboard) assert response.name == "name_value" @@ -407,20 +501,25 @@ def test_create_dashboard(transport: str = "grpc"): assert response.etag == "etag_value" +def test_create_dashboard_from_dict(): + test_create_dashboard(request_type=dict) + + @pytest.mark.asyncio -async def test_create_dashboard_async(transport: str = "grpc_asyncio"): +async def test_create_dashboard_async( + transport: str = "grpc_asyncio", + request_type=dashboards_service.CreateDashboardRequest, +): client = DashboardsServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = dashboards_service.CreateDashboardRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.create_dashboard), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_dashboard), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( dashboard.Dashboard( @@ -434,7 +533,7 @@ async def test_create_dashboard_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == dashboards_service.CreateDashboardRequest() # Establish that the response is the type that we expect. assert isinstance(response, dashboard.Dashboard) @@ -446,6 +545,11 @@ async def test_create_dashboard_async(transport: str = "grpc_asyncio"): assert response.etag == "etag_value" +@pytest.mark.asyncio +async def test_create_dashboard_async_from_dict(): + await test_create_dashboard_async(request_type=dict) + + def test_create_dashboard_field_headers(): client = DashboardsServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -455,9 +559,7 @@ def test_create_dashboard_field_headers(): request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._transport.create_dashboard), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_dashboard), "__call__") as call: call.return_value = dashboard.Dashboard() client.create_dashboard(request) @@ -484,9 +586,7 @@ async def test_create_dashboard_field_headers_async(): request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.create_dashboard), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_dashboard), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dashboard.Dashboard()) await client.create_dashboard(request) @@ -501,17 +601,19 @@ async def test_create_dashboard_field_headers_async(): assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] -def test_list_dashboards(transport: str = "grpc"): +def test_list_dashboards( + transport: str = "grpc", request_type=dashboards_service.ListDashboardsRequest +): client = DashboardsServiceClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = dashboards_service.ListDashboardsRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_dashboards), "__call__") as call: + with mock.patch.object(type(client.transport.list_dashboards), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = dashboards_service.ListDashboardsResponse( next_page_token="next_page_token_value", @@ -523,28 +625,34 @@ def test_list_dashboards(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == dashboards_service.ListDashboardsRequest() # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDashboardsPager) assert response.next_page_token == "next_page_token_value" +def test_list_dashboards_from_dict(): + test_list_dashboards(request_type=dict) + + @pytest.mark.asyncio -async def test_list_dashboards_async(transport: str = "grpc_asyncio"): +async def test_list_dashboards_async( + transport: str = "grpc_asyncio", + request_type=dashboards_service.ListDashboardsRequest, +): client = DashboardsServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = dashboards_service.ListDashboardsRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_dashboards), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_dashboards), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( dashboards_service.ListDashboardsResponse( @@ -558,7 +666,7 @@ async def test_list_dashboards_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == dashboards_service.ListDashboardsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListDashboardsAsyncPager) @@ -566,6 +674,11 @@ async def test_list_dashboards_async(transport: str = "grpc_asyncio"): assert response.next_page_token == "next_page_token_value" +@pytest.mark.asyncio +async def test_list_dashboards_async_from_dict(): + await test_list_dashboards_async(request_type=dict) + + def test_list_dashboards_field_headers(): client = DashboardsServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -575,7 +688,7 @@ def test_list_dashboards_field_headers(): request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_dashboards), "__call__") as call: + with mock.patch.object(type(client.transport.list_dashboards), "__call__") as call: call.return_value = dashboards_service.ListDashboardsResponse() client.list_dashboards(request) @@ -602,9 +715,7 @@ async def test_list_dashboards_field_headers_async(): request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_dashboards), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_dashboards), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( dashboards_service.ListDashboardsResponse() ) @@ -625,7 +736,7 @@ def test_list_dashboards_pager(): client = DashboardsServiceClient(credentials=credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_dashboards), "__call__") as call: + with mock.patch.object(type(client.transport.list_dashboards), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( dashboards_service.ListDashboardsResponse( @@ -665,7 +776,7 @@ def test_list_dashboards_pages(): client = DashboardsServiceClient(credentials=credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_dashboards), "__call__") as call: + with mock.patch.object(type(client.transport.list_dashboards), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( dashboards_service.ListDashboardsResponse( @@ -688,8 +799,8 @@ def test_list_dashboards_pages(): RuntimeError, ) pages = list(client.list_dashboards(request={}).pages) - for page, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page.raw_page.next_page_token == token + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token @pytest.mark.asyncio @@ -698,9 +809,7 @@ async def test_list_dashboards_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_dashboards), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_dashboards), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( @@ -739,9 +848,7 @@ async def test_list_dashboards_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_dashboards), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_dashboards), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( @@ -765,23 +872,25 @@ async def test_list_dashboards_async_pages(): RuntimeError, ) pages = [] - async for page in (await client.list_dashboards(request={})).pages: - pages.append(page) - for page, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page.raw_page.next_page_token == token + async for page_ in (await client.list_dashboards(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_get_dashboard(transport: str = "grpc"): +def test_get_dashboard( + transport: str = "grpc", request_type=dashboards_service.GetDashboardRequest +): client = DashboardsServiceClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = dashboards_service.GetDashboardRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_dashboard), "__call__") as call: + with mock.patch.object(type(client.transport.get_dashboard), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = dashboard.Dashboard( name="name_value", @@ -796,9 +905,10 @@ def test_get_dashboard(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == dashboards_service.GetDashboardRequest() # Establish that the response is the type that we expect. + assert isinstance(response, dashboard.Dashboard) assert response.name == "name_value" @@ -808,20 +918,24 @@ def test_get_dashboard(transport: str = "grpc"): assert response.etag == "etag_value" +def test_get_dashboard_from_dict(): + test_get_dashboard(request_type=dict) + + @pytest.mark.asyncio -async def test_get_dashboard_async(transport: str = "grpc_asyncio"): +async def test_get_dashboard_async( + transport: str = "grpc_asyncio", request_type=dashboards_service.GetDashboardRequest +): client = DashboardsServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = dashboards_service.GetDashboardRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_dashboard), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_dashboard), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( dashboard.Dashboard( @@ -835,7 +949,7 @@ async def test_get_dashboard_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == dashboards_service.GetDashboardRequest() # Establish that the response is the type that we expect. assert isinstance(response, dashboard.Dashboard) @@ -847,6 +961,11 @@ async def test_get_dashboard_async(transport: str = "grpc_asyncio"): assert response.etag == "etag_value" +@pytest.mark.asyncio +async def test_get_dashboard_async_from_dict(): + await test_get_dashboard_async(request_type=dict) + + def test_get_dashboard_field_headers(): client = DashboardsServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -856,7 +975,7 @@ def test_get_dashboard_field_headers(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_dashboard), "__call__") as call: + with mock.patch.object(type(client.transport.get_dashboard), "__call__") as call: call.return_value = dashboard.Dashboard() client.get_dashboard(request) @@ -883,9 +1002,7 @@ async def test_get_dashboard_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_dashboard), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_dashboard), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dashboard.Dashboard()) await client.get_dashboard(request) @@ -900,19 +1017,19 @@ async def test_get_dashboard_field_headers_async(): assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] -def test_delete_dashboard(transport: str = "grpc"): +def test_delete_dashboard( + transport: str = "grpc", request_type=dashboards_service.DeleteDashboardRequest +): client = DashboardsServiceClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = dashboards_service.DeleteDashboardRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._transport.delete_dashboard), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_dashboard), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None @@ -922,26 +1039,31 @@ def test_delete_dashboard(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == dashboards_service.DeleteDashboardRequest() # Establish that the response is the type that we expect. assert response is None +def test_delete_dashboard_from_dict(): + test_delete_dashboard(request_type=dict) + + @pytest.mark.asyncio -async def test_delete_dashboard_async(transport: str = "grpc_asyncio"): +async def test_delete_dashboard_async( + transport: str = "grpc_asyncio", + request_type=dashboards_service.DeleteDashboardRequest, +): client = DashboardsServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = dashboards_service.DeleteDashboardRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.delete_dashboard), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_dashboard), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) @@ -951,12 +1073,17 @@ async def test_delete_dashboard_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == dashboards_service.DeleteDashboardRequest() # Establish that the response is the type that we expect. assert response is None +@pytest.mark.asyncio +async def test_delete_dashboard_async_from_dict(): + await test_delete_dashboard_async(request_type=dict) + + def test_delete_dashboard_field_headers(): client = DashboardsServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -966,9 +1093,7 @@ def test_delete_dashboard_field_headers(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._transport.delete_dashboard), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_dashboard), "__call__") as call: call.return_value = None client.delete_dashboard(request) @@ -995,9 +1120,7 @@ async def test_delete_dashboard_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.delete_dashboard), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_dashboard), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_dashboard(request) @@ -1012,19 +1135,19 @@ async def test_delete_dashboard_field_headers_async(): assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] -def test_update_dashboard(transport: str = "grpc"): +def test_update_dashboard( + transport: str = "grpc", request_type=dashboards_service.UpdateDashboardRequest +): client = DashboardsServiceClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = dashboards_service.UpdateDashboardRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._transport.update_dashboard), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_dashboard), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = dashboard.Dashboard( name="name_value", @@ -1039,9 +1162,10 @@ def test_update_dashboard(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == dashboards_service.UpdateDashboardRequest() # Establish that the response is the type that we expect. + assert isinstance(response, dashboard.Dashboard) assert response.name == "name_value" @@ -1051,20 +1175,25 @@ def test_update_dashboard(transport: str = "grpc"): assert response.etag == "etag_value" +def test_update_dashboard_from_dict(): + test_update_dashboard(request_type=dict) + + @pytest.mark.asyncio -async def test_update_dashboard_async(transport: str = "grpc_asyncio"): +async def test_update_dashboard_async( + transport: str = "grpc_asyncio", + request_type=dashboards_service.UpdateDashboardRequest, +): client = DashboardsServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = dashboards_service.UpdateDashboardRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.update_dashboard), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_dashboard), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( dashboard.Dashboard( @@ -1078,7 +1207,7 @@ async def test_update_dashboard_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == dashboards_service.UpdateDashboardRequest() # Establish that the response is the type that we expect. assert isinstance(response, dashboard.Dashboard) @@ -1090,6 +1219,11 @@ async def test_update_dashboard_async(transport: str = "grpc_asyncio"): assert response.etag == "etag_value" +@pytest.mark.asyncio +async def test_update_dashboard_async_from_dict(): + await test_update_dashboard_async(request_type=dict) + + def test_update_dashboard_field_headers(): client = DashboardsServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -1099,9 +1233,7 @@ def test_update_dashboard_field_headers(): request.dashboard.name = "dashboard.name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._transport.update_dashboard), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_dashboard), "__call__") as call: call.return_value = dashboard.Dashboard() client.update_dashboard(request) @@ -1130,9 +1262,7 @@ async def test_update_dashboard_field_headers_async(): request.dashboard.name = "dashboard.name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.update_dashboard), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_dashboard), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(dashboard.Dashboard()) await client.update_dashboard(request) @@ -1185,7 +1315,7 @@ def test_transport_instance(): credentials=credentials.AnonymousCredentials(), ) client = DashboardsServiceClient(transport=transport) - assert client._transport is transport + assert client.transport is transport def test_transport_get_channel(): @@ -1203,10 +1333,25 @@ def test_transport_get_channel(): assert channel +@pytest.mark.parametrize( + "transport_class", + [ + transports.DashboardsServiceGrpcTransport, + transports.DashboardsServiceGrpcAsyncIOTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = DashboardsServiceClient(credentials=credentials.AnonymousCredentials(),) - assert isinstance(client._transport, transports.DashboardsServiceGrpcTransport,) + assert isinstance(client.transport, transports.DashboardsServiceGrpcTransport,) def test_dashboards_service_base_transport_error(): @@ -1266,6 +1411,17 @@ def test_dashboards_service_base_transport_with_credentials_file(): ) +def test_dashboards_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(auth, "default") as adc, mock.patch( + "google.cloud.monitoring_dashboard_v1.services.dashboards_service.transports.DashboardsServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.DashboardsServiceTransport() + adc.assert_called_once() + + def test_dashboards_service_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(auth, "default") as adc: @@ -1308,7 +1464,7 @@ def test_dashboards_service_host_no_port(): api_endpoint="monitoring.googleapis.com" ), ) - assert client._transport._host == "monitoring.googleapis.com:443" + assert client.transport._host == "monitoring.googleapis.com:443" def test_dashboards_service_host_with_port(): @@ -1318,205 +1474,129 @@ def test_dashboards_service_host_with_port(): api_endpoint="monitoring.googleapis.com:8000" ), ) - assert client._transport._host == "monitoring.googleapis.com:8000" + assert client.transport._host == "monitoring.googleapis.com:8000" def test_dashboards_service_grpc_transport_channel(): channel = grpc.insecure_channel("http://localhost/") - # Check that if channel is provided, mtls endpoint and client_cert_source - # won't be used. - callback = mock.MagicMock() + # Check that channel is used if provided. transport = transports.DashboardsServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=callback, + host="squid.clam.whelk", channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" - assert not callback.called + assert transport._ssl_channel_credentials == None def test_dashboards_service_grpc_asyncio_transport_channel(): channel = aio.insecure_channel("http://localhost/") - # Check that if channel is provided, mtls endpoint and client_cert_source - # won't be used. - callback = mock.MagicMock() + # Check that channel is used if provided. transport = transports.DashboardsServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=callback, + host="squid.clam.whelk", channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" - assert not callback.called - - -@mock.patch("grpc.ssl_channel_credentials", autospec=True) -@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) -def test_dashboards_service_grpc_transport_channel_mtls_with_client_cert_source( - grpc_create_channel, grpc_ssl_channel_cred -): - # Check that if channel is None, but api_mtls_endpoint and client_cert_source - # are provided, then a mTLS channel will be created. - mock_cred = mock.Mock() - - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - transport = transports.DashboardsServiceGrpcTransport( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/monitoring", - "https://www.googleapis.com/auth/monitoring.read", - "https://www.googleapis.com/auth/monitoring.write", - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - ) - assert transport.grpc_channel == mock_grpc_channel - - -@mock.patch("grpc.ssl_channel_credentials", autospec=True) -@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) -def test_dashboards_service_grpc_asyncio_transport_channel_mtls_with_client_cert_source( - grpc_create_channel, grpc_ssl_channel_cred -): - # Check that if channel is None, but api_mtls_endpoint and client_cert_source - # are provided, then a mTLS channel will be created. - mock_cred = mock.Mock() - - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - transport = transports.DashboardsServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/monitoring", - "https://www.googleapis.com/auth/monitoring.read", - "https://www.googleapis.com/auth/monitoring.write", - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - ) - assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == None @pytest.mark.parametrize( - "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] + "transport_class", + [ + transports.DashboardsServiceGrpcTransport, + transports.DashboardsServiceGrpcAsyncIOTransport, + ], ) -@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) -def test_dashboards_service_grpc_transport_channel_mtls_with_adc( - grpc_create_channel, api_mtls_endpoint +def test_dashboards_service_transport_channel_mtls_with_client_cert_source( + transport_class, ): - # Check that if channel and client_cert_source are None, but api_mtls_endpoint - # is provided, then a mTLS channel will be created with SSL ADC. - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - # Mock google.auth.transport.grpc.SslCredentials class. - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - mock_cred = mock.Mock() - transport = transports.DashboardsServiceGrpcTransport( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint=api_mtls_endpoint, - client_cert_source=None, - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/monitoring", - "https://www.googleapis.com/auth/monitoring.read", - "https://www.googleapis.com/auth/monitoring.write", - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - ) - assert transport.grpc_channel == mock_grpc_channel + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + "https://www.googleapis.com/auth/monitoring.write", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred @pytest.mark.parametrize( - "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] + "transport_class", + [ + transports.DashboardsServiceGrpcTransport, + transports.DashboardsServiceGrpcAsyncIOTransport, + ], ) -@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) -def test_dashboards_service_grpc_asyncio_transport_channel_mtls_with_adc( - grpc_create_channel, api_mtls_endpoint -): - # Check that if channel and client_cert_source are None, but api_mtls_endpoint - # is provided, then a mTLS channel will be created with SSL ADC. - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - # Mock google.auth.transport.grpc.SslCredentials class. +def test_dashboards_service_transport_channel_mtls_with_adc(transport_class): mock_ssl_cred = mock.Mock() with mock.patch.multiple( "google.auth.transport.grpc.SslCredentials", __init__=mock.Mock(return_value=None), ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), ): - mock_cred = mock.Mock() - transport = transports.DashboardsServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint=api_mtls_endpoint, - client_cert_source=None, - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/monitoring", - "https://www.googleapis.com/auth/monitoring.read", - "https://www.googleapis.com/auth/monitoring.write", - ), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - ) - assert transport.grpc_channel == mock_grpc_channel + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + "https://www.googleapis.com/auth/monitoring.write", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel def test_dashboard_path(): @@ -1540,3 +1620,125 @@ def test_parse_dashboard_path(): # Check that the path construction is reversible. actual = DashboardsServiceClient.parse_dashboard_path(path) assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "oyster" + + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = DashboardsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = DashboardsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DashboardsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "cuttlefish" + + expected = "folders/{folder}".format(folder=folder,) + actual = DashboardsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = DashboardsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DashboardsServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "winkle" + + expected = "organizations/{organization}".format(organization=organization,) + actual = DashboardsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = DashboardsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DashboardsServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "scallop" + + expected = "projects/{project}".format(project=project,) + actual = DashboardsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = DashboardsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DashboardsServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "squid" + location = "clam" + + expected = "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + actual = DashboardsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = DashboardsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DashboardsServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.DashboardsServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = DashboardsServiceClient( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.DashboardsServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = DashboardsServiceClient.get_transport_class() + transport = transport_class( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info)