diff --git a/packages/google-cloud-data-qna/google/cloud/dataqna/__init__.py b/packages/google-cloud-data-qna/google/cloud/dataqna/__init__.py index 15c865bec900..c4b824e038b6 100644 --- a/packages/google-cloud-data-qna/google/cloud/dataqna/__init__.py +++ b/packages/google-cloud-data-qna/google/cloud/dataqna/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,38 +14,39 @@ # limitations under the License. # -from google.cloud.dataqna_v1alpha.services.auto_suggestion_service.async_client import ( - AutoSuggestionServiceAsyncClient, -) from google.cloud.dataqna_v1alpha.services.auto_suggestion_service.client import ( AutoSuggestionServiceClient, ) -from google.cloud.dataqna_v1alpha.services.question_service.async_client import ( - QuestionServiceAsyncClient, +from google.cloud.dataqna_v1alpha.services.auto_suggestion_service.async_client import ( + AutoSuggestionServiceAsyncClient, ) from google.cloud.dataqna_v1alpha.services.question_service.client import ( QuestionServiceClient, ) +from google.cloud.dataqna_v1alpha.services.question_service.async_client import ( + QuestionServiceAsyncClient, +) + from google.cloud.dataqna_v1alpha.types.annotated_string import AnnotatedString +from google.cloud.dataqna_v1alpha.types.auto_suggestion_service import Suggestion +from google.cloud.dataqna_v1alpha.types.auto_suggestion_service import SuggestionInfo from google.cloud.dataqna_v1alpha.types.auto_suggestion_service import ( SuggestQueriesRequest, ) from google.cloud.dataqna_v1alpha.types.auto_suggestion_service import ( SuggestQueriesResponse, ) -from google.cloud.dataqna_v1alpha.types.auto_suggestion_service import Suggestion -from google.cloud.dataqna_v1alpha.types.auto_suggestion_service import SuggestionInfo from google.cloud.dataqna_v1alpha.types.auto_suggestion_service import SuggestionType from google.cloud.dataqna_v1alpha.types.question import BigQueryJob from google.cloud.dataqna_v1alpha.types.question import DataQuery from google.cloud.dataqna_v1alpha.types.question import DebugFlags from google.cloud.dataqna_v1alpha.types.question import ExecutionInfo from google.cloud.dataqna_v1alpha.types.question import HumanReadable -from google.cloud.dataqna_v1alpha.types.question import InterpretEntity -from google.cloud.dataqna_v1alpha.types.question import InterpretError from google.cloud.dataqna_v1alpha.types.question import Interpretation from google.cloud.dataqna_v1alpha.types.question import InterpretationStructure +from google.cloud.dataqna_v1alpha.types.question import InterpretError from google.cloud.dataqna_v1alpha.types.question import Question +from google.cloud.dataqna_v1alpha.types.question import InterpretEntity from google.cloud.dataqna_v1alpha.types.question_service import CreateQuestionRequest from google.cloud.dataqna_v1alpha.types.question_service import ExecuteQuestionRequest from google.cloud.dataqna_v1alpha.types.question_service import GetQuestionRequest @@ -57,30 +57,30 @@ from google.cloud.dataqna_v1alpha.types.user_feedback import UserFeedback __all__ = ( - "AnnotatedString", - "AutoSuggestionServiceAsyncClient", "AutoSuggestionServiceClient", + "AutoSuggestionServiceAsyncClient", + "QuestionServiceClient", + "QuestionServiceAsyncClient", + "AnnotatedString", + "Suggestion", + "SuggestionInfo", + "SuggestQueriesRequest", + "SuggestQueriesResponse", + "SuggestionType", "BigQueryJob", - "CreateQuestionRequest", "DataQuery", "DebugFlags", - "ExecuteQuestionRequest", "ExecutionInfo", - "GetQuestionRequest", - "GetUserFeedbackRequest", "HumanReadable", - "InterpretEntity", - "InterpretError", "Interpretation", "InterpretationStructure", + "InterpretError", "Question", - "QuestionServiceAsyncClient", - "QuestionServiceClient", - "SuggestQueriesRequest", - "SuggestQueriesResponse", - "Suggestion", - "SuggestionInfo", - "SuggestionType", + "InterpretEntity", + "CreateQuestionRequest", + "ExecuteQuestionRequest", + "GetQuestionRequest", + "GetUserFeedbackRequest", "UpdateUserFeedbackRequest", "UserFeedback", ) diff --git a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/__init__.py b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/__init__.py index 37d7ed334d65..46b3227078cf 100644 --- a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/__init__.py +++ b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,23 +15,26 @@ # from .services.auto_suggestion_service import AutoSuggestionServiceClient +from .services.auto_suggestion_service import AutoSuggestionServiceAsyncClient from .services.question_service import QuestionServiceClient +from .services.question_service import QuestionServiceAsyncClient + from .types.annotated_string import AnnotatedString -from .types.auto_suggestion_service import SuggestQueriesRequest -from .types.auto_suggestion_service import SuggestQueriesResponse from .types.auto_suggestion_service import Suggestion from .types.auto_suggestion_service import SuggestionInfo +from .types.auto_suggestion_service import SuggestQueriesRequest +from .types.auto_suggestion_service import SuggestQueriesResponse from .types.auto_suggestion_service import SuggestionType from .types.question import BigQueryJob from .types.question import DataQuery from .types.question import DebugFlags from .types.question import ExecutionInfo from .types.question import HumanReadable -from .types.question import InterpretEntity -from .types.question import InterpretError from .types.question import Interpretation from .types.question import InterpretationStructure +from .types.question import InterpretError from .types.question import Question +from .types.question import InterpretEntity from .types.question_service import CreateQuestionRequest from .types.question_service import ExecuteQuestionRequest from .types.question_service import GetQuestionRequest @@ -40,8 +42,9 @@ from .types.question_service import UpdateUserFeedbackRequest from .types.user_feedback import UserFeedback - __all__ = ( + "AutoSuggestionServiceAsyncClient", + "QuestionServiceAsyncClient", "AnnotatedString", "AutoSuggestionServiceClient", "BigQueryJob", @@ -58,6 +61,7 @@ "Interpretation", "InterpretationStructure", "Question", + "QuestionServiceClient", "SuggestQueriesRequest", "SuggestQueriesResponse", "Suggestion", @@ -65,5 +69,4 @@ "SuggestionType", "UpdateUserFeedbackRequest", "UserFeedback", - "QuestionServiceClient", ) diff --git a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/gapic_metadata.json b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/gapic_metadata.json new file mode 100644 index 000000000000..7ba1907d85de --- /dev/null +++ b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/gapic_metadata.json @@ -0,0 +1,97 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.dataqna_v1alpha", + "protoPackage": "google.cloud.dataqna.v1alpha", + "schema": "1.0", + "services": { + "AutoSuggestionService": { + "clients": { + "grpc": { + "libraryClient": "AutoSuggestionServiceClient", + "rpcs": { + "SuggestQueries": { + "methods": [ + "suggest_queries" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AutoSuggestionServiceAsyncClient", + "rpcs": { + "SuggestQueries": { + "methods": [ + "suggest_queries" + ] + } + } + } + } + }, + "QuestionService": { + "clients": { + "grpc": { + "libraryClient": "QuestionServiceClient", + "rpcs": { + "CreateQuestion": { + "methods": [ + "create_question" + ] + }, + "ExecuteQuestion": { + "methods": [ + "execute_question" + ] + }, + "GetQuestion": { + "methods": [ + "get_question" + ] + }, + "GetUserFeedback": { + "methods": [ + "get_user_feedback" + ] + }, + "UpdateUserFeedback": { + "methods": [ + "update_user_feedback" + ] + } + } + }, + "grpc-async": { + "libraryClient": "QuestionServiceAsyncClient", + "rpcs": { + "CreateQuestion": { + "methods": [ + "create_question" + ] + }, + "ExecuteQuestion": { + "methods": [ + "execute_question" + ] + }, + "GetQuestion": { + "methods": [ + "get_question" + ] + }, + "GetUserFeedback": { + "methods": [ + "get_user_feedback" + ] + }, + "UpdateUserFeedback": { + "methods": [ + "update_user_feedback" + ] + } + } + } + } + } + } +} diff --git a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/__init__.py b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/__init__.py index 42ffdf2bc43d..4de65971c238 100644 --- a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/__init__.py +++ b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/__init__.py b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/__init__.py index 86c7bd3ece8b..36d9bc8b8bf2 100644 --- a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/__init__.py +++ b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import AutoSuggestionServiceClient from .async_client import AutoSuggestionServiceAsyncClient diff --git a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/async_client.py b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/async_client.py index ffb47e553df6..9b631ffee8ab 100644 --- a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/async_client.py +++ b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,14 +20,13 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.dataqna_v1alpha.types import auto_suggestion_service - from .transports.base import AutoSuggestionServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import AutoSuggestionServiceGrpcAsyncIOTransport from .client import AutoSuggestionServiceClient @@ -120,24 +117,20 @@ class AutoSuggestionServiceAsyncClient: parse_common_billing_account_path = staticmethod( AutoSuggestionServiceClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(AutoSuggestionServiceClient.common_folder_path) parse_common_folder_path = staticmethod( AutoSuggestionServiceClient.parse_common_folder_path ) - common_organization_path = staticmethod( AutoSuggestionServiceClient.common_organization_path ) parse_common_organization_path = staticmethod( AutoSuggestionServiceClient.parse_common_organization_path ) - common_project_path = staticmethod(AutoSuggestionServiceClient.common_project_path) parse_common_project_path = staticmethod( AutoSuggestionServiceClient.parse_common_project_path ) - common_location_path = staticmethod( AutoSuggestionServiceClient.common_location_path ) @@ -147,7 +140,8 @@ class AutoSuggestionServiceAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -162,7 +156,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -179,7 +173,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AutoSuggestionServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: AutoSuggestionServiceTransport: The transport used by the client instance. @@ -194,12 +188,12 @@ def transport(self) -> AutoSuggestionServiceTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, AutoSuggestionServiceTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the auto suggestion service client. + """Instantiates the auto suggestion service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -231,7 +225,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = AutoSuggestionServiceClient( credentials=credentials, transport=transport, @@ -253,7 +246,6 @@ async def suggest_queries( Args: request (:class:`google.cloud.dataqna_v1alpha.types.SuggestQueriesRequest`): The request object. Request for query suggestions. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -265,7 +257,6 @@ async def suggest_queries( Response to SuggestQueries. """ # Create or coerce a protobuf request object. - request = auto_suggestion_service.SuggestQueriesRequest(request) # Wrap the RPC method; this adds retry and timeout information, diff --git a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/client.py b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/client.py index 377327c36bce..b2105ef639cc 100644 --- a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/client.py +++ b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,17 +21,16 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.dataqna_v1alpha.types import auto_suggestion_service - from .transports.base import AutoSuggestionServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AutoSuggestionServiceGrpcTransport from .transports.grpc_asyncio import AutoSuggestionServiceGrpcAsyncIOTransport @@ -56,7 +53,7 @@ class AutoSuggestionServiceClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[AutoSuggestionServiceTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -150,7 +147,8 @@ class AutoSuggestionServiceClient(metaclass=AutoSuggestionServiceClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -184,7 +182,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -201,7 +200,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -220,16 +219,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AutoSuggestionServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - AutoSuggestionServiceTransport: The transport used by the client instance. + AutoSuggestionServiceTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -242,7 +242,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -253,7 +253,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -264,7 +264,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -275,7 +275,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -289,12 +289,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, AutoSuggestionServiceTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the auto suggestion service client. + """Instantiates the auto suggestion service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -349,9 +349,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -363,12 +364,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -383,8 +386,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -413,7 +416,6 @@ def suggest_queries( Args: request (google.cloud.dataqna_v1alpha.types.SuggestQueriesRequest): The request object. Request for query suggestions. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -425,7 +427,6 @@ def suggest_queries( Response to SuggestQueries. """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a auto_suggestion_service.SuggestQueriesRequest. # There's no risk of modifying the input as we've already verified diff --git a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/transports/__init__.py b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/transports/__init__.py index f05e7bdde2c1..ef507ef97504 100644 --- a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/transports/__init__.py +++ b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/transports/base.py b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/transports/base.py index 4519ea2d69c3..3cd57ca2167c 100644 --- a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/transports/base.py +++ b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dataqna_v1alpha.types import auto_suggestion_service - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-dataqna",).version, @@ -35,27 +34,41 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class AutoSuggestionServiceTransport(abc.ABC): """Abstract transport class for AutoSuggestionService.""" AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + DEFAULT_HOST: str = "dataqna.googleapis.com" + def __init__( self, *, - host: str = "dataqna.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -64,7 +77,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -78,29 +91,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -112,11 +172,11 @@ def _prep_wrapped_messages(self, client_info): @property def suggest_queries( self, - ) -> typing.Callable[ + ) -> Callable[ [auto_suggestion_service.SuggestQueriesRequest], - typing.Union[ + Union[ auto_suggestion_service.SuggestQueriesResponse, - typing.Awaitable[auto_suggestion_service.SuggestQueriesResponse], + Awaitable[auto_suggestion_service.SuggestQueriesResponse], ], ]: raise NotImplementedError() diff --git a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/transports/grpc.py b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/transports/grpc.py index d934e18cbff8..2a364c3231d0 100644 --- a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/transports/grpc.py +++ b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,18 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union 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 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.dataqna_v1alpha.types import auto_suggestion_service - from .base import AutoSuggestionServiceTransport, DEFAULT_CLIENT_INFO @@ -120,7 +117,7 @@ def __init__( self, *, host: str = "dataqna.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -134,7 +131,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -244,7 +242,7 @@ def __init__( def create_channel( cls, host: str = "dataqna.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -275,13 +273,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) diff --git a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/transports/grpc_asyncio.py b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/transports/grpc_asyncio.py index bb3f13678cf3..f10da78f4183 100644 --- a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,19 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union 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 import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dataqna_v1alpha.types import auto_suggestion_service - from .base import AutoSuggestionServiceTransport, DEFAULT_CLIENT_INFO from .grpc import AutoSuggestionServiceGrpcTransport @@ -123,7 +120,7 @@ class AutoSuggestionServiceGrpcAsyncIOTransport(AutoSuggestionServiceTransport): def create_channel( cls, host: str = "dataqna.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -150,13 +147,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -164,7 +163,7 @@ def __init__( self, *, host: str = "dataqna.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -178,7 +177,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -236,7 +236,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint diff --git a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/__init__.py b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/__init__.py index 9626dd05acec..8de2e92ef22c 100644 --- a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/__init__.py +++ b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import QuestionServiceClient from .async_client import QuestionServiceAsyncClient diff --git a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/async_client.py b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/async_client.py index 9aa5868769dc..12bbfc3c4acd 100644 --- a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/async_client.py +++ b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.dataqna_v1alpha.types import question @@ -33,10 +31,9 @@ from google.cloud.dataqna_v1alpha.types import question_service from google.cloud.dataqna_v1alpha.types import user_feedback from google.cloud.dataqna_v1alpha.types import user_feedback as gcd_user_feedback -from google.protobuf import any_pb2 as gp_any # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import QuestionServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import QuestionServiceGrpcAsyncIOTransport from .client import QuestionServiceClient @@ -73,31 +70,26 @@ class QuestionServiceAsyncClient: parse_user_feedback_path = staticmethod( QuestionServiceClient.parse_user_feedback_path ) - common_billing_account_path = staticmethod( QuestionServiceClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( QuestionServiceClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(QuestionServiceClient.common_folder_path) parse_common_folder_path = staticmethod( QuestionServiceClient.parse_common_folder_path ) - common_organization_path = staticmethod( QuestionServiceClient.common_organization_path ) parse_common_organization_path = staticmethod( QuestionServiceClient.parse_common_organization_path ) - common_project_path = staticmethod(QuestionServiceClient.common_project_path) parse_common_project_path = staticmethod( QuestionServiceClient.parse_common_project_path ) - common_location_path = staticmethod(QuestionServiceClient.common_location_path) parse_common_location_path = staticmethod( QuestionServiceClient.parse_common_location_path @@ -105,7 +97,8 @@ class QuestionServiceAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -120,7 +113,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -137,7 +130,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> QuestionServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: QuestionServiceTransport: The transport used by the client instance. @@ -151,12 +144,12 @@ def transport(self) -> QuestionServiceTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, QuestionServiceTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the question service client. + """Instantiates the question service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -188,7 +181,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = QuestionServiceClient( credentials=credentials, transport=transport, @@ -218,7 +210,6 @@ async def get_question( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -248,7 +239,6 @@ async def get_question( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -301,7 +291,6 @@ async def create_question( This corresponds to the ``question`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -331,7 +320,6 @@ async def create_question( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if question is not None: @@ -387,7 +375,6 @@ async def execute_question( This corresponds to the ``interpretation_index`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -417,7 +404,6 @@ async def execute_question( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if interpretation_index is not None: @@ -466,7 +452,6 @@ async def get_user_feedback( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -491,7 +476,6 @@ async def get_user_feedback( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -520,7 +504,7 @@ async def update_user_feedback( request: question_service.UpdateUserFeedbackRequest = None, *, user_feedback: gcd_user_feedback.UserFeedback = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -547,7 +531,6 @@ async def update_user_feedback( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -572,7 +555,6 @@ async def update_user_feedback( # If we have keyword arguments corresponding to fields on the # request, apply these. - if user_feedback is not None: request.user_feedback = user_feedback if update_mask is not None: diff --git a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/client.py b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/client.py index ce674a1c224a..1d77cec80d16 100644 --- a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/client.py +++ b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -37,10 +35,9 @@ from google.cloud.dataqna_v1alpha.types import question_service from google.cloud.dataqna_v1alpha.types import user_feedback from google.cloud.dataqna_v1alpha.types import user_feedback as gcd_user_feedback -from google.protobuf import any_pb2 as gp_any # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import QuestionServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import QuestionServiceGrpcTransport from .transports.grpc_asyncio import QuestionServiceGrpcAsyncIOTransport @@ -61,7 +58,7 @@ class QuestionServiceClientMeta(type): _transport_registry["grpc_asyncio"] = QuestionServiceGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[QuestionServiceTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -101,7 +98,8 @@ class QuestionServiceClient(metaclass=QuestionServiceClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -135,7 +133,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -152,7 +151,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -171,23 +170,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> QuestionServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - QuestionServiceTransport: The transport used by the client instance. + QuestionServiceTransport: The transport used by the client + instance. """ return self._transport @staticmethod def question_path(project: str, location: str, question: str,) -> str: - """Return a fully-qualified question string.""" + """Returns a fully-qualified question string.""" return "projects/{project}/locations/{location}/questions/{question}".format( project=project, location=location, question=question, ) @staticmethod def parse_question_path(path: str) -> Dict[str, str]: - """Parse a question path into its component segments.""" + """Parses a question path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/questions/(?P.+?)$", path, @@ -196,14 +196,14 @@ def parse_question_path(path: str) -> Dict[str, str]: @staticmethod def user_feedback_path(project: str, location: str, question: str,) -> str: - """Return a fully-qualified user_feedback string.""" + """Returns a fully-qualified user_feedback string.""" return "projects/{project}/locations/{location}/questions/{question}/userFeedback".format( project=project, location=location, question=question, ) @staticmethod def parse_user_feedback_path(path: str) -> Dict[str, str]: - """Parse a user_feedback path into its component segments.""" + """Parses a user_feedback path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/questions/(?P.+?)/userFeedback$", path, @@ -212,7 +212,7 @@ def parse_user_feedback_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -225,7 +225,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -236,7 +236,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -247,7 +247,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -258,7 +258,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -272,12 +272,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, QuestionServiceTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the question service client. + """Instantiates the question service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -332,9 +332,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -346,12 +347,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -366,8 +369,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -404,7 +407,6 @@ def get_question( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -436,10 +438,8 @@ def get_question( # there are no flattened fields. if not isinstance(request, question_service.GetQuestionRequest): request = question_service.GetQuestionRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -488,7 +488,6 @@ def create_question( This corresponds to the ``question`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -520,10 +519,8 @@ def create_question( # there are no flattened fields. if not isinstance(request, question_service.CreateQuestionRequest): request = question_service.CreateQuestionRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if question is not None: @@ -575,7 +572,6 @@ def execute_question( This corresponds to the ``interpretation_index`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -607,10 +603,8 @@ def execute_question( # there are no flattened fields. if not isinstance(request, question_service.ExecuteQuestionRequest): request = question_service.ExecuteQuestionRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if interpretation_index is not None: @@ -655,7 +649,6 @@ def get_user_feedback( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -682,10 +675,8 @@ def get_user_feedback( # there are no flattened fields. if not isinstance(request, question_service.GetUserFeedbackRequest): request = question_service.GetUserFeedbackRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -710,7 +701,7 @@ def update_user_feedback( request: question_service.UpdateUserFeedbackRequest = None, *, user_feedback: gcd_user_feedback.UserFeedback = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -737,7 +728,6 @@ def update_user_feedback( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -764,10 +754,8 @@ def update_user_feedback( # there are no flattened fields. if not isinstance(request, question_service.UpdateUserFeedbackRequest): request = question_service.UpdateUserFeedbackRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if user_feedback is not None: request.user_feedback = user_feedback if update_mask is not None: diff --git a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/transports/__init__.py b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/transports/__init__.py index 0ecb17ea6f17..dee15dee6561 100644 --- a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/transports/__init__.py +++ b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/transports/base.py b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/transports/base.py index 263632903ecb..b224da2625fc 100644 --- a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/transports/base.py +++ b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,16 +13,17 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dataqna_v1alpha.types import question from google.cloud.dataqna_v1alpha.types import question as gcd_question @@ -31,7 +31,6 @@ from google.cloud.dataqna_v1alpha.types import user_feedback from google.cloud.dataqna_v1alpha.types import user_feedback as gcd_user_feedback - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-dataqna",).version, @@ -39,27 +38,41 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class QuestionServiceTransport(abc.ABC): """Abstract transport class for QuestionService.""" AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + DEFAULT_HOST: str = "dataqna.googleapis.com" + def __init__( self, *, - host: str = "dataqna.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -68,7 +81,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -82,29 +95,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -130,49 +190,46 @@ def _prep_wrapped_messages(self, client_info): @property def get_question( self, - ) -> typing.Callable[ + ) -> Callable[ [question_service.GetQuestionRequest], - typing.Union[question.Question, typing.Awaitable[question.Question]], + Union[question.Question, Awaitable[question.Question]], ]: raise NotImplementedError() @property def create_question( self, - ) -> typing.Callable[ + ) -> Callable[ [question_service.CreateQuestionRequest], - typing.Union[gcd_question.Question, typing.Awaitable[gcd_question.Question]], + Union[gcd_question.Question, Awaitable[gcd_question.Question]], ]: raise NotImplementedError() @property def execute_question( self, - ) -> typing.Callable[ + ) -> Callable[ [question_service.ExecuteQuestionRequest], - typing.Union[question.Question, typing.Awaitable[question.Question]], + Union[question.Question, Awaitable[question.Question]], ]: raise NotImplementedError() @property def get_user_feedback( self, - ) -> typing.Callable[ + ) -> Callable[ [question_service.GetUserFeedbackRequest], - typing.Union[ - user_feedback.UserFeedback, typing.Awaitable[user_feedback.UserFeedback] - ], + Union[user_feedback.UserFeedback, Awaitable[user_feedback.UserFeedback]], ]: raise NotImplementedError() @property def update_user_feedback( self, - ) -> typing.Callable[ + ) -> Callable[ [question_service.UpdateUserFeedbackRequest], - typing.Union[ - gcd_user_feedback.UserFeedback, - typing.Awaitable[gcd_user_feedback.UserFeedback], + Union[ + gcd_user_feedback.UserFeedback, Awaitable[gcd_user_feedback.UserFeedback] ], ]: raise NotImplementedError() diff --git a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/transports/grpc.py b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/transports/grpc.py index 6f06aaa67a96..3fc22e951783 100644 --- a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/transports/grpc.py +++ b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union 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 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore @@ -31,7 +29,6 @@ from google.cloud.dataqna_v1alpha.types import question_service from google.cloud.dataqna_v1alpha.types import user_feedback from google.cloud.dataqna_v1alpha.types import user_feedback as gcd_user_feedback - from .base import QuestionServiceTransport, DEFAULT_CLIENT_INFO @@ -70,7 +67,7 @@ def __init__( self, *, host: str = "dataqna.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -84,7 +81,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -194,7 +192,7 @@ def __init__( def create_channel( cls, host: str = "dataqna.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -225,13 +223,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) diff --git a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/transports/grpc_asyncio.py b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/transports/grpc_asyncio.py index 5da945ce5946..f1d41daccbdc 100644 --- a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union 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 import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore @@ -32,7 +30,6 @@ from google.cloud.dataqna_v1alpha.types import question_service from google.cloud.dataqna_v1alpha.types import user_feedback from google.cloud.dataqna_v1alpha.types import user_feedback as gcd_user_feedback - from .base import QuestionServiceTransport, DEFAULT_CLIENT_INFO from .grpc import QuestionServiceGrpcTransport @@ -73,7 +70,7 @@ class QuestionServiceGrpcAsyncIOTransport(QuestionServiceTransport): def create_channel( cls, host: str = "dataqna.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -100,13 +97,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -114,7 +113,7 @@ def __init__( self, *, host: str = "dataqna.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -128,7 +127,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -186,7 +186,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint diff --git a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/types/__init__.py b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/types/__init__.py index 12e28d531131..df3351a1f68e 100644 --- a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/types/__init__.py +++ b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .annotated_string import AnnotatedString from .auto_suggestion_service import ( Suggestion, diff --git a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/types/annotated_string.py b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/types/annotated_string.py index 826b54185205..c144ec9a0427 100644 --- a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/types/annotated_string.py +++ b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/types/annotated_string.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -91,15 +89,11 @@ class SemanticMarkup(proto.Message): type_ = proto.Field( proto.ENUM, number=1, enum="AnnotatedString.SemanticMarkupType", ) + start_char_index = proto.Field(proto.INT32, number=2,) + length = proto.Field(proto.INT32, number=3,) - start_char_index = proto.Field(proto.INT32, number=2) - - length = proto.Field(proto.INT32, number=3) - - text_formatted = proto.Field(proto.STRING, number=1) - - html_formatted = proto.Field(proto.STRING, number=2) - + text_formatted = proto.Field(proto.STRING, number=1,) + html_formatted = proto.Field(proto.STRING, number=2,) markups = proto.RepeatedField(proto.MESSAGE, number=3, message=SemanticMarkup,) diff --git a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/types/auto_suggestion_service.py b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/types/auto_suggestion_service.py index 453f3fc6044e..075e5535532c 100644 --- a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/types/auto_suggestion_service.py +++ b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/types/auto_suggestion_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,10 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dataqna_v1alpha.types import annotated_string @@ -42,7 +39,6 @@ class SuggestionType(proto.Enum): class SuggestQueriesRequest(proto.Message): r"""Request for query suggestions. - Attributes: parent (str): Required. The parent of the suggestion query @@ -68,18 +64,14 @@ class SuggestQueriesRequest(proto.Message): cut these suggestions off. """ - parent = proto.Field(proto.STRING, number=1) - - scopes = proto.RepeatedField(proto.STRING, number=2) - - query = proto.Field(proto.STRING, number=3) - + parent = proto.Field(proto.STRING, number=1,) + scopes = proto.RepeatedField(proto.STRING, number=2,) + query = proto.Field(proto.STRING, number=3,) suggestion_types = proto.RepeatedField(proto.ENUM, number=4, enum="SuggestionType",) class Suggestion(proto.Message): r"""A suggestion for a query with a ranking score. - Attributes: suggestion_info (google.cloud.dataqna_v1alpha.types.SuggestionInfo): Detailed information about the suggestion. @@ -93,15 +85,12 @@ class Suggestion(proto.Message): """ suggestion_info = proto.Field(proto.MESSAGE, number=1, message="SuggestionInfo",) - - ranking_score = proto.Field(proto.DOUBLE, number=2) - + ranking_score = proto.Field(proto.DOUBLE, number=2,) suggestion_type = proto.Field(proto.ENUM, number=3, enum="SuggestionType",) class SuggestionInfo(proto.Message): r"""Detailed information about the suggestion. - Attributes: annotated_suggestion (google.cloud.dataqna_v1alpha.types.AnnotatedString): Annotations for the suggestion. This provides @@ -148,20 +137,17 @@ class MatchInfo(proto.Message): substring. """ - start_char_index = proto.Field(proto.INT32, number=1) - - length = proto.Field(proto.INT32, number=2) + start_char_index = proto.Field(proto.INT32, number=1,) + length = proto.Field(proto.INT32, number=2,) annotated_suggestion = proto.Field( proto.MESSAGE, number=1, message=annotated_string.AnnotatedString, ) - query_matches = proto.RepeatedField(proto.MESSAGE, number=2, message=MatchInfo,) class SuggestQueriesResponse(proto.Message): r"""Response to SuggestQueries. - Attributes: suggestions (Sequence[google.cloud.dataqna_v1alpha.types.Suggestion]): A list of suggestions. diff --git a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/types/question.py b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/types/question.py index 29de5ea91d37..5d79f864edf2 100644 --- a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/types/question.py +++ b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/types/question.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dataqna_v1alpha.types import annotated_string -from google.protobuf import any_pb2 as gp_any # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.rpc import status_pb2 as status # type: ignore +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module( @@ -105,32 +102,22 @@ class Question(proto.Message): message. """ - name = proto.Field(proto.STRING, number=1) - - scopes = proto.RepeatedField(proto.STRING, number=2) - - query = proto.Field(proto.STRING, number=3) - - data_source_annotations = proto.RepeatedField(proto.STRING, number=4) - + name = proto.Field(proto.STRING, number=1,) + scopes = proto.RepeatedField(proto.STRING, number=2,) + query = proto.Field(proto.STRING, number=3,) + data_source_annotations = proto.RepeatedField(proto.STRING, number=4,) interpret_error = proto.Field(proto.MESSAGE, number=5, message="InterpretError",) - interpretations = proto.RepeatedField( proto.MESSAGE, number=6, message="Interpretation", ) - - create_time = proto.Field(proto.MESSAGE, number=7, message=timestamp.Timestamp,) - - user_email = proto.Field(proto.STRING, number=8) - + create_time = proto.Field(proto.MESSAGE, number=7, message=timestamp_pb2.Timestamp,) + user_email = proto.Field(proto.STRING, number=8,) debug_flags = proto.Field(proto.MESSAGE, number=9, message="DebugFlags",) - - debug_info = proto.Field(proto.MESSAGE, number=10, message=gp_any.Any,) + debug_info = proto.Field(proto.MESSAGE, number=10, message=any_pb2.Any,) class InterpretError(proto.Message): r"""Details on the failure to interpret the question. - Attributes: message (str): Error message explaining why this question @@ -153,7 +140,6 @@ class InterpretErrorCode(proto.Enum): class InterpretErrorDetails(proto.Message): r"""Details on interpretation failure. - Attributes: unsupported_details (google.cloud.dataqna_v1alpha.types.InterpretError.InterpretUnsupportedDetails): Populated if parts of the query are @@ -169,20 +155,17 @@ class InterpretErrorDetails(proto.Message): number=1, message="InterpretError.InterpretUnsupportedDetails", ) - incomplete_query_details = proto.Field( proto.MESSAGE, number=2, message="InterpretError.InterpretIncompleteQueryDetails", ) - ambiguity_details = proto.Field( proto.MESSAGE, number=3, message="InterpretError.InterpretAmbiguityDetails", ) class InterpretUnsupportedDetails(proto.Message): r"""Details about unsupported parts in a query. - Attributes: operators (Sequence[str]): Unsupported operators. For example: median. @@ -190,13 +173,11 @@ class InterpretUnsupportedDetails(proto.Message): Unsupported intents. """ - operators = proto.RepeatedField(proto.STRING, number=1) - - intent = proto.RepeatedField(proto.STRING, number=2) + operators = proto.RepeatedField(proto.STRING, number=1,) + intent = proto.RepeatedField(proto.STRING, number=2,) class InterpretIncompleteQueryDetails(proto.Message): r"""Details about an incomplete query. - Attributes: entities (Sequence[google.cloud.dataqna_v1alpha.types.InterpretEntity]): List of missing interpret entities. @@ -208,12 +189,10 @@ class InterpretAmbiguityDetails(proto.Message): r"""Details about a query that was too ambiguous. Currently, the message has no fields and its presence signals that there was ambiguity. - """ - - message = proto.Field(proto.STRING, number=1) + """ + message = proto.Field(proto.STRING, number=1,) code = proto.Field(proto.ENUM, number=2, enum=InterpretErrorCode,) - details = proto.Field(proto.MESSAGE, number=3, message=InterpretErrorDetails,) @@ -244,12 +223,11 @@ class JobExecutionState(proto.Enum): SUCCEEDED = 3 FAILED = 4 - job_creation_status = proto.Field(proto.MESSAGE, number=1, message=status.Status,) - + job_creation_status = proto.Field( + proto.MESSAGE, number=1, message=status_pb2.Status, + ) job_execution_state = proto.Field(proto.ENUM, number=2, enum=JobExecutionState,) - - create_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) - + create_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) bigquery_job = proto.Field(proto.MESSAGE, number=4, message="BigQueryJob",) @@ -267,16 +245,13 @@ class BigQueryJob(proto.Message): The location where the job is running. """ - job_id = proto.Field(proto.STRING, number=1) - - project_id = proto.Field(proto.STRING, number=2) - - location = proto.Field(proto.STRING, number=3) + job_id = proto.Field(proto.STRING, number=1,) + project_id = proto.Field(proto.STRING, number=2,) + location = proto.Field(proto.STRING, number=3,) class Interpretation(proto.Message): r"""An interpretation of a natural language query. - Attributes: data_sources (Sequence[str]): List of data sources used in the current @@ -305,20 +280,14 @@ class Interpretation(proto.Message): interpretation was requested. """ - data_sources = proto.RepeatedField(proto.STRING, number=1) - - confidence = proto.Field(proto.DOUBLE, number=2) - - unused_phrases = proto.RepeatedField(proto.STRING, number=3) - + data_sources = proto.RepeatedField(proto.STRING, number=1,) + confidence = proto.Field(proto.DOUBLE, number=2,) + unused_phrases = proto.RepeatedField(proto.STRING, number=3,) human_readable = proto.Field(proto.MESSAGE, number=4, message="HumanReadable",) - interpretation_structure = proto.Field( proto.MESSAGE, number=5, message="InterpretationStructure", ) - data_query = proto.Field(proto.MESSAGE, number=6, message="DataQuery",) - execution_info = proto.Field(proto.MESSAGE, number=7, message="ExecutionInfo",) @@ -336,12 +305,11 @@ class DataQuery(proto.Message): backend. """ - sql = proto.Field(proto.STRING, number=1) + sql = proto.Field(proto.STRING, number=1,) class HumanReadable(proto.Message): r"""Human readable interpretation. - Attributes: generated_interpretation (google.cloud.dataqna_v1alpha.types.AnnotatedString): Generated query explaining the @@ -353,7 +321,6 @@ class HumanReadable(proto.Message): generated_interpretation = proto.Field( proto.MESSAGE, number=1, message=annotated_string.AnnotatedString, ) - original_question = proto.Field( proto.MESSAGE, number=2, message=annotated_string.AnnotatedString, ) @@ -394,7 +361,6 @@ class VisualizationType(proto.Enum): class ColumnInfo(proto.Message): r"""Information about a column. - Attributes: output_alias (str): The alias of the output column as used by the @@ -405,20 +371,17 @@ class ColumnInfo(proto.Message): Human readable name of the output column. """ - output_alias = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) + output_alias = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) visualization_types = proto.RepeatedField( proto.ENUM, number=1, enum=VisualizationType, ) - column_info = proto.RepeatedField(proto.MESSAGE, number=2, message=ColumnInfo,) class DebugFlags(proto.Message): r"""Configuriation of debug flags. - Attributes: include_va_query (bool): Whether to include the original VAQuery. @@ -459,29 +422,18 @@ class DebugFlags(proto.Message): Whether to include the domain list. """ - include_va_query = proto.Field(proto.BOOL, number=1) - - include_nested_va_query = proto.Field(proto.BOOL, number=2) - - include_human_interpretation = proto.Field(proto.BOOL, number=3) - - include_aqua_debug_response = proto.Field(proto.BOOL, number=4) - - time_override = proto.Field(proto.INT64, number=5) - - is_internal_google_user = proto.Field(proto.BOOL, number=6) - - ignore_cache = proto.Field(proto.BOOL, number=7) - - include_search_entities_rpc = proto.Field(proto.BOOL, number=8) - - include_list_column_annotations_rpc = proto.Field(proto.BOOL, number=9) - - include_virtual_analyst_entities = proto.Field(proto.BOOL, number=10) - - include_table_list = proto.Field(proto.BOOL, number=11) - - include_domain_list = proto.Field(proto.BOOL, number=12) + include_va_query = proto.Field(proto.BOOL, number=1,) + include_nested_va_query = proto.Field(proto.BOOL, number=2,) + include_human_interpretation = proto.Field(proto.BOOL, number=3,) + include_aqua_debug_response = proto.Field(proto.BOOL, number=4,) + time_override = proto.Field(proto.INT64, number=5,) + is_internal_google_user = proto.Field(proto.BOOL, number=6,) + ignore_cache = proto.Field(proto.BOOL, number=7,) + include_search_entities_rpc = proto.Field(proto.BOOL, number=8,) + include_list_column_annotations_rpc = proto.Field(proto.BOOL, number=9,) + include_virtual_analyst_entities = proto.Field(proto.BOOL, number=10,) + include_table_list = proto.Field(proto.BOOL, number=11,) + include_domain_list = proto.Field(proto.BOOL, number=12,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/types/question_service.py b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/types/question_service.py index 9cf3ccc4c2b6..d23c0d97d3ac 100644 --- a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/types/question_service.py +++ b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/types/question_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,13 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dataqna_v1alpha.types import question as gcd_question from google.cloud.dataqna_v1alpha.types import user_feedback as gcd_user_feedback -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -37,7 +34,6 @@ class GetQuestionRequest(proto.Message): r"""A request to get a previously created question. - Attributes: name (str): Required. The unique identifier for the question. Example: @@ -46,14 +42,12 @@ class GetQuestionRequest(proto.Message): The list of fields to be retrieved. """ - name = proto.Field(proto.STRING, number=1) - - read_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + name = proto.Field(proto.STRING, number=1,) + read_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask,) class CreateQuestionRequest(proto.Message): r"""Request to create a question resource. - Attributes: parent (str): Required. The name of the project this data source reference @@ -62,14 +56,12 @@ class CreateQuestionRequest(proto.Message): Required. The question to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) question = proto.Field(proto.MESSAGE, number=2, message=gcd_question.Question,) class ExecuteQuestionRequest(proto.Message): r"""Request to execute an interpretation. - Attributes: name (str): Required. The unique identifier for the question. Example: @@ -79,14 +71,12 @@ class ExecuteQuestionRequest(proto.Message): execute. """ - name = proto.Field(proto.STRING, number=1) - - interpretation_index = proto.Field(proto.INT32, number=2) + name = proto.Field(proto.STRING, number=1,) + interpretation_index = proto.Field(proto.INT32, number=2,) class GetUserFeedbackRequest(proto.Message): r"""Request to get user feedback. - Attributes: name (str): Required. The unique identifier for the user feedback. User @@ -94,12 +84,11 @@ class GetUserFeedbackRequest(proto.Message): ``projects/foo/locations/bar/questions/1234/userFeedback`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class UpdateUserFeedbackRequest(proto.Message): r"""Request to updates user feedback. - Attributes: user_feedback (google.cloud.dataqna_v1alpha.types.UserFeedback): Required. The user feedback to update. This @@ -114,8 +103,9 @@ class UpdateUserFeedbackRequest(proto.Message): user_feedback = proto.Field( proto.MESSAGE, number=1, message=gcd_user_feedback.UserFeedback, ) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/types/user_feedback.py b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/types/user_feedback.py index a97f85748a19..8aa69bc816b2 100644 --- a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/types/user_feedback.py +++ b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/types/user_feedback.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -25,7 +23,6 @@ class UserFeedback(proto.Message): r"""Feedback provided by a user. - Attributes: name (str): Required. The unique identifier for the user feedback. User @@ -43,10 +40,8 @@ class UserFeedbackRating(proto.Enum): POSITIVE = 1 NEGATIVE = 2 - name = proto.Field(proto.STRING, number=1) - - free_form_feedback = proto.Field(proto.STRING, number=2) - + name = proto.Field(proto.STRING, number=1,) + free_form_feedback = proto.Field(proto.STRING, number=2,) rating = proto.Field(proto.ENUM, number=3, enum=UserFeedbackRating,) diff --git a/packages/google-cloud-data-qna/scripts/fixup_dataqna_v1alpha_keywords.py b/packages/google-cloud-data-qna/scripts/fixup_dataqna_v1alpha_keywords.py index 067042327bdc..da5349a9b4e9 100644 --- a/packages/google-cloud-data-qna/scripts/fixup_dataqna_v1alpha_keywords.py +++ b/packages/google-cloud-data-qna/scripts/fixup_dataqna_v1alpha_keywords.py @@ -1,6 +1,5 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -41,13 +39,12 @@ def partition( class dataqnaCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_question': ('parent', 'question', ), - 'execute_question': ('name', 'interpretation_index', ), - 'get_question': ('name', 'read_mask', ), - 'get_user_feedback': ('name', ), - 'suggest_queries': ('parent', 'scopes', 'query', 'suggestion_types', ), - 'update_user_feedback': ('user_feedback', 'update_mask', ), - + 'create_question': ('parent', 'question', ), + 'execute_question': ('name', 'interpretation_index', ), + 'get_question': ('name', 'read_mask', ), + 'get_user_feedback': ('name', ), + 'suggest_queries': ('parent', 'scopes', 'query', 'suggestion_types', ), + 'update_user_feedback': ('user_feedback', 'update_mask', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -78,7 +75,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +cst.Element(value=arg.value) ) # Note: the args + kwargs looks silly, but keep in mind that # the control parameters had to be stripped out, and that diff --git a/packages/google-cloud-data-qna/tests/__init__.py b/packages/google-cloud-data-qna/tests/__init__.py new file mode 100644 index 000000000000..4de65971c238 --- /dev/null +++ b/packages/google-cloud-data-qna/tests/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/packages/google-cloud-data-qna/tests/unit/__init__.py b/packages/google-cloud-data-qna/tests/unit/__init__.py new file mode 100644 index 000000000000..4de65971c238 --- /dev/null +++ b/packages/google-cloud-data-qna/tests/unit/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/packages/google-cloud-data-qna/tests/unit/gapic/__init__.py b/packages/google-cloud-data-qna/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..4de65971c238 --- /dev/null +++ b/packages/google-cloud-data-qna/tests/unit/gapic/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/packages/google-cloud-data-qna/tests/unit/gapic/dataqna_v1alpha/__init__.py b/packages/google-cloud-data-qna/tests/unit/gapic/dataqna_v1alpha/__init__.py index 42ffdf2bc43d..4de65971c238 100644 --- a/packages/google-cloud-data-qna/tests/unit/gapic/dataqna_v1alpha/__init__.py +++ b/packages/google-cloud-data-qna/tests/unit/gapic/dataqna_v1alpha/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/packages/google-cloud-data-qna/tests/unit/gapic/dataqna_v1alpha/test_auto_suggestion_service.py b/packages/google-cloud-data-qna/tests/unit/gapic/dataqna_v1alpha/test_auto_suggestion_service.py index 2880a630b7fd..daacdbab52a8 100644 --- a/packages/google-cloud-data-qna/tests/unit/gapic/dataqna_v1alpha/test_auto_suggestion_service.py +++ b/packages/google-cloud-data-qna/tests/unit/gapic/dataqna_v1alpha/test_auto_suggestion_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,13 +23,13 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dataqna_v1alpha.services.auto_suggestion_service import ( AutoSuggestionServiceAsyncClient, @@ -39,8 +38,38 @@ AutoSuggestionServiceClient, ) from google.cloud.dataqna_v1alpha.services.auto_suggestion_service import transports +from google.cloud.dataqna_v1alpha.services.auto_suggestion_service.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dataqna_v1alpha.services.auto_suggestion_service.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dataqna_v1alpha.types import auto_suggestion_service from google.oauth2 import service_account +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -92,7 +121,7 @@ def test__get_default_mtls_endpoint(): "client_class", [AutoSuggestionServiceClient, AutoSuggestionServiceAsyncClient,] ) def test_auto_suggestion_service_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -109,7 +138,7 @@ def test_auto_suggestion_service_client_from_service_account_info(client_class): "client_class", [AutoSuggestionServiceClient, AutoSuggestionServiceAsyncClient,] ) def test_auto_suggestion_service_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -166,7 +195,7 @@ def test_auto_suggestion_service_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(AutoSuggestionServiceClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -472,7 +501,7 @@ def test_suggest_queries( transport: str = "grpc", request_type=auto_suggestion_service.SuggestQueriesRequest ): client = AutoSuggestionServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -483,17 +512,14 @@ def test_suggest_queries( with mock.patch.object(type(client.transport.suggest_queries), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = auto_suggestion_service.SuggestQueriesResponse() - response = client.suggest_queries(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == auto_suggestion_service.SuggestQueriesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, auto_suggestion_service.SuggestQueriesResponse) @@ -505,7 +531,7 @@ def test_suggest_queries_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AutoSuggestionServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -513,7 +539,6 @@ def test_suggest_queries_empty_call(): client.suggest_queries() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == auto_suggestion_service.SuggestQueriesRequest() @@ -523,7 +548,7 @@ async def test_suggest_queries_async( request_type=auto_suggestion_service.SuggestQueriesRequest, ): client = AutoSuggestionServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -536,13 +561,11 @@ async def test_suggest_queries_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( auto_suggestion_service.SuggestQueriesResponse() ) - response = await client.suggest_queries(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == auto_suggestion_service.SuggestQueriesRequest() # Establish that the response is the type that we expect. @@ -556,18 +579,18 @@ async def test_suggest_queries_async_from_dict(): def test_suggest_queries_field_headers(): client = AutoSuggestionServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = auto_suggestion_service.SuggestQueriesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.suggest_queries), "__call__") as call: call.return_value = auto_suggestion_service.SuggestQueriesResponse() - client.suggest_queries(request) # Establish that the underlying gRPC stub method was called. @@ -583,12 +606,13 @@ def test_suggest_queries_field_headers(): @pytest.mark.asyncio async def test_suggest_queries_field_headers_async(): client = AutoSuggestionServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = auto_suggestion_service.SuggestQueriesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -596,7 +620,6 @@ async def test_suggest_queries_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( auto_suggestion_service.SuggestQueriesResponse() ) - await client.suggest_queries(request) # Establish that the underlying gRPC stub method was called. @@ -612,16 +635,16 @@ async def test_suggest_queries_field_headers_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.AutoSuggestionServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AutoSuggestionServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.AutoSuggestionServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AutoSuggestionServiceClient( @@ -631,7 +654,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.AutoSuggestionServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AutoSuggestionServiceClient( @@ -642,7 +665,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.AutoSuggestionServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = AutoSuggestionServiceClient(transport=transport) assert client.transport is transport @@ -651,13 +674,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.AutoSuggestionServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.AutoSuggestionServiceGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -672,8 +695,8 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() @@ -681,16 +704,16 @@ def test_transport_adc(transport_class): def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = AutoSuggestionServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) assert isinstance(client.transport, transports.AutoSuggestionServiceGrpcTransport,) def test_auto_suggestion_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.AutoSuggestionServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -702,7 +725,7 @@ def test_auto_suggestion_service_base_transport(): ) as Transport: Transport.return_value = None transport = transports.AutoSuggestionServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -713,15 +736,37 @@ def test_auto_suggestion_service_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_auto_suggestion_service_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dataqna_v1alpha.services.auto_suggestion_service.transports.AutoSuggestionServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AutoSuggestionServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_auto_suggestion_service_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.dataqna_v1alpha.services.auto_suggestion_service.transports.AutoSuggestionServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AutoSuggestionServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -734,19 +779,33 @@ def test_auto_suggestion_service_base_transport_with_credentials_file(): def test_auto_suggestion_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( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dataqna_v1alpha.services.auto_suggestion_service.transports.AutoSuggestionServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AutoSuggestionServiceTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_auto_suggestion_service_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AutoSuggestionServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_auto_suggestion_service_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) AutoSuggestionServiceClient() adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), @@ -754,20 +813,158 @@ def test_auto_suggestion_service_auth_adc(): ) -def test_auto_suggestion_service_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.AutoSuggestionServiceGrpcTransport, + transports.AutoSuggestionServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_auto_suggestion_service_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.AutoSuggestionServiceGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AutoSuggestionServiceGrpcTransport, + transports.AutoSuggestionServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_auto_suggestion_service_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AutoSuggestionServiceGrpcTransport, grpc_helpers), + (transports.AutoSuggestionServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_auto_suggestion_service_transport_create_channel( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dataqna.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="dataqna.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AutoSuggestionServiceGrpcTransport, grpc_helpers), + (transports.AutoSuggestionServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_auto_suggestion_service_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dataqna.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AutoSuggestionServiceGrpcTransport, grpc_helpers), + (transports.AutoSuggestionServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_auto_suggestion_service_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dataqna.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -778,7 +975,7 @@ def test_auto_suggestion_service_transport_auth_adc(): def test_auto_suggestion_service_grpc_transport_client_cert_source_for_mtls( transport_class, ): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -817,7 +1014,7 @@ def test_auto_suggestion_service_grpc_transport_client_cert_source_for_mtls( def test_auto_suggestion_service_host_no_port(): client = AutoSuggestionServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dataqna.googleapis.com" ), @@ -827,7 +1024,7 @@ def test_auto_suggestion_service_host_no_port(): def test_auto_suggestion_service_host_with_port(): client = AutoSuggestionServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dataqna.googleapis.com:8000" ), @@ -883,9 +1080,9 @@ def test_auto_suggestion_service_transport_channel_mtls_with_client_cert_source( mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -961,7 +1158,6 @@ def test_auto_suggestion_service_transport_channel_mtls_with_adc(transport_class def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -982,7 +1178,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = AutoSuggestionServiceClient.common_folder_path(folder) assert expected == actual @@ -1001,7 +1196,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = AutoSuggestionServiceClient.common_organization_path(organization) assert expected == actual @@ -1020,7 +1214,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = AutoSuggestionServiceClient.common_project_path(project) assert expected == actual @@ -1040,7 +1233,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1067,7 +1259,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.AutoSuggestionServiceTransport, "_prep_wrapped_messages" ) as prep: client = AutoSuggestionServiceClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1076,6 +1268,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = AutoSuggestionServiceClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/packages/google-cloud-data-qna/tests/unit/gapic/dataqna_v1alpha/test_question_service.py b/packages/google-cloud-data-qna/tests/unit/gapic/dataqna_v1alpha/test_question_service.py index 52ffbb8285a9..34d4d3bd16aa 100644 --- a/packages/google-cloud-data-qna/tests/unit/gapic/dataqna_v1alpha/test_question_service.py +++ b/packages/google-cloud-data-qna/tests/unit/gapic/dataqna_v1alpha/test_question_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,19 +23,25 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dataqna_v1alpha.services.question_service import ( QuestionServiceAsyncClient, ) from google.cloud.dataqna_v1alpha.services.question_service import QuestionServiceClient from google.cloud.dataqna_v1alpha.services.question_service import transports +from google.cloud.dataqna_v1alpha.services.question_service.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dataqna_v1alpha.services.question_service.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dataqna_v1alpha.types import annotated_string from google.cloud.dataqna_v1alpha.types import question from google.cloud.dataqna_v1alpha.types import question as gcd_question @@ -44,10 +49,34 @@ from google.cloud.dataqna_v1alpha.types import user_feedback from google.cloud.dataqna_v1alpha.types import user_feedback as gcd_user_feedback from google.oauth2 import service_account -from google.protobuf import any_pb2 as gp_any # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.rpc import status_pb2 as status # type: ignore +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -98,7 +127,7 @@ def test__get_default_mtls_endpoint(): "client_class", [QuestionServiceClient, QuestionServiceAsyncClient,] ) def test_question_service_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -115,7 +144,7 @@ def test_question_service_client_from_service_account_info(client_class): "client_class", [QuestionServiceClient, QuestionServiceAsyncClient,] ) def test_question_service_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -168,7 +197,7 @@ def test_question_service_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(QuestionServiceClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -466,7 +495,7 @@ def test_get_question( transport: str = "grpc", request_type=question_service.GetQuestionRequest ): client = QuestionServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -483,27 +512,19 @@ def test_get_question( data_source_annotations=["data_source_annotations_value"], user_email="user_email_value", ) - response = client.get_question(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == question_service.GetQuestionRequest() # Establish that the response is the type that we expect. - assert isinstance(response, question.Question) - assert response.name == "name_value" - assert response.scopes == ["scopes_value"] - assert response.query == "query_value" - assert response.data_source_annotations == ["data_source_annotations_value"] - assert response.user_email == "user_email_value" @@ -515,7 +536,7 @@ def test_get_question_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = QuestionServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -523,7 +544,6 @@ def test_get_question_empty_call(): client.get_question() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == question_service.GetQuestionRequest() @@ -532,7 +552,7 @@ async def test_get_question_async( transport: str = "grpc_asyncio", request_type=question_service.GetQuestionRequest ): client = QuestionServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -551,26 +571,19 @@ async def test_get_question_async( user_email="user_email_value", ) ) - response = await client.get_question(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == question_service.GetQuestionRequest() # Establish that the response is the type that we expect. assert isinstance(response, question.Question) - assert response.name == "name_value" - assert response.scopes == ["scopes_value"] - assert response.query == "query_value" - assert response.data_source_annotations == ["data_source_annotations_value"] - assert response.user_email == "user_email_value" @@ -580,17 +593,17 @@ async def test_get_question_async_from_dict(): def test_get_question_field_headers(): - client = QuestionServiceClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = question_service.GetQuestionRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_question), "__call__") as call: call.return_value = question.Question() - client.get_question(request) # Establish that the underlying gRPC stub method was called. @@ -605,17 +618,19 @@ def test_get_question_field_headers(): @pytest.mark.asyncio async def test_get_question_field_headers_async(): - client = QuestionServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = question_service.GetQuestionRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_question), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(question.Question()) - await client.get_question(request) # Establish that the underlying gRPC stub method was called. @@ -629,13 +644,12 @@ async def test_get_question_field_headers_async(): def test_get_question_flattened(): - client = QuestionServiceClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_question), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = question.Question() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_question(name="name_value",) @@ -644,12 +658,11 @@ def test_get_question_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_question_flattened_error(): - client = QuestionServiceClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -661,7 +674,9 @@ def test_get_question_flattened_error(): @pytest.mark.asyncio async def test_get_question_flattened_async(): - client = QuestionServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_question), "__call__") as call: @@ -677,13 +692,14 @@ async def test_get_question_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_question_flattened_error_async(): - client = QuestionServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -697,7 +713,7 @@ def test_create_question( transport: str = "grpc", request_type=question_service.CreateQuestionRequest ): client = QuestionServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -714,27 +730,19 @@ def test_create_question( data_source_annotations=["data_source_annotations_value"], user_email="user_email_value", ) - response = client.create_question(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == question_service.CreateQuestionRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_question.Question) - assert response.name == "name_value" - assert response.scopes == ["scopes_value"] - assert response.query == "query_value" - assert response.data_source_annotations == ["data_source_annotations_value"] - assert response.user_email == "user_email_value" @@ -746,7 +754,7 @@ def test_create_question_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = QuestionServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -754,7 +762,6 @@ def test_create_question_empty_call(): client.create_question() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == question_service.CreateQuestionRequest() @@ -763,7 +770,7 @@ async def test_create_question_async( transport: str = "grpc_asyncio", request_type=question_service.CreateQuestionRequest ): client = QuestionServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -782,26 +789,19 @@ async def test_create_question_async( user_email="user_email_value", ) ) - response = await client.create_question(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == question_service.CreateQuestionRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_question.Question) - assert response.name == "name_value" - assert response.scopes == ["scopes_value"] - assert response.query == "query_value" - assert response.data_source_annotations == ["data_source_annotations_value"] - assert response.user_email == "user_email_value" @@ -811,17 +811,17 @@ async def test_create_question_async_from_dict(): def test_create_question_field_headers(): - client = QuestionServiceClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = question_service.CreateQuestionRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_question), "__call__") as call: call.return_value = gcd_question.Question() - client.create_question(request) # Establish that the underlying gRPC stub method was called. @@ -836,11 +836,14 @@ def test_create_question_field_headers(): @pytest.mark.asyncio async def test_create_question_field_headers_async(): - client = QuestionServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = question_service.CreateQuestionRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -848,7 +851,6 @@ async def test_create_question_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_question.Question() ) - await client.create_question(request) # Establish that the underlying gRPC stub method was called. @@ -862,13 +864,12 @@ async def test_create_question_field_headers_async(): def test_create_question_flattened(): - client = QuestionServiceClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_question), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_question.Question() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_question( @@ -879,14 +880,12 @@ def test_create_question_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].question == gcd_question.Question(name="name_value") def test_create_question_flattened_error(): - client = QuestionServiceClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -900,7 +899,9 @@ def test_create_question_flattened_error(): @pytest.mark.asyncio async def test_create_question_flattened_async(): - client = QuestionServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_question), "__call__") as call: @@ -920,15 +921,15 @@ async def test_create_question_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].question == gcd_question.Question(name="name_value") @pytest.mark.asyncio async def test_create_question_flattened_error_async(): - client = QuestionServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -944,7 +945,7 @@ def test_execute_question( transport: str = "grpc", request_type=question_service.ExecuteQuestionRequest ): client = QuestionServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -961,27 +962,19 @@ def test_execute_question( data_source_annotations=["data_source_annotations_value"], user_email="user_email_value", ) - response = client.execute_question(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == question_service.ExecuteQuestionRequest() # Establish that the response is the type that we expect. - assert isinstance(response, question.Question) - assert response.name == "name_value" - assert response.scopes == ["scopes_value"] - assert response.query == "query_value" - assert response.data_source_annotations == ["data_source_annotations_value"] - assert response.user_email == "user_email_value" @@ -993,7 +986,7 @@ def test_execute_question_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = QuestionServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1001,7 +994,6 @@ def test_execute_question_empty_call(): client.execute_question() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == question_service.ExecuteQuestionRequest() @@ -1011,7 +1003,7 @@ async def test_execute_question_async( request_type=question_service.ExecuteQuestionRequest, ): client = QuestionServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1030,26 +1022,19 @@ async def test_execute_question_async( user_email="user_email_value", ) ) - response = await client.execute_question(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == question_service.ExecuteQuestionRequest() # Establish that the response is the type that we expect. assert isinstance(response, question.Question) - assert response.name == "name_value" - assert response.scopes == ["scopes_value"] - assert response.query == "query_value" - assert response.data_source_annotations == ["data_source_annotations_value"] - assert response.user_email == "user_email_value" @@ -1059,17 +1044,17 @@ async def test_execute_question_async_from_dict(): def test_execute_question_field_headers(): - client = QuestionServiceClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = question_service.ExecuteQuestionRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.execute_question), "__call__") as call: call.return_value = question.Question() - client.execute_question(request) # Establish that the underlying gRPC stub method was called. @@ -1084,17 +1069,19 @@ def test_execute_question_field_headers(): @pytest.mark.asyncio async def test_execute_question_field_headers_async(): - client = QuestionServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = question_service.ExecuteQuestionRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.execute_question), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(question.Question()) - await client.execute_question(request) # Establish that the underlying gRPC stub method was called. @@ -1108,13 +1095,12 @@ async def test_execute_question_field_headers_async(): def test_execute_question_flattened(): - client = QuestionServiceClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.execute_question), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = question.Question() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.execute_question( @@ -1125,14 +1111,12 @@ def test_execute_question_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].interpretation_index == 2159 def test_execute_question_flattened_error(): - client = QuestionServiceClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1146,7 +1130,9 @@ def test_execute_question_flattened_error(): @pytest.mark.asyncio async def test_execute_question_flattened_async(): - client = QuestionServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.execute_question), "__call__") as call: @@ -1164,15 +1150,15 @@ async def test_execute_question_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].interpretation_index == 2159 @pytest.mark.asyncio async def test_execute_question_flattened_error_async(): - client = QuestionServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1188,7 +1174,7 @@ def test_get_user_feedback( transport: str = "grpc", request_type=question_service.GetUserFeedbackRequest ): client = QuestionServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1205,23 +1191,17 @@ def test_get_user_feedback( free_form_feedback="free_form_feedback_value", rating=user_feedback.UserFeedback.UserFeedbackRating.POSITIVE, ) - response = client.get_user_feedback(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == question_service.GetUserFeedbackRequest() # Establish that the response is the type that we expect. - assert isinstance(response, user_feedback.UserFeedback) - assert response.name == "name_value" - assert response.free_form_feedback == "free_form_feedback_value" - assert response.rating == user_feedback.UserFeedback.UserFeedbackRating.POSITIVE @@ -1233,7 +1213,7 @@ def test_get_user_feedback_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = QuestionServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1243,7 +1223,6 @@ def test_get_user_feedback_empty_call(): client.get_user_feedback() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == question_service.GetUserFeedbackRequest() @@ -1253,7 +1232,7 @@ async def test_get_user_feedback_async( request_type=question_service.GetUserFeedbackRequest, ): client = QuestionServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1272,22 +1251,17 @@ async def test_get_user_feedback_async( rating=user_feedback.UserFeedback.UserFeedbackRating.POSITIVE, ) ) - response = await client.get_user_feedback(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == question_service.GetUserFeedbackRequest() # Establish that the response is the type that we expect. assert isinstance(response, user_feedback.UserFeedback) - assert response.name == "name_value" - assert response.free_form_feedback == "free_form_feedback_value" - assert response.rating == user_feedback.UserFeedback.UserFeedbackRating.POSITIVE @@ -1297,11 +1271,12 @@ async def test_get_user_feedback_async_from_dict(): def test_get_user_feedback_field_headers(): - client = QuestionServiceClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = question_service.GetUserFeedbackRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1309,7 +1284,6 @@ def test_get_user_feedback_field_headers(): type(client.transport.get_user_feedback), "__call__" ) as call: call.return_value = user_feedback.UserFeedback() - client.get_user_feedback(request) # Establish that the underlying gRPC stub method was called. @@ -1324,11 +1298,14 @@ def test_get_user_feedback_field_headers(): @pytest.mark.asyncio async def test_get_user_feedback_field_headers_async(): - client = QuestionServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = question_service.GetUserFeedbackRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1338,7 +1315,6 @@ async def test_get_user_feedback_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( user_feedback.UserFeedback() ) - await client.get_user_feedback(request) # Establish that the underlying gRPC stub method was called. @@ -1352,7 +1328,7 @@ async def test_get_user_feedback_field_headers_async(): def test_get_user_feedback_flattened(): - client = QuestionServiceClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1360,7 +1336,6 @@ def test_get_user_feedback_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = user_feedback.UserFeedback() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_user_feedback(name="name_value",) @@ -1369,12 +1344,11 @@ def test_get_user_feedback_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_user_feedback_flattened_error(): - client = QuestionServiceClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1386,7 +1360,9 @@ def test_get_user_feedback_flattened_error(): @pytest.mark.asyncio async def test_get_user_feedback_flattened_async(): - client = QuestionServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1406,13 +1382,14 @@ async def test_get_user_feedback_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_user_feedback_flattened_error_async(): - client = QuestionServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1426,7 +1403,7 @@ def test_update_user_feedback( transport: str = "grpc", request_type=question_service.UpdateUserFeedbackRequest ): client = QuestionServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1443,23 +1420,17 @@ def test_update_user_feedback( free_form_feedback="free_form_feedback_value", rating=gcd_user_feedback.UserFeedback.UserFeedbackRating.POSITIVE, ) - response = client.update_user_feedback(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == question_service.UpdateUserFeedbackRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_user_feedback.UserFeedback) - assert response.name == "name_value" - assert response.free_form_feedback == "free_form_feedback_value" - assert response.rating == gcd_user_feedback.UserFeedback.UserFeedbackRating.POSITIVE @@ -1471,7 +1442,7 @@ def test_update_user_feedback_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = QuestionServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1481,7 +1452,6 @@ def test_update_user_feedback_empty_call(): client.update_user_feedback() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == question_service.UpdateUserFeedbackRequest() @@ -1491,7 +1461,7 @@ async def test_update_user_feedback_async( request_type=question_service.UpdateUserFeedbackRequest, ): client = QuestionServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1510,22 +1480,17 @@ async def test_update_user_feedback_async( rating=gcd_user_feedback.UserFeedback.UserFeedbackRating.POSITIVE, ) ) - response = await client.update_user_feedback(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == question_service.UpdateUserFeedbackRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_user_feedback.UserFeedback) - assert response.name == "name_value" - assert response.free_form_feedback == "free_form_feedback_value" - assert response.rating == gcd_user_feedback.UserFeedback.UserFeedbackRating.POSITIVE @@ -1535,11 +1500,12 @@ async def test_update_user_feedback_async_from_dict(): def test_update_user_feedback_field_headers(): - client = QuestionServiceClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = question_service.UpdateUserFeedbackRequest() + request.user_feedback.name = "user_feedback.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1547,7 +1513,6 @@ def test_update_user_feedback_field_headers(): type(client.transport.update_user_feedback), "__call__" ) as call: call.return_value = gcd_user_feedback.UserFeedback() - client.update_user_feedback(request) # Establish that the underlying gRPC stub method was called. @@ -1565,11 +1530,14 @@ def test_update_user_feedback_field_headers(): @pytest.mark.asyncio async def test_update_user_feedback_field_headers_async(): - client = QuestionServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = question_service.UpdateUserFeedbackRequest() + request.user_feedback.name = "user_feedback.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1579,7 +1547,6 @@ async def test_update_user_feedback_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_user_feedback.UserFeedback() ) - await client.update_user_feedback(request) # Establish that the underlying gRPC stub method was called. @@ -1596,7 +1563,7 @@ async def test_update_user_feedback_field_headers_async(): def test_update_user_feedback_flattened(): - client = QuestionServiceClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1604,28 +1571,25 @@ def test_update_user_feedback_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_user_feedback.UserFeedback() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_user_feedback( user_feedback=gcd_user_feedback.UserFeedback(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].user_feedback == gcd_user_feedback.UserFeedback( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_user_feedback_flattened_error(): - client = QuestionServiceClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1633,13 +1597,15 @@ def test_update_user_feedback_flattened_error(): client.update_user_feedback( question_service.UpdateUserFeedbackRequest(), user_feedback=gcd_user_feedback.UserFeedback(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_user_feedback_flattened_async(): - client = QuestionServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1655,24 +1621,24 @@ async def test_update_user_feedback_flattened_async(): # using the keyword arguments to the method. response = await client.update_user_feedback( user_feedback=gcd_user_feedback.UserFeedback(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].user_feedback == gcd_user_feedback.UserFeedback( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_user_feedback_flattened_error_async(): - client = QuestionServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1680,23 +1646,23 @@ async def test_update_user_feedback_flattened_error_async(): await client.update_user_feedback( question_service.UpdateUserFeedbackRequest(), user_feedback=gcd_user_feedback.UserFeedback(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.QuestionServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = QuestionServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.QuestionServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = QuestionServiceClient( @@ -1706,7 +1672,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.QuestionServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = QuestionServiceClient( @@ -1717,7 +1683,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.QuestionServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = QuestionServiceClient(transport=transport) assert client.transport is transport @@ -1726,13 +1692,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.QuestionServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.QuestionServiceGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1747,23 +1713,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = QuestionServiceClient(credentials=credentials.AnonymousCredentials(),) + client = QuestionServiceClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.QuestionServiceGrpcTransport,) def test_question_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.QuestionServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1775,7 +1741,7 @@ def test_question_service_base_transport(): ) as Transport: Transport.return_value = None transport = transports.QuestionServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1792,15 +1758,37 @@ def test_question_service_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_question_service_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.dataqna_v1alpha.services.question_service.transports.QuestionServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.QuestionServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_question_service_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dataqna_v1alpha.services.question_service.transports.QuestionServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.QuestionServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1813,19 +1801,33 @@ def test_question_service_base_transport_with_credentials_file(): def test_question_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( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dataqna_v1alpha.services.question_service.transports.QuestionServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.QuestionServiceTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_question_service_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + QuestionServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_question_service_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) QuestionServiceClient() adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), @@ -1833,20 +1835,156 @@ def test_question_service_auth_adc(): ) -def test_question_service_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.QuestionServiceGrpcTransport, + transports.QuestionServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_question_service_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.QuestionServiceGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.QuestionServiceGrpcTransport, + transports.QuestionServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_question_service_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.QuestionServiceGrpcTransport, grpc_helpers), + (transports.QuestionServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_question_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dataqna.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="dataqna.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.QuestionServiceGrpcTransport, grpc_helpers), + (transports.QuestionServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_question_service_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dataqna.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.QuestionServiceGrpcTransport, grpc_helpers), + (transports.QuestionServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_question_service_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dataqna.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -1855,7 +1993,7 @@ def test_question_service_transport_auth_adc(): ], ) def test_question_service_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1894,7 +2032,7 @@ def test_question_service_grpc_transport_client_cert_source_for_mtls(transport_c def test_question_service_host_no_port(): client = QuestionServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dataqna.googleapis.com" ), @@ -1904,7 +2042,7 @@ def test_question_service_host_no_port(): def test_question_service_host_with_port(): client = QuestionServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dataqna.googleapis.com:8000" ), @@ -1960,9 +2098,9 @@ def test_question_service_transport_channel_mtls_with_client_cert_source( mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2040,7 +2178,6 @@ def test_question_path(): project = "squid" location = "clam" question = "whelk" - expected = "projects/{project}/locations/{location}/questions/{question}".format( project=project, location=location, question=question, ) @@ -2065,7 +2202,6 @@ def test_user_feedback_path(): project = "cuttlefish" location = "mussel" question = "winkle" - expected = "projects/{project}/locations/{location}/questions/{question}/userFeedback".format( project=project, location=location, question=question, ) @@ -2088,7 +2224,6 @@ def test_parse_user_feedback_path(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2109,7 +2244,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = QuestionServiceClient.common_folder_path(folder) assert expected == actual @@ -2128,7 +2262,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = QuestionServiceClient.common_organization_path(organization) assert expected == actual @@ -2147,7 +2280,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = QuestionServiceClient.common_project_path(project) assert expected == actual @@ -2167,7 +2299,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2194,7 +2325,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.QuestionServiceTransport, "_prep_wrapped_messages" ) as prep: client = QuestionServiceClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2203,6 +2334,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = QuestionServiceClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info)