diff --git a/google/cloud/dataqna_v1alpha/gapic_metadata.json b/google/cloud/dataqna_v1alpha/gapic_metadata.json index 7ba1907..766ccd9 100644 --- a/google/cloud/dataqna_v1alpha/gapic_metadata.json +++ b/google/cloud/dataqna_v1alpha/gapic_metadata.json @@ -26,6 +26,16 @@ ] } } + }, + "rest": { + "libraryClient": "AutoSuggestionServiceClient", + "rpcs": { + "SuggestQueries": { + "methods": [ + "suggest_queries" + ] + } + } } } }, @@ -90,6 +100,36 @@ ] } } + }, + "rest": { + "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" + ] + } + } } } } diff --git a/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/client.py b/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/client.py index 77c2616..a68ed23 100644 --- a/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/client.py +++ b/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/client.py @@ -39,6 +39,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, AutoSuggestionServiceTransport from .transports.grpc import AutoSuggestionServiceGrpcTransport from .transports.grpc_asyncio import AutoSuggestionServiceGrpcAsyncIOTransport +from .transports.rest import AutoSuggestionServiceRestTransport class AutoSuggestionServiceClientMeta(type): @@ -54,6 +55,7 @@ class AutoSuggestionServiceClientMeta(type): ) # type: Dict[str, Type[AutoSuggestionServiceTransport]] _transport_registry["grpc"] = AutoSuggestionServiceGrpcTransport _transport_registry["grpc_asyncio"] = AutoSuggestionServiceGrpcAsyncIOTransport + _transport_registry["rest"] = AutoSuggestionServiceRestTransport def get_transport_class( cls, @@ -396,6 +398,9 @@ def __init__( transport (Union[str, AutoSuggestionServiceTransport]): The transport to use. If set to None, a transport is chosen automatically. + NOTE: "rest" transport functionality is currently in a + beta state (preview). We welcome your feedback via an + issue in this library's source repository. client_options (google.api_core.client_options.ClientOptions): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the diff --git a/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/transports/__init__.py b/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/transports/__init__.py index cdaa5a5..b571458 100644 --- a/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/transports/__init__.py +++ b/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/transports/__init__.py @@ -19,6 +19,10 @@ from .base import AutoSuggestionServiceTransport from .grpc import AutoSuggestionServiceGrpcTransport from .grpc_asyncio import AutoSuggestionServiceGrpcAsyncIOTransport +from .rest import ( + AutoSuggestionServiceRestInterceptor, + AutoSuggestionServiceRestTransport, +) # Compile a registry of transports. _transport_registry = ( @@ -26,9 +30,12 @@ ) # type: Dict[str, Type[AutoSuggestionServiceTransport]] _transport_registry["grpc"] = AutoSuggestionServiceGrpcTransport _transport_registry["grpc_asyncio"] = AutoSuggestionServiceGrpcAsyncIOTransport +_transport_registry["rest"] = AutoSuggestionServiceRestTransport __all__ = ( "AutoSuggestionServiceTransport", "AutoSuggestionServiceGrpcTransport", "AutoSuggestionServiceGrpcAsyncIOTransport", + "AutoSuggestionServiceRestTransport", + "AutoSuggestionServiceRestInterceptor", ) diff --git a/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/transports/rest.py b/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/transports/rest.py new file mode 100644 index 0000000..36732f9 --- /dev/null +++ b/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/transports/rest.py @@ -0,0 +1,390 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.dataqna_v1alpha.types import auto_suggestion_service + +from .base import AutoSuggestionServiceTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class AutoSuggestionServiceRestInterceptor: + """Interceptor for AutoSuggestionService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the AutoSuggestionServiceRestTransport. + + .. code-block:: python + class MyCustomAutoSuggestionServiceInterceptor(AutoSuggestionServiceRestInterceptor): + def pre_suggest_queries(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_suggest_queries(response): + logging.log(f"Received response: {response}") + + transport = AutoSuggestionServiceRestTransport(interceptor=MyCustomAutoSuggestionServiceInterceptor()) + client = AutoSuggestionServiceClient(transport=transport) + + + """ + + def pre_suggest_queries( + self, + request: auto_suggestion_service.SuggestQueriesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + auto_suggestion_service.SuggestQueriesRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for suggest_queries + + Override in a subclass to manipulate the request or metadata + before they are sent to the AutoSuggestionService server. + """ + return request, metadata + + def post_suggest_queries( + self, response: auto_suggestion_service.SuggestQueriesResponse + ) -> auto_suggestion_service.SuggestQueriesResponse: + """Post-rpc interceptor for suggest_queries + + Override in a subclass to manipulate the response + after it is returned by the AutoSuggestionService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AutoSuggestionServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AutoSuggestionServiceRestInterceptor + + +class AutoSuggestionServiceRestTransport(AutoSuggestionServiceTransport): + """REST backend transport for AutoSuggestionService. + + This stateless API provides automatic suggestions for natural + language queries for the data sources in the provided project and + location. + + The service provides a resourceless operation ``suggestQueries`` + that can be called to get a list of suggestions for a given + incomplete query and scope (or list of scopes) under which the query + is to be interpreted. + + There are two types of suggestions, ENTITY for single entity + suggestions and TEMPLATE for full sentences. By default, both types + are returned. + + Example Request: + + :: + + GetSuggestions({ + parent: "locations/us/projects/my-project" + scopes: + "//bigquery.googleapis.com/projects/my-project/datasets/my-dataset/tables/my-table" + query: "top it" + }) + + The service will retrieve information based on the given scope(s) + and give suggestions based on that (e.g. "top item" for "top it" if + "item" is a known dimension for the provided scope). + + :: + + suggestions { + suggestion_info { + annotated_suggestion { + text_formatted: "top item by sum of usd_revenue_net" + markups { + type: DIMENSION + start_char_index: 4 + length: 4 + } + markups { + type: METRIC + start_char_index: 19 + length: 15 + } + } + query_matches { + start_char_index: 0 + length: 6 + } + } + suggestion_type: TEMPLATE + ranking_score: 0.9 + } + suggestions { + suggestion_info { + annotated_suggestion { + text_formatted: "item" + markups { + type: DIMENSION + start_char_index: 4 + length: 2 + } + } + query_matches { + start_char_index: 0 + length: 6 + } + } + suggestion_type: ENTITY + ranking_score: 0.8 + } + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via an issue in this + library's source repository. Thank you! + """ + + def __init__( + self, + *, + host: str = "dataqna.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[AutoSuggestionServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or AutoSuggestionServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _SuggestQueries(AutoSuggestionServiceRestStub): + def __hash__(self): + return hash("SuggestQueries") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: auto_suggestion_service.SuggestQueriesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> auto_suggestion_service.SuggestQueriesResponse: + r"""Call the suggest queries method over HTTP. + + Args: + request (~.auto_suggestion_service.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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.auto_suggestion_service.SuggestQueriesResponse: + Response to SuggestQueries. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{parent=projects/*/locations/*}:suggestQueries", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_suggest_queries(request, metadata) + pb_request = auto_suggestion_service.SuggestQueriesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = auto_suggestion_service.SuggestQueriesResponse() + pb_resp = auto_suggestion_service.SuggestQueriesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_suggest_queries(resp) + return resp + + @property + def suggest_queries( + self, + ) -> Callable[ + [auto_suggestion_service.SuggestQueriesRequest], + auto_suggestion_service.SuggestQueriesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SuggestQueries(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("AutoSuggestionServiceRestTransport",) diff --git a/google/cloud/dataqna_v1alpha/services/question_service/client.py b/google/cloud/dataqna_v1alpha/services/question_service/client.py index c8bd609..830e9c6 100644 --- a/google/cloud/dataqna_v1alpha/services/question_service/client.py +++ b/google/cloud/dataqna_v1alpha/services/question_service/client.py @@ -47,6 +47,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, QuestionServiceTransport from .transports.grpc import QuestionServiceGrpcTransport from .transports.grpc_asyncio import QuestionServiceGrpcAsyncIOTransport +from .transports.rest import QuestionServiceRestTransport class QuestionServiceClientMeta(type): @@ -62,6 +63,7 @@ class QuestionServiceClientMeta(type): ) # type: Dict[str, Type[QuestionServiceTransport]] _transport_registry["grpc"] = QuestionServiceGrpcTransport _transport_registry["grpc_asyncio"] = QuestionServiceGrpcAsyncIOTransport + _transport_registry["rest"] = QuestionServiceRestTransport def get_transport_class( cls, @@ -394,6 +396,9 @@ def __init__( transport (Union[str, QuestionServiceTransport]): The transport to use. If set to None, a transport is chosen automatically. + NOTE: "rest" transport functionality is currently in a + beta state (preview). We welcome your feedback via an + issue in this library's source repository. client_options (google.api_core.client_options.ClientOptions): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the diff --git a/google/cloud/dataqna_v1alpha/services/question_service/transports/__init__.py b/google/cloud/dataqna_v1alpha/services/question_service/transports/__init__.py index 80e9be5..4c4b16b 100644 --- a/google/cloud/dataqna_v1alpha/services/question_service/transports/__init__.py +++ b/google/cloud/dataqna_v1alpha/services/question_service/transports/__init__.py @@ -19,14 +19,18 @@ from .base import QuestionServiceTransport from .grpc import QuestionServiceGrpcTransport from .grpc_asyncio import QuestionServiceGrpcAsyncIOTransport +from .rest import QuestionServiceRestInterceptor, QuestionServiceRestTransport # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[QuestionServiceTransport]] _transport_registry["grpc"] = QuestionServiceGrpcTransport _transport_registry["grpc_asyncio"] = QuestionServiceGrpcAsyncIOTransport +_transport_registry["rest"] = QuestionServiceRestTransport __all__ = ( "QuestionServiceTransport", "QuestionServiceGrpcTransport", "QuestionServiceGrpcAsyncIOTransport", + "QuestionServiceRestTransport", + "QuestionServiceRestInterceptor", ) diff --git a/google/cloud/dataqna_v1alpha/services/question_service/transports/rest.py b/google/cloud/dataqna_v1alpha/services/question_service/transports/rest.py new file mode 100644 index 0000000..375af1f --- /dev/null +++ b/google/cloud/dataqna_v1alpha/services/question_service/transports/rest.py @@ -0,0 +1,866 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.dataqna_v1alpha.types import user_feedback as gcd_user_feedback +from google.cloud.dataqna_v1alpha.types import question +from google.cloud.dataqna_v1alpha.types import question as gcd_question +from google.cloud.dataqna_v1alpha.types import question_service +from google.cloud.dataqna_v1alpha.types import user_feedback + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import QuestionServiceTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class QuestionServiceRestInterceptor: + """Interceptor for QuestionService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the QuestionServiceRestTransport. + + .. code-block:: python + class MyCustomQuestionServiceInterceptor(QuestionServiceRestInterceptor): + def pre_create_question(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_question(response): + logging.log(f"Received response: {response}") + + def pre_execute_question(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_execute_question(response): + logging.log(f"Received response: {response}") + + def pre_get_question(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_question(response): + logging.log(f"Received response: {response}") + + def pre_get_user_feedback(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_user_feedback(response): + logging.log(f"Received response: {response}") + + def pre_update_user_feedback(request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_user_feedback(response): + logging.log(f"Received response: {response}") + + transport = QuestionServiceRestTransport(interceptor=MyCustomQuestionServiceInterceptor()) + client = QuestionServiceClient(transport=transport) + + + """ + + def pre_create_question( + self, + request: question_service.CreateQuestionRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[question_service.CreateQuestionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_question + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuestionService server. + """ + return request, metadata + + def post_create_question( + self, response: gcd_question.Question + ) -> gcd_question.Question: + """Post-rpc interceptor for create_question + + Override in a subclass to manipulate the response + after it is returned by the QuestionService server but before + it is returned to user code. + """ + return response + + def pre_execute_question( + self, + request: question_service.ExecuteQuestionRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[question_service.ExecuteQuestionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for execute_question + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuestionService server. + """ + return request, metadata + + def post_execute_question(self, response: question.Question) -> question.Question: + """Post-rpc interceptor for execute_question + + Override in a subclass to manipulate the response + after it is returned by the QuestionService server but before + it is returned to user code. + """ + return response + + def pre_get_question( + self, + request: question_service.GetQuestionRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[question_service.GetQuestionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_question + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuestionService server. + """ + return request, metadata + + def post_get_question(self, response: question.Question) -> question.Question: + """Post-rpc interceptor for get_question + + Override in a subclass to manipulate the response + after it is returned by the QuestionService server but before + it is returned to user code. + """ + return response + + def pre_get_user_feedback( + self, + request: question_service.GetUserFeedbackRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[question_service.GetUserFeedbackRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_user_feedback + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuestionService server. + """ + return request, metadata + + def post_get_user_feedback( + self, response: user_feedback.UserFeedback + ) -> user_feedback.UserFeedback: + """Post-rpc interceptor for get_user_feedback + + Override in a subclass to manipulate the response + after it is returned by the QuestionService server but before + it is returned to user code. + """ + return response + + def pre_update_user_feedback( + self, + request: question_service.UpdateUserFeedbackRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[question_service.UpdateUserFeedbackRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_user_feedback + + Override in a subclass to manipulate the request or metadata + before they are sent to the QuestionService server. + """ + return request, metadata + + def post_update_user_feedback( + self, response: gcd_user_feedback.UserFeedback + ) -> gcd_user_feedback.UserFeedback: + """Post-rpc interceptor for update_user_feedback + + Override in a subclass to manipulate the response + after it is returned by the QuestionService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class QuestionServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: QuestionServiceRestInterceptor + + +class QuestionServiceRestTransport(QuestionServiceTransport): + """REST backend transport for QuestionService. + + Service to interpret natural language queries. The service allows to + create ``Question`` resources that are interpreted and are filled + with one or more interpretations if the question could be + interpreted. Once a ``Question`` resource is created and has at + least one interpretation, an interpretation can be chosen for + execution, which triggers a query to the backend (for BigQuery, it + will create a job). Upon successful execution of that + interpretation, backend specific information will be returned so + that the client can retrieve the results from the backend. + + The ``Question`` resources are named + ``projects/*/locations/*/questions/*``. + + The ``Question`` resource has a singletion sub-resource + ``UserFeedback`` named + ``projects/*/locations/*/questions/*/userFeedback``, which allows + access to user feedback. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via an issue in this + library's source repository. Thank you! + """ + + def __init__( + self, + *, + host: str = "dataqna.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[QuestionServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or QuestionServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateQuestion(QuestionServiceRestStub): + def __hash__(self): + return hash("CreateQuestion") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: question_service.CreateQuestionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_question.Question: + r"""Call the create question method over HTTP. + + Args: + request (~.question_service.CreateQuestionRequest): + The request object. Request to create a question + resource. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcd_question.Question: + The question resource represents a + natural language query, its settings, + understanding generated by the system, + and answer retrieval status. A question + cannot be modified. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{parent=projects/*/locations/*}/questions", + "body": "question", + }, + ] + request, metadata = self._interceptor.pre_create_question(request, metadata) + pb_request = question_service.CreateQuestionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcd_question.Question() + pb_resp = gcd_question.Question.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_question(resp) + return resp + + class _ExecuteQuestion(QuestionServiceRestStub): + def __hash__(self): + return hash("ExecuteQuestion") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: question_service.ExecuteQuestionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> question.Question: + r"""Call the execute question method over HTTP. + + Args: + request (~.question_service.ExecuteQuestionRequest): + The request object. Request to execute an interpretation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.question.Question: + The question resource represents a + natural language query, its settings, + understanding generated by the system, + and answer retrieval status. A question + cannot be modified. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{name=projects/*/locations/*/questions/*}:execute", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_execute_question( + request, metadata + ) + pb_request = question_service.ExecuteQuestionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = question.Question() + pb_resp = question.Question.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_execute_question(resp) + return resp + + class _GetQuestion(QuestionServiceRestStub): + def __hash__(self): + return hash("GetQuestion") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: question_service.GetQuestionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> question.Question: + r"""Call the get question method over HTTP. + + Args: + request (~.question_service.GetQuestionRequest): + The request object. A request to get a previously created + question. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.question.Question: + The question resource represents a + natural language query, its settings, + understanding generated by the system, + and answer retrieval status. A question + cannot be modified. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/questions/*}", + }, + ] + request, metadata = self._interceptor.pre_get_question(request, metadata) + pb_request = question_service.GetQuestionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = question.Question() + pb_resp = question.Question.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_question(resp) + return resp + + class _GetUserFeedback(QuestionServiceRestStub): + def __hash__(self): + return hash("GetUserFeedback") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: question_service.GetUserFeedbackRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> user_feedback.UserFeedback: + r"""Call the get user feedback method over HTTP. + + Args: + request (~.question_service.GetUserFeedbackRequest): + The request object. Request to get user feedback. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.user_feedback.UserFeedback: + Feedback provided by a user. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/questions/*/userFeedback}", + }, + ] + request, metadata = self._interceptor.pre_get_user_feedback( + request, metadata + ) + pb_request = question_service.GetUserFeedbackRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = user_feedback.UserFeedback() + pb_resp = user_feedback.UserFeedback.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_user_feedback(resp) + return resp + + class _UpdateUserFeedback(QuestionServiceRestStub): + def __hash__(self): + return hash("UpdateUserFeedback") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: question_service.UpdateUserFeedbackRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_user_feedback.UserFeedback: + r"""Call the update user feedback method over HTTP. + + Args: + request (~.question_service.UpdateUserFeedbackRequest): + The request object. Request to updates user feedback. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcd_user_feedback.UserFeedback: + Feedback provided by a user. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1alpha/{user_feedback.name=projects/*/locations/*/questions/*/userFeedback}", + "body": "user_feedback", + }, + ] + request, metadata = self._interceptor.pre_update_user_feedback( + request, metadata + ) + pb_request = question_service.UpdateUserFeedbackRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcd_user_feedback.UserFeedback() + pb_resp = gcd_user_feedback.UserFeedback.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_user_feedback(resp) + return resp + + @property + def create_question( + self, + ) -> Callable[[question_service.CreateQuestionRequest], gcd_question.Question]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateQuestion(self._session, self._host, self._interceptor) # type: ignore + + @property + def execute_question( + self, + ) -> Callable[[question_service.ExecuteQuestionRequest], question.Question]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ExecuteQuestion(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_question( + self, + ) -> Callable[[question_service.GetQuestionRequest], question.Question]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetQuestion(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_user_feedback( + self, + ) -> Callable[ + [question_service.GetUserFeedbackRequest], user_feedback.UserFeedback + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetUserFeedback(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_user_feedback( + self, + ) -> Callable[ + [question_service.UpdateUserFeedbackRequest], gcd_user_feedback.UserFeedback + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateUserFeedback(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("QuestionServiceRestTransport",) diff --git a/samples/generated_samples/dataqna_v1alpha_generated_auto_suggestion_service_suggest_queries_sync.py b/samples/generated_samples/dataqna_v1alpha_generated_auto_suggestion_service_suggest_queries_sync_d283907c.py similarity index 97% rename from samples/generated_samples/dataqna_v1alpha_generated_auto_suggestion_service_suggest_queries_sync.py rename to samples/generated_samples/dataqna_v1alpha_generated_auto_suggestion_service_suggest_queries_sync_d283907c.py index 33ac38e..b94990b 100644 --- a/samples/generated_samples/dataqna_v1alpha_generated_auto_suggestion_service_suggest_queries_sync.py +++ b/samples/generated_samples/dataqna_v1alpha_generated_auto_suggestion_service_suggest_queries_sync_d283907c.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-dataqna -# [START dataqna_v1alpha_generated_AutoSuggestionService_SuggestQueries_sync] +# [START dataqna_v1alpha_generated_AutoSuggestionService_SuggestQueries_sync_d283907c] # This snippet has been automatically generated and should be regarded as a # code template only. # It will require modifications to work: @@ -49,4 +49,4 @@ def sample_suggest_queries(): # Handle the response print(response) -# [END dataqna_v1alpha_generated_AutoSuggestionService_SuggestQueries_sync] +# [END dataqna_v1alpha_generated_AutoSuggestionService_SuggestQueries_sync_d283907c] diff --git a/samples/generated_samples/dataqna_v1alpha_generated_auto_suggestion_service_suggest_queries_sync_f773b5fc.py b/samples/generated_samples/dataqna_v1alpha_generated_auto_suggestion_service_suggest_queries_sync_f773b5fc.py new file mode 100644 index 0000000..867a9b5 --- /dev/null +++ b/samples/generated_samples/dataqna_v1alpha_generated_auto_suggestion_service_suggest_queries_sync_f773b5fc.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SuggestQueries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dataqna + + +# [START dataqna_v1alpha_generated_AutoSuggestionService_SuggestQueries_sync_f773b5fc] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dataqna_v1alpha + + +def sample_suggest_queries(): + # Create a client + client = dataqna_v1alpha.AutoSuggestionServiceClient() + + # Initialize request argument(s) + request = dataqna_v1alpha.SuggestQueriesRequest( + parent="parent_value", + ) + + # Make the request + response = client.suggest_queries(request=request) + + # Handle the response + print(response) + +# [END dataqna_v1alpha_generated_AutoSuggestionService_SuggestQueries_sync_f773b5fc] diff --git a/samples/generated_samples/dataqna_v1alpha_generated_question_service_create_question_sync.py b/samples/generated_samples/dataqna_v1alpha_generated_question_service_create_question_sync_dc8a80fc.py similarity index 98% rename from samples/generated_samples/dataqna_v1alpha_generated_question_service_create_question_sync.py rename to samples/generated_samples/dataqna_v1alpha_generated_question_service_create_question_sync_dc8a80fc.py index fdf3b21..da1eb0d 100644 --- a/samples/generated_samples/dataqna_v1alpha_generated_question_service_create_question_sync.py +++ b/samples/generated_samples/dataqna_v1alpha_generated_question_service_create_question_sync_dc8a80fc.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-dataqna -# [START dataqna_v1alpha_generated_QuestionService_CreateQuestion_sync] +# [START dataqna_v1alpha_generated_QuestionService_CreateQuestion_sync_dc8a80fc] # This snippet has been automatically generated and should be regarded as a # code template only. # It will require modifications to work: @@ -54,4 +54,4 @@ def sample_create_question(): # Handle the response print(response) -# [END dataqna_v1alpha_generated_QuestionService_CreateQuestion_sync] +# [END dataqna_v1alpha_generated_QuestionService_CreateQuestion_sync_dc8a80fc] diff --git a/samples/generated_samples/dataqna_v1alpha_generated_question_service_create_question_sync_ddc01494.py b/samples/generated_samples/dataqna_v1alpha_generated_question_service_create_question_sync_ddc01494.py new file mode 100644 index 0000000..ef9e974 --- /dev/null +++ b/samples/generated_samples/dataqna_v1alpha_generated_question_service_create_question_sync_ddc01494.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateQuestion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dataqna + + +# [START dataqna_v1alpha_generated_QuestionService_CreateQuestion_sync_ddc01494] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dataqna_v1alpha + + +def sample_create_question(): + # Create a client + client = dataqna_v1alpha.QuestionServiceClient() + + # Initialize request argument(s) + question = dataqna_v1alpha.Question() + question.scopes = ['scopes_value1', 'scopes_value2'] + question.query = "query_value" + + request = dataqna_v1alpha.CreateQuestionRequest( + parent="parent_value", + question=question, + ) + + # Make the request + response = client.create_question(request=request) + + # Handle the response + print(response) + +# [END dataqna_v1alpha_generated_QuestionService_CreateQuestion_sync_ddc01494] diff --git a/samples/generated_samples/dataqna_v1alpha_generated_question_service_execute_question_sync.py b/samples/generated_samples/dataqna_v1alpha_generated_question_service_execute_question_sync_65ec7ecd.py similarity index 98% rename from samples/generated_samples/dataqna_v1alpha_generated_question_service_execute_question_sync.py rename to samples/generated_samples/dataqna_v1alpha_generated_question_service_execute_question_sync_65ec7ecd.py index fcff838..012f7d5 100644 --- a/samples/generated_samples/dataqna_v1alpha_generated_question_service_execute_question_sync.py +++ b/samples/generated_samples/dataqna_v1alpha_generated_question_service_execute_question_sync_65ec7ecd.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-dataqna -# [START dataqna_v1alpha_generated_QuestionService_ExecuteQuestion_sync] +# [START dataqna_v1alpha_generated_QuestionService_ExecuteQuestion_sync_65ec7ecd] # This snippet has been automatically generated and should be regarded as a # code template only. # It will require modifications to work: @@ -50,4 +50,4 @@ def sample_execute_question(): # Handle the response print(response) -# [END dataqna_v1alpha_generated_QuestionService_ExecuteQuestion_sync] +# [END dataqna_v1alpha_generated_QuestionService_ExecuteQuestion_sync_65ec7ecd] diff --git a/samples/generated_samples/dataqna_v1alpha_generated_question_service_execute_question_sync_af447ce0.py b/samples/generated_samples/dataqna_v1alpha_generated_question_service_execute_question_sync_af447ce0.py new file mode 100644 index 0000000..64585a0 --- /dev/null +++ b/samples/generated_samples/dataqna_v1alpha_generated_question_service_execute_question_sync_af447ce0.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ExecuteQuestion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dataqna + + +# [START dataqna_v1alpha_generated_QuestionService_ExecuteQuestion_sync_af447ce0] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dataqna_v1alpha + + +def sample_execute_question(): + # Create a client + client = dataqna_v1alpha.QuestionServiceClient() + + # Initialize request argument(s) + request = dataqna_v1alpha.ExecuteQuestionRequest( + name="name_value", + interpretation_index=2159, + ) + + # Make the request + response = client.execute_question(request=request) + + # Handle the response + print(response) + +# [END dataqna_v1alpha_generated_QuestionService_ExecuteQuestion_sync_af447ce0] diff --git a/samples/generated_samples/dataqna_v1alpha_generated_question_service_get_question_sync.py b/samples/generated_samples/dataqna_v1alpha_generated_question_service_get_question_sync_42230e84.py similarity index 98% rename from samples/generated_samples/dataqna_v1alpha_generated_question_service_get_question_sync.py rename to samples/generated_samples/dataqna_v1alpha_generated_question_service_get_question_sync_42230e84.py index 3603021..71e66db 100644 --- a/samples/generated_samples/dataqna_v1alpha_generated_question_service_get_question_sync.py +++ b/samples/generated_samples/dataqna_v1alpha_generated_question_service_get_question_sync_42230e84.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-dataqna -# [START dataqna_v1alpha_generated_QuestionService_GetQuestion_sync] +# [START dataqna_v1alpha_generated_QuestionService_GetQuestion_sync_42230e84] # This snippet has been automatically generated and should be regarded as a # code template only. # It will require modifications to work: @@ -49,4 +49,4 @@ def sample_get_question(): # Handle the response print(response) -# [END dataqna_v1alpha_generated_QuestionService_GetQuestion_sync] +# [END dataqna_v1alpha_generated_QuestionService_GetQuestion_sync_42230e84] diff --git a/samples/generated_samples/dataqna_v1alpha_generated_question_service_get_question_sync_46d5ce19.py b/samples/generated_samples/dataqna_v1alpha_generated_question_service_get_question_sync_46d5ce19.py new file mode 100644 index 0000000..990e2a1 --- /dev/null +++ b/samples/generated_samples/dataqna_v1alpha_generated_question_service_get_question_sync_46d5ce19.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetQuestion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dataqna + + +# [START dataqna_v1alpha_generated_QuestionService_GetQuestion_sync_46d5ce19] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dataqna_v1alpha + + +def sample_get_question(): + # Create a client + client = dataqna_v1alpha.QuestionServiceClient() + + # Initialize request argument(s) + request = dataqna_v1alpha.GetQuestionRequest( + name="name_value", + ) + + # Make the request + response = client.get_question(request=request) + + # Handle the response + print(response) + +# [END dataqna_v1alpha_generated_QuestionService_GetQuestion_sync_46d5ce19] diff --git a/samples/generated_samples/dataqna_v1alpha_generated_question_service_get_user_feedback_sync.py b/samples/generated_samples/dataqna_v1alpha_generated_question_service_get_user_feedback_sync_57510043.py similarity index 98% rename from samples/generated_samples/dataqna_v1alpha_generated_question_service_get_user_feedback_sync.py rename to samples/generated_samples/dataqna_v1alpha_generated_question_service_get_user_feedback_sync_57510043.py index df04fd3..2e5eea1 100644 --- a/samples/generated_samples/dataqna_v1alpha_generated_question_service_get_user_feedback_sync.py +++ b/samples/generated_samples/dataqna_v1alpha_generated_question_service_get_user_feedback_sync_57510043.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-dataqna -# [START dataqna_v1alpha_generated_QuestionService_GetUserFeedback_sync] +# [START dataqna_v1alpha_generated_QuestionService_GetUserFeedback_sync_57510043] # This snippet has been automatically generated and should be regarded as a # code template only. # It will require modifications to work: @@ -49,4 +49,4 @@ def sample_get_user_feedback(): # Handle the response print(response) -# [END dataqna_v1alpha_generated_QuestionService_GetUserFeedback_sync] +# [END dataqna_v1alpha_generated_QuestionService_GetUserFeedback_sync_57510043] diff --git a/samples/generated_samples/dataqna_v1alpha_generated_question_service_get_user_feedback_sync_7b0c3817.py b/samples/generated_samples/dataqna_v1alpha_generated_question_service_get_user_feedback_sync_7b0c3817.py new file mode 100644 index 0000000..73124e6 --- /dev/null +++ b/samples/generated_samples/dataqna_v1alpha_generated_question_service_get_user_feedback_sync_7b0c3817.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetUserFeedback +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dataqna + + +# [START dataqna_v1alpha_generated_QuestionService_GetUserFeedback_sync_7b0c3817] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dataqna_v1alpha + + +def sample_get_user_feedback(): + # Create a client + client = dataqna_v1alpha.QuestionServiceClient() + + # Initialize request argument(s) + request = dataqna_v1alpha.GetUserFeedbackRequest( + name="name_value", + ) + + # Make the request + response = client.get_user_feedback(request=request) + + # Handle the response + print(response) + +# [END dataqna_v1alpha_generated_QuestionService_GetUserFeedback_sync_7b0c3817] diff --git a/samples/generated_samples/dataqna_v1alpha_generated_question_service_update_user_feedback_sync.py b/samples/generated_samples/dataqna_v1alpha_generated_question_service_update_user_feedback_sync_66ce529c.py similarity index 98% rename from samples/generated_samples/dataqna_v1alpha_generated_question_service_update_user_feedback_sync.py rename to samples/generated_samples/dataqna_v1alpha_generated_question_service_update_user_feedback_sync_66ce529c.py index 5860acd..47e5acd 100644 --- a/samples/generated_samples/dataqna_v1alpha_generated_question_service_update_user_feedback_sync.py +++ b/samples/generated_samples/dataqna_v1alpha_generated_question_service_update_user_feedback_sync_66ce529c.py @@ -23,7 +23,7 @@ # python3 -m pip install google-cloud-dataqna -# [START dataqna_v1alpha_generated_QuestionService_UpdateUserFeedback_sync] +# [START dataqna_v1alpha_generated_QuestionService_UpdateUserFeedback_sync_66ce529c] # This snippet has been automatically generated and should be regarded as a # code template only. # It will require modifications to work: @@ -52,4 +52,4 @@ def sample_update_user_feedback(): # Handle the response print(response) -# [END dataqna_v1alpha_generated_QuestionService_UpdateUserFeedback_sync] +# [END dataqna_v1alpha_generated_QuestionService_UpdateUserFeedback_sync_66ce529c] diff --git a/samples/generated_samples/dataqna_v1alpha_generated_question_service_update_user_feedback_sync_a626ced5.py b/samples/generated_samples/dataqna_v1alpha_generated_question_service_update_user_feedback_sync_a626ced5.py new file mode 100644 index 0000000..ba80d54 --- /dev/null +++ b/samples/generated_samples/dataqna_v1alpha_generated_question_service_update_user_feedback_sync_a626ced5.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateUserFeedback +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-dataqna + + +# [START dataqna_v1alpha_generated_QuestionService_UpdateUserFeedback_sync_a626ced5] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import dataqna_v1alpha + + +def sample_update_user_feedback(): + # Create a client + client = dataqna_v1alpha.QuestionServiceClient() + + # Initialize request argument(s) + user_feedback = dataqna_v1alpha.UserFeedback() + user_feedback.name = "name_value" + + request = dataqna_v1alpha.UpdateUserFeedbackRequest( + user_feedback=user_feedback, + ) + + # Make the request + response = client.update_user_feedback(request=request) + + # Handle the response + print(response) + +# [END dataqna_v1alpha_generated_QuestionService_UpdateUserFeedback_sync_a626ced5] diff --git a/samples/generated_samples/snippet_metadata_dataqna_v1alpha.json b/samples/generated_samples/snippet_metadata_dataqna_v1alpha.json index 3d4b8e3..37755e5 100644 --- a/samples/generated_samples/snippet_metadata_dataqna_v1alpha.json +++ b/samples/generated_samples/snippet_metadata_dataqna_v1alpha.json @@ -125,7 +125,7 @@ "shortName": "suggest_queries" }, "description": "Sample for SuggestQueries", - "file": "dataqna_v1alpha_generated_auto_suggestion_service_suggest_queries_sync.py", + "file": "dataqna_v1alpha_generated_auto_suggestion_service_suggest_queries_sync_f773b5fc.py", "language": "PYTHON", "origin": "API_DEFINITION", "regionTag": "dataqna_v1alpha_generated_AutoSuggestionService_SuggestQueries_sync", @@ -161,7 +161,83 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dataqna_v1alpha_generated_auto_suggestion_service_suggest_queries_sync.py" + "title": "dataqna_v1alpha_generated_auto_suggestion_service_suggest_queries_sync_f773b5fc.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dataqna_v1alpha.AutoSuggestionServiceClient", + "shortName": "AutoSuggestionServiceClient" + }, + "fullName": "google.cloud.dataqna_v1alpha.AutoSuggestionServiceClient.suggest_queries", + "method": { + "fullName": "google.cloud.dataqna.v1alpha.AutoSuggestionService.SuggestQueries", + "service": { + "fullName": "google.cloud.dataqna.v1alpha.AutoSuggestionService", + "shortName": "AutoSuggestionService" + }, + "shortName": "SuggestQueries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dataqna_v1alpha.types.SuggestQueriesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.dataqna_v1alpha.types.SuggestQueriesResponse", + "shortName": "suggest_queries" + }, + "description": "Sample for SuggestQueries", + "file": "dataqna_v1alpha_generated_auto_suggestion_service_suggest_queries_sync_d283907c.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dataqna_v1alpha_generated_AutoSuggestionService_SuggestQueries_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dataqna_v1alpha_generated_auto_suggestion_service_suggest_queries_sync_d283907c.py" }, { "canonical": true, @@ -294,7 +370,91 @@ "shortName": "create_question" }, "description": "Sample for CreateQuestion", - "file": "dataqna_v1alpha_generated_question_service_create_question_sync.py", + "file": "dataqna_v1alpha_generated_question_service_create_question_sync_dc8a80fc.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dataqna_v1alpha_generated_QuestionService_CreateQuestion_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dataqna_v1alpha_generated_question_service_create_question_sync_dc8a80fc.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dataqna_v1alpha.QuestionServiceClient", + "shortName": "QuestionServiceClient" + }, + "fullName": "google.cloud.dataqna_v1alpha.QuestionServiceClient.create_question", + "method": { + "fullName": "google.cloud.dataqna.v1alpha.QuestionService.CreateQuestion", + "service": { + "fullName": "google.cloud.dataqna.v1alpha.QuestionService", + "shortName": "QuestionService" + }, + "shortName": "CreateQuestion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dataqna_v1alpha.types.CreateQuestionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "question", + "type": "google.cloud.dataqna_v1alpha.types.Question" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.dataqna_v1alpha.types.Question", + "shortName": "create_question" + }, + "description": "Sample for CreateQuestion", + "file": "dataqna_v1alpha_generated_question_service_create_question_sync_ddc01494.py", "language": "PYTHON", "origin": "API_DEFINITION", "regionTag": "dataqna_v1alpha_generated_QuestionService_CreateQuestion_sync", @@ -330,7 +490,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dataqna_v1alpha_generated_question_service_create_question_sync.py" + "title": "dataqna_v1alpha_generated_question_service_create_question_sync_ddc01494.py" }, { "canonical": true, @@ -463,7 +623,91 @@ "shortName": "execute_question" }, "description": "Sample for ExecuteQuestion", - "file": "dataqna_v1alpha_generated_question_service_execute_question_sync.py", + "file": "dataqna_v1alpha_generated_question_service_execute_question_sync_65ec7ecd.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dataqna_v1alpha_generated_QuestionService_ExecuteQuestion_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dataqna_v1alpha_generated_question_service_execute_question_sync_65ec7ecd.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dataqna_v1alpha.QuestionServiceClient", + "shortName": "QuestionServiceClient" + }, + "fullName": "google.cloud.dataqna_v1alpha.QuestionServiceClient.execute_question", + "method": { + "fullName": "google.cloud.dataqna.v1alpha.QuestionService.ExecuteQuestion", + "service": { + "fullName": "google.cloud.dataqna.v1alpha.QuestionService", + "shortName": "QuestionService" + }, + "shortName": "ExecuteQuestion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dataqna_v1alpha.types.ExecuteQuestionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "interpretation_index", + "type": "int" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.dataqna_v1alpha.types.Question", + "shortName": "execute_question" + }, + "description": "Sample for ExecuteQuestion", + "file": "dataqna_v1alpha_generated_question_service_execute_question_sync_af447ce0.py", "language": "PYTHON", "origin": "API_DEFINITION", "regionTag": "dataqna_v1alpha_generated_QuestionService_ExecuteQuestion_sync", @@ -499,7 +743,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dataqna_v1alpha_generated_question_service_execute_question_sync.py" + "title": "dataqna_v1alpha_generated_question_service_execute_question_sync_af447ce0.py" }, { "canonical": true, @@ -624,7 +868,7 @@ "shortName": "get_question" }, "description": "Sample for GetQuestion", - "file": "dataqna_v1alpha_generated_question_service_get_question_sync.py", + "file": "dataqna_v1alpha_generated_question_service_get_question_sync_46d5ce19.py", "language": "PYTHON", "origin": "API_DEFINITION", "regionTag": "dataqna_v1alpha_generated_QuestionService_GetQuestion_sync", @@ -660,7 +904,87 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dataqna_v1alpha_generated_question_service_get_question_sync.py" + "title": "dataqna_v1alpha_generated_question_service_get_question_sync_46d5ce19.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dataqna_v1alpha.QuestionServiceClient", + "shortName": "QuestionServiceClient" + }, + "fullName": "google.cloud.dataqna_v1alpha.QuestionServiceClient.get_question", + "method": { + "fullName": "google.cloud.dataqna.v1alpha.QuestionService.GetQuestion", + "service": { + "fullName": "google.cloud.dataqna.v1alpha.QuestionService", + "shortName": "QuestionService" + }, + "shortName": "GetQuestion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dataqna_v1alpha.types.GetQuestionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.dataqna_v1alpha.types.Question", + "shortName": "get_question" + }, + "description": "Sample for GetQuestion", + "file": "dataqna_v1alpha_generated_question_service_get_question_sync_42230e84.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dataqna_v1alpha_generated_QuestionService_GetQuestion_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dataqna_v1alpha_generated_question_service_get_question_sync_42230e84.py" }, { "canonical": true, @@ -785,7 +1109,87 @@ "shortName": "get_user_feedback" }, "description": "Sample for GetUserFeedback", - "file": "dataqna_v1alpha_generated_question_service_get_user_feedback_sync.py", + "file": "dataqna_v1alpha_generated_question_service_get_user_feedback_sync_57510043.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dataqna_v1alpha_generated_QuestionService_GetUserFeedback_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dataqna_v1alpha_generated_question_service_get_user_feedback_sync_57510043.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dataqna_v1alpha.QuestionServiceClient", + "shortName": "QuestionServiceClient" + }, + "fullName": "google.cloud.dataqna_v1alpha.QuestionServiceClient.get_user_feedback", + "method": { + "fullName": "google.cloud.dataqna.v1alpha.QuestionService.GetUserFeedback", + "service": { + "fullName": "google.cloud.dataqna.v1alpha.QuestionService", + "shortName": "QuestionService" + }, + "shortName": "GetUserFeedback" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dataqna_v1alpha.types.GetUserFeedbackRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.dataqna_v1alpha.types.UserFeedback", + "shortName": "get_user_feedback" + }, + "description": "Sample for GetUserFeedback", + "file": "dataqna_v1alpha_generated_question_service_get_user_feedback_sync_7b0c3817.py", "language": "PYTHON", "origin": "API_DEFINITION", "regionTag": "dataqna_v1alpha_generated_QuestionService_GetUserFeedback_sync", @@ -821,7 +1225,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dataqna_v1alpha_generated_question_service_get_user_feedback_sync.py" + "title": "dataqna_v1alpha_generated_question_service_get_user_feedback_sync_7b0c3817.py" }, { "canonical": true, @@ -954,7 +1358,91 @@ "shortName": "update_user_feedback" }, "description": "Sample for UpdateUserFeedback", - "file": "dataqna_v1alpha_generated_question_service_update_user_feedback_sync.py", + "file": "dataqna_v1alpha_generated_question_service_update_user_feedback_sync_66ce529c.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dataqna_v1alpha_generated_QuestionService_UpdateUserFeedback_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dataqna_v1alpha_generated_question_service_update_user_feedback_sync_66ce529c.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dataqna_v1alpha.QuestionServiceClient", + "shortName": "QuestionServiceClient" + }, + "fullName": "google.cloud.dataqna_v1alpha.QuestionServiceClient.update_user_feedback", + "method": { + "fullName": "google.cloud.dataqna.v1alpha.QuestionService.UpdateUserFeedback", + "service": { + "fullName": "google.cloud.dataqna.v1alpha.QuestionService", + "shortName": "QuestionService" + }, + "shortName": "UpdateUserFeedback" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dataqna_v1alpha.types.UpdateUserFeedbackRequest" + }, + { + "name": "user_feedback", + "type": "google.cloud.dataqna_v1alpha.types.UserFeedback" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.dataqna_v1alpha.types.UserFeedback", + "shortName": "update_user_feedback" + }, + "description": "Sample for UpdateUserFeedback", + "file": "dataqna_v1alpha_generated_question_service_update_user_feedback_sync_a626ced5.py", "language": "PYTHON", "origin": "API_DEFINITION", "regionTag": "dataqna_v1alpha_generated_QuestionService_UpdateUserFeedback_sync", @@ -990,7 +1478,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dataqna_v1alpha_generated_question_service_update_user_feedback_sync.py" + "title": "dataqna_v1alpha_generated_question_service_update_user_feedback_sync_a626ced5.py" } ] } diff --git a/setup.py b/setup.py index c4aa560..fe7d9ce 100644 --- a/setup.py +++ b/setup.py @@ -46,9 +46,9 @@ platforms="Posix; MacOS X; Windows", include_package_data=True, install_requires=( - "google-api-core[grpc] >= 1.32.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*", + "google-api-core[grpc] >= 1.33.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*", "proto-plus >= 1.22.0, <2.0.0dev", - "protobuf >= 3.19.0, <5.0.0dev", + "protobuf >= 3.20.1, <5.0.0dev", ), python_requires=">=3.7", classifiers=[ diff --git a/testing/constraints-3.7.txt b/testing/constraints-3.7.txt index 51901fb..dfb70ba 100644 --- a/testing/constraints-3.7.txt +++ b/testing/constraints-3.7.txt @@ -5,6 +5,6 @@ # # e.g., if setup.py has "foo >= 1.14.0, < 2.0.0dev", # Then this file should have foo==1.14.0 -google-api-core==1.32.0 +google-api-core==1.33.1 proto-plus==1.22.0 -protobuf==3.19.0 +protobuf==3.20.1 diff --git a/tests/unit/gapic/dataqna_v1alpha/test_auto_suggestion_service.py b/tests/unit/gapic/dataqna_v1alpha/test_auto_suggestion_service.py index 3768889..6f9fca0 100644 --- a/tests/unit/gapic/dataqna_v1alpha/test_auto_suggestion_service.py +++ b/tests/unit/gapic/dataqna_v1alpha/test_auto_suggestion_service.py @@ -22,6 +22,8 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import Iterable +import json import math from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template @@ -31,11 +33,14 @@ from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.oauth2 import service_account +from google.protobuf import json_format import grpc from grpc.experimental import aio from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session from google.cloud.dataqna_v1alpha.services.auto_suggestion_service import ( AutoSuggestionServiceAsyncClient, @@ -95,6 +100,7 @@ def test__get_default_mtls_endpoint(): [ (AutoSuggestionServiceClient, "grpc"), (AutoSuggestionServiceAsyncClient, "grpc_asyncio"), + (AutoSuggestionServiceClient, "rest"), ], ) def test_auto_suggestion_service_client_from_service_account_info( @@ -110,7 +116,11 @@ def test_auto_suggestion_service_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("dataqna.googleapis.com:443") + assert client.transport._host == ( + "dataqna.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dataqna.googleapis.com" + ) @pytest.mark.parametrize( @@ -118,6 +128,7 @@ def test_auto_suggestion_service_client_from_service_account_info( [ (transports.AutoSuggestionServiceGrpcTransport, "grpc"), (transports.AutoSuggestionServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AutoSuggestionServiceRestTransport, "rest"), ], ) def test_auto_suggestion_service_client_service_account_always_use_jwt( @@ -143,6 +154,7 @@ def test_auto_suggestion_service_client_service_account_always_use_jwt( [ (AutoSuggestionServiceClient, "grpc"), (AutoSuggestionServiceAsyncClient, "grpc_asyncio"), + (AutoSuggestionServiceClient, "rest"), ], ) def test_auto_suggestion_service_client_from_service_account_file( @@ -165,13 +177,18 @@ def test_auto_suggestion_service_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("dataqna.googleapis.com:443") + assert client.transport._host == ( + "dataqna.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dataqna.googleapis.com" + ) def test_auto_suggestion_service_client_get_transport_class(): transport = AutoSuggestionServiceClient.get_transport_class() available_transports = [ transports.AutoSuggestionServiceGrpcTransport, + transports.AutoSuggestionServiceRestTransport, ] assert transport in available_transports @@ -192,6 +209,11 @@ def test_auto_suggestion_service_client_get_transport_class(): transports.AutoSuggestionServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + ( + AutoSuggestionServiceClient, + transports.AutoSuggestionServiceRestTransport, + "rest", + ), ], ) @mock.patch.object( @@ -347,6 +369,18 @@ def test_auto_suggestion_service_client_client_options( "grpc_asyncio", "false", ), + ( + AutoSuggestionServiceClient, + transports.AutoSuggestionServiceRestTransport, + "rest", + "true", + ), + ( + AutoSuggestionServiceClient, + transports.AutoSuggestionServiceRestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -550,6 +584,11 @@ def test_auto_suggestion_service_client_get_mtls_endpoint_and_cert_source(client transports.AutoSuggestionServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + ( + AutoSuggestionServiceClient, + transports.AutoSuggestionServiceRestTransport, + "rest", + ), ], ) def test_auto_suggestion_service_client_client_options_scopes( @@ -590,6 +629,12 @@ def test_auto_suggestion_service_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + ( + AutoSuggestionServiceClient, + transports.AutoSuggestionServiceRestTransport, + "rest", + None, + ), ], ) def test_auto_suggestion_service_client_client_options_credentials_file( @@ -847,6 +892,222 @@ async def test_suggest_queries_field_headers_async(): ) in kw["metadata"] +@pytest.mark.parametrize( + "request_type", + [ + auto_suggestion_service.SuggestQueriesRequest, + dict, + ], +) +def test_suggest_queries_rest(request_type): + client = AutoSuggestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = auto_suggestion_service.SuggestQueriesResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = auto_suggestion_service.SuggestQueriesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.suggest_queries(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, auto_suggestion_service.SuggestQueriesResponse) + + +def test_suggest_queries_rest_required_fields( + request_type=auto_suggestion_service.SuggestQueriesRequest, +): + transport_class = transports.AutoSuggestionServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).suggest_queries._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).suggest_queries._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AutoSuggestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = auto_suggestion_service.SuggestQueriesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = auto_suggestion_service.SuggestQueriesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.suggest_queries(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_suggest_queries_rest_unset_required_fields(): + transport = transports.AutoSuggestionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.suggest_queries._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_suggest_queries_rest_interceptors(null_interceptor): + transport = transports.AutoSuggestionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AutoSuggestionServiceRestInterceptor(), + ) + client = AutoSuggestionServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AutoSuggestionServiceRestInterceptor, "post_suggest_queries" + ) as post, mock.patch.object( + transports.AutoSuggestionServiceRestInterceptor, "pre_suggest_queries" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = auto_suggestion_service.SuggestQueriesRequest.pb( + auto_suggestion_service.SuggestQueriesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + auto_suggestion_service.SuggestQueriesResponse.to_json( + auto_suggestion_service.SuggestQueriesResponse() + ) + ) + + request = auto_suggestion_service.SuggestQueriesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = auto_suggestion_service.SuggestQueriesResponse() + + client.suggest_queries( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_suggest_queries_rest_bad_request( + transport: str = "rest", request_type=auto_suggestion_service.SuggestQueriesRequest +): + client = AutoSuggestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.suggest_queries(request) + + +def test_suggest_queries_rest_error(): + client = AutoSuggestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.AutoSuggestionServiceGrpcTransport( @@ -928,6 +1189,7 @@ def test_transport_get_channel(): [ transports.AutoSuggestionServiceGrpcTransport, transports.AutoSuggestionServiceGrpcAsyncIOTransport, + transports.AutoSuggestionServiceRestTransport, ], ) def test_transport_adc(transport_class): @@ -942,6 +1204,7 @@ def test_transport_adc(transport_class): "transport_name", [ "grpc", + "rest", ], ) def test_transport_kind(transport_name): @@ -1069,6 +1332,7 @@ def test_auto_suggestion_service_transport_auth_adc(transport_class): [ transports.AutoSuggestionServiceGrpcTransport, transports.AutoSuggestionServiceGrpcAsyncIOTransport, + transports.AutoSuggestionServiceRestTransport, ], ) def test_auto_suggestion_service_transport_auth_gdch_credentials(transport_class): @@ -1170,11 +1434,23 @@ def test_auto_suggestion_service_grpc_transport_client_cert_source_for_mtls( ) +def test_auto_suggestion_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.AutoSuggestionServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_auto_suggestion_service_host_no_port(transport_name): @@ -1185,7 +1461,11 @@ def test_auto_suggestion_service_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("dataqna.googleapis.com:443") + assert client.transport._host == ( + "dataqna.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dataqna.googleapis.com" + ) @pytest.mark.parametrize( @@ -1193,6 +1473,7 @@ def test_auto_suggestion_service_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_auto_suggestion_service_host_with_port(transport_name): @@ -1203,7 +1484,33 @@ def test_auto_suggestion_service_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("dataqna.googleapis.com:8000") + assert client.transport._host == ( + "dataqna.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dataqna.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_auto_suggestion_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AutoSuggestionServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AutoSuggestionServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.suggest_queries._session + session2 = client2.transport.suggest_queries._session + assert session1 != session2 def test_auto_suggestion_service_grpc_transport_channel(): @@ -1474,6 +1781,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -1491,6 +1799,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: diff --git a/tests/unit/gapic/dataqna_v1alpha/test_question_service.py b/tests/unit/gapic/dataqna_v1alpha/test_question_service.py index 5755e22..db6e41d 100644 --- a/tests/unit/gapic/dataqna_v1alpha/test_question_service.py +++ b/tests/unit/gapic/dataqna_v1alpha/test_question_service.py @@ -22,6 +22,8 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import Iterable +import json import math from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template @@ -33,6 +35,7 @@ from google.oauth2 import service_account from google.protobuf import any_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore import grpc @@ -40,6 +43,8 @@ from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session from google.cloud.dataqna_v1alpha.services.question_service import ( QuestionServiceAsyncClient, @@ -103,6 +108,7 @@ def test__get_default_mtls_endpoint(): [ (QuestionServiceClient, "grpc"), (QuestionServiceAsyncClient, "grpc_asyncio"), + (QuestionServiceClient, "rest"), ], ) def test_question_service_client_from_service_account_info( @@ -118,7 +124,11 @@ def test_question_service_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("dataqna.googleapis.com:443") + assert client.transport._host == ( + "dataqna.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dataqna.googleapis.com" + ) @pytest.mark.parametrize( @@ -126,6 +136,7 @@ def test_question_service_client_from_service_account_info( [ (transports.QuestionServiceGrpcTransport, "grpc"), (transports.QuestionServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.QuestionServiceRestTransport, "rest"), ], ) def test_question_service_client_service_account_always_use_jwt( @@ -151,6 +162,7 @@ def test_question_service_client_service_account_always_use_jwt( [ (QuestionServiceClient, "grpc"), (QuestionServiceAsyncClient, "grpc_asyncio"), + (QuestionServiceClient, "rest"), ], ) def test_question_service_client_from_service_account_file( @@ -173,13 +185,18 @@ def test_question_service_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("dataqna.googleapis.com:443") + assert client.transport._host == ( + "dataqna.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dataqna.googleapis.com" + ) def test_question_service_client_get_transport_class(): transport = QuestionServiceClient.get_transport_class() available_transports = [ transports.QuestionServiceGrpcTransport, + transports.QuestionServiceRestTransport, ] assert transport in available_transports @@ -196,6 +213,7 @@ def test_question_service_client_get_transport_class(): transports.QuestionServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + (QuestionServiceClient, transports.QuestionServiceRestTransport, "rest"), ], ) @mock.patch.object( @@ -351,6 +369,18 @@ def test_question_service_client_client_options( "grpc_asyncio", "false", ), + ( + QuestionServiceClient, + transports.QuestionServiceRestTransport, + "rest", + "true", + ), + ( + QuestionServiceClient, + transports.QuestionServiceRestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -550,6 +580,7 @@ def test_question_service_client_get_mtls_endpoint_and_cert_source(client_class) transports.QuestionServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + (QuestionServiceClient, transports.QuestionServiceRestTransport, "rest"), ], ) def test_question_service_client_client_options_scopes( @@ -590,6 +621,7 @@ def test_question_service_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + (QuestionServiceClient, transports.QuestionServiceRestTransport, "rest", None), ], ) def test_question_service_client_client_options_credentials_file( @@ -1979,172 +2011,1770 @@ async def test_update_user_feedback_flattened_error_async(): ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.QuestionServiceGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + question_service.GetQuestionRequest, + dict, + ], +) +def test_get_question_rest(request_type): + client = QuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = QuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/questions/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = question.Question( + name="name_value", + scopes=["scopes_value"], + query="query_value", + data_source_annotations=["data_source_annotations_value"], + user_email="user_email_value", ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.QuestionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = QuestionServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = question.Question.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_question(request) + + # 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" + + +def test_get_question_rest_required_fields( + request_type=question_service.GetQuestionRequest, +): + transport_class = transports.QuestionServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, ) + ) - # It is an error to provide an api_key and a transport instance. - transport = transports.QuestionServiceGrpcTransport( + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_question._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_question._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("read_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = QuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = question.Question() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = question.Question.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_question(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_question_rest_unset_required_fields(): + transport = transports.QuestionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = QuestionServiceClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = QuestionServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + unset_fields = transport.get_question._get_unset_required_fields({}) + assert set(unset_fields) == (set(("readMask",)) & set(("name",))) - # It is an error to provide scopes and a transport instance. - transport = transports.QuestionServiceGrpcTransport( + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_question_rest_interceptors(null_interceptor): + transport = transports.QuestionServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.QuestionServiceRestInterceptor(), ) - with pytest.raises(ValueError): - client = QuestionServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + client = QuestionServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.QuestionServiceRestInterceptor, "post_get_question" + ) as post, mock.patch.object( + transports.QuestionServiceRestInterceptor, "pre_get_question" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = question_service.GetQuestionRequest.pb( + question_service.GetQuestionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = question.Question.to_json(question.Question()) + + request = question_service.GetQuestionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = question.Question() + + client.get_question( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) + pre.assert_called_once() + post.assert_called_once() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.QuestionServiceGrpcTransport( + +def test_get_question_rest_bad_request( + transport: str = "rest", request_type=question_service.GetQuestionRequest +): + client = QuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - client = QuestionServiceClient(transport=transport) - assert client.transport is transport + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/questions/sample3"} + request = request_type(**request_init) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.QuestionServiceGrpcTransport( + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_question(request) + + +def test_get_question_rest_flattened(): + client = QuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.QuestionServiceGrpcAsyncIOTransport( + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = question.Question() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/questions/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = question.Question.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_question(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=projects/*/locations/*/questions/*}" + % client.transport._host, + args[1], + ) + + +def test_get_question_rest_flattened_error(transport: str = "rest"): + client = QuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_question( + question_service.GetQuestionRequest(), + name="name_value", + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.QuestionServiceGrpcTransport, - transports.QuestionServiceGrpcAsyncIOTransport, - ], -) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() +def test_get_question_rest_error(): + client = QuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", + question_service.CreateQuestionRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = QuestionServiceClient.get_transport_class(transport_name)( +def test_create_question_rest(request_type): + client = QuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["question"] = { + "name": "name_value", + "scopes": ["scopes_value1", "scopes_value2"], + "query": "query_value", + "data_source_annotations": [ + "data_source_annotations_value1", + "data_source_annotations_value2", + ], + "interpret_error": { + "message": "message_value", + "code": 1, + "details": { + "unsupported_details": { + "operators": ["operators_value1", "operators_value2"], + "intent": ["intent_value1", "intent_value2"], + }, + "incomplete_query_details": {"entities": [1]}, + "ambiguity_details": {}, + }, + }, + "interpretations": [ + { + "data_sources": ["data_sources_value1", "data_sources_value2"], + "confidence": 0.1038, + "unused_phrases": ["unused_phrases_value1", "unused_phrases_value2"], + "human_readable": { + "generated_interpretation": { + "text_formatted": "text_formatted_value", + "html_formatted": "html_formatted_value", + "markups": [ + {"type_": 1, "start_char_index": 1698, "length": 642} + ], + }, + "original_question": {}, + }, + "interpretation_structure": { + "visualization_types": [1], + "column_info": [ + { + "output_alias": "output_alias_value", + "display_name": "display_name_value", + } + ], + }, + "data_query": {"sql": "sql_value"}, + "execution_info": { + "job_creation_status": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + "job_execution_state": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "bigquery_job": { + "job_id": "job_id_value", + "project_id": "project_id_value", + "location": "location_value", + }, + }, + } + ], + "create_time": {}, + "user_email": "user_email_value", + "debug_flags": { + "include_va_query": True, + "include_nested_va_query": True, + "include_human_interpretation": True, + "include_aqua_debug_response": True, + "time_override": 1390, + "is_internal_google_user": True, + "ignore_cache": True, + "include_search_entities_rpc": True, + "include_list_column_annotations_rpc": True, + "include_virtual_analyst_entities": True, + "include_table_list": True, + "include_domain_list": True, + }, + "debug_info": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcd_question.Question( + name="name_value", + scopes=["scopes_value"], + query="query_value", + data_source_annotations=["data_source_annotations_value"], + user_email="user_email_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = gcd_question.Question.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_question(request) + + # 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" + + +def test_create_question_rest_required_fields( + request_type=question_service.CreateQuestionRequest, +): + transport_class = transports.QuestionServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_question._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_question._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. client = QuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert isinstance( - client.transport, - transports.QuestionServiceGrpcTransport, + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcd_question.Question() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = gcd_question.Question.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_question(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_question_rest_unset_required_fields(): + transport = transports.QuestionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) + unset_fields = transport.create_question._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "question", + ) + ) + ) -def test_question_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.QuestionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_question_rest_interceptors(null_interceptor): + transport = transports.QuestionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.QuestionServiceRestInterceptor(), + ) + client = QuestionServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.QuestionServiceRestInterceptor, "post_create_question" + ) as post, mock.patch.object( + transports.QuestionServiceRestInterceptor, "pre_create_question" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = question_service.CreateQuestionRequest.pb( + question_service.CreateQuestionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcd_question.Question.to_json( + gcd_question.Question() ) + request = question_service.CreateQuestionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcd_question.Question() -def test_question_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.dataqna_v1alpha.services.question_service.transports.QuestionServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.QuestionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), + client.create_question( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "get_question", - "create_question", - "execute_question", - "get_user_feedback", - "update_user_feedback", + pre.assert_called_once() + post.assert_called_once() + + +def test_create_question_rest_bad_request( + transport: str = "rest", request_type=question_service.CreateQuestionRequest +): + client = QuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - with pytest.raises(NotImplementedError): - transport.close() + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["question"] = { + "name": "name_value", + "scopes": ["scopes_value1", "scopes_value2"], + "query": "query_value", + "data_source_annotations": [ + "data_source_annotations_value1", + "data_source_annotations_value2", + ], + "interpret_error": { + "message": "message_value", + "code": 1, + "details": { + "unsupported_details": { + "operators": ["operators_value1", "operators_value2"], + "intent": ["intent_value1", "intent_value2"], + }, + "incomplete_query_details": {"entities": [1]}, + "ambiguity_details": {}, + }, + }, + "interpretations": [ + { + "data_sources": ["data_sources_value1", "data_sources_value2"], + "confidence": 0.1038, + "unused_phrases": ["unused_phrases_value1", "unused_phrases_value2"], + "human_readable": { + "generated_interpretation": { + "text_formatted": "text_formatted_value", + "html_formatted": "html_formatted_value", + "markups": [ + {"type_": 1, "start_char_index": 1698, "length": 642} + ], + }, + "original_question": {}, + }, + "interpretation_structure": { + "visualization_types": [1], + "column_info": [ + { + "output_alias": "output_alias_value", + "display_name": "display_name_value", + } + ], + }, + "data_query": {"sql": "sql_value"}, + "execution_info": { + "job_creation_status": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + "job_execution_state": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "bigquery_job": { + "job_id": "job_id_value", + "project_id": "project_id_value", + "location": "location_value", + }, + }, + } + ], + "create_time": {}, + "user_email": "user_email_value", + "debug_flags": { + "include_va_query": True, + "include_nested_va_query": True, + "include_human_interpretation": True, + "include_aqua_debug_response": True, + "time_override": 1390, + "is_internal_google_user": True, + "ignore_cache": True, + "include_search_entities_rpc": True, + "include_list_column_annotations_rpc": True, + "include_virtual_analyst_entities": True, + "include_table_list": True, + "include_domain_list": True, + }, + "debug_info": {}, + } + request = request_type(**request_init) - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_question(request) -def test_question_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch( - "google.cloud.dataqna_v1alpha.services.question_service.transports.QuestionServiceTransport._prep_wrapped_messages" - ) as Transport: +def test_create_question_rest_flattened(): + client = QuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcd_question.Question() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + question=gcd_question.Question(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = gcd_question.Question.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_question(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{parent=projects/*/locations/*}/questions" + % client.transport._host, + args[1], + ) + + +def test_create_question_rest_flattened_error(transport: str = "rest"): + client = QuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_question( + question_service.CreateQuestionRequest(), + parent="parent_value", + question=gcd_question.Question(name="name_value"), + ) + + +def test_create_question_rest_error(): + client = QuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + question_service.ExecuteQuestionRequest, + dict, + ], +) +def test_execute_question_rest(request_type): + client = QuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/questions/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = question.Question( + name="name_value", + scopes=["scopes_value"], + query="query_value", + data_source_annotations=["data_source_annotations_value"], + user_email="user_email_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = question.Question.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.execute_question(request) + + # 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" + + +def test_execute_question_rest_required_fields( + request_type=question_service.ExecuteQuestionRequest, +): + transport_class = transports.QuestionServiceRestTransport + + request_init = {} + request_init["name"] = "" + request_init["interpretation_index"] = 0 + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).execute_question._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + jsonified_request["interpretationIndex"] = 2159 + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).execute_question._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "interpretationIndex" in jsonified_request + assert jsonified_request["interpretationIndex"] == 2159 + + client = QuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = question.Question() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = question.Question.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.execute_question(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_execute_question_rest_unset_required_fields(): + transport = transports.QuestionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.execute_question._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "interpretationIndex", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_execute_question_rest_interceptors(null_interceptor): + transport = transports.QuestionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.QuestionServiceRestInterceptor(), + ) + client = QuestionServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.QuestionServiceRestInterceptor, "post_execute_question" + ) as post, mock.patch.object( + transports.QuestionServiceRestInterceptor, "pre_execute_question" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = question_service.ExecuteQuestionRequest.pb( + question_service.ExecuteQuestionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = question.Question.to_json(question.Question()) + + request = question_service.ExecuteQuestionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = question.Question() + + client.execute_question( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_execute_question_rest_bad_request( + transport: str = "rest", request_type=question_service.ExecuteQuestionRequest +): + client = QuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/questions/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.execute_question(request) + + +def test_execute_question_rest_flattened(): + client = QuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = question.Question() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/questions/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + interpretation_index=2159, + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = question.Question.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.execute_question(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=projects/*/locations/*/questions/*}:execute" + % client.transport._host, + args[1], + ) + + +def test_execute_question_rest_flattened_error(transport: str = "rest"): + client = QuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.execute_question( + question_service.ExecuteQuestionRequest(), + name="name_value", + interpretation_index=2159, + ) + + +def test_execute_question_rest_error(): + client = QuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + question_service.GetUserFeedbackRequest, + dict, + ], +) +def test_get_user_feedback_rest(request_type): + client = QuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/questions/sample3/userFeedback" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = user_feedback.UserFeedback( + name="name_value", + free_form_feedback="free_form_feedback_value", + rating=user_feedback.UserFeedback.UserFeedbackRating.POSITIVE, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = user_feedback.UserFeedback.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_user_feedback(request) + + # 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 + + +def test_get_user_feedback_rest_required_fields( + request_type=question_service.GetUserFeedbackRequest, +): + transport_class = transports.QuestionServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_user_feedback._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_user_feedback._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = QuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = user_feedback.UserFeedback() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = user_feedback.UserFeedback.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_user_feedback(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_user_feedback_rest_unset_required_fields(): + transport = transports.QuestionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_user_feedback._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_user_feedback_rest_interceptors(null_interceptor): + transport = transports.QuestionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.QuestionServiceRestInterceptor(), + ) + client = QuestionServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.QuestionServiceRestInterceptor, "post_get_user_feedback" + ) as post, mock.patch.object( + transports.QuestionServiceRestInterceptor, "pre_get_user_feedback" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = question_service.GetUserFeedbackRequest.pb( + question_service.GetUserFeedbackRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = user_feedback.UserFeedback.to_json( + user_feedback.UserFeedback() + ) + + request = question_service.GetUserFeedbackRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = user_feedback.UserFeedback() + + client.get_user_feedback( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_user_feedback_rest_bad_request( + transport: str = "rest", request_type=question_service.GetUserFeedbackRequest +): + client = QuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/questions/sample3/userFeedback" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_user_feedback(request) + + +def test_get_user_feedback_rest_flattened(): + client = QuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = user_feedback.UserFeedback() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/questions/sample3/userFeedback" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = user_feedback.UserFeedback.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_user_feedback(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=projects/*/locations/*/questions/*/userFeedback}" + % client.transport._host, + args[1], + ) + + +def test_get_user_feedback_rest_flattened_error(transport: str = "rest"): + client = QuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_user_feedback( + question_service.GetUserFeedbackRequest(), + name="name_value", + ) + + +def test_get_user_feedback_rest_error(): + client = QuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + question_service.UpdateUserFeedbackRequest, + dict, + ], +) +def test_update_user_feedback_rest(request_type): + client = QuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "user_feedback": { + "name": "projects/sample1/locations/sample2/questions/sample3/userFeedback" + } + } + request_init["user_feedback"] = { + "name": "projects/sample1/locations/sample2/questions/sample3/userFeedback", + "free_form_feedback": "free_form_feedback_value", + "rating": 1, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcd_user_feedback.UserFeedback( + name="name_value", + free_form_feedback="free_form_feedback_value", + rating=gcd_user_feedback.UserFeedback.UserFeedbackRating.POSITIVE, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = gcd_user_feedback.UserFeedback.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_user_feedback(request) + + # 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 + + +def test_update_user_feedback_rest_required_fields( + request_type=question_service.UpdateUserFeedbackRequest, +): + transport_class = transports.QuestionServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_user_feedback._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_user_feedback._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = QuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcd_user_feedback.UserFeedback() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = gcd_user_feedback.UserFeedback.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_user_feedback(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_user_feedback_rest_unset_required_fields(): + transport = transports.QuestionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_user_feedback._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("userFeedback",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_user_feedback_rest_interceptors(null_interceptor): + transport = transports.QuestionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.QuestionServiceRestInterceptor(), + ) + client = QuestionServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.QuestionServiceRestInterceptor, "post_update_user_feedback" + ) as post, mock.patch.object( + transports.QuestionServiceRestInterceptor, "pre_update_user_feedback" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = question_service.UpdateUserFeedbackRequest.pb( + question_service.UpdateUserFeedbackRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcd_user_feedback.UserFeedback.to_json( + gcd_user_feedback.UserFeedback() + ) + + request = question_service.UpdateUserFeedbackRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcd_user_feedback.UserFeedback() + + client.update_user_feedback( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_user_feedback_rest_bad_request( + transport: str = "rest", request_type=question_service.UpdateUserFeedbackRequest +): + client = QuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "user_feedback": { + "name": "projects/sample1/locations/sample2/questions/sample3/userFeedback" + } + } + request_init["user_feedback"] = { + "name": "projects/sample1/locations/sample2/questions/sample3/userFeedback", + "free_form_feedback": "free_form_feedback_value", + "rating": 1, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_user_feedback(request) + + +def test_update_user_feedback_rest_flattened(): + client = QuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcd_user_feedback.UserFeedback() + + # get arguments that satisfy an http rule for this method + sample_request = { + "user_feedback": { + "name": "projects/sample1/locations/sample2/questions/sample3/userFeedback" + } + } + + # get truthy value for each flattened field + mock_args = dict( + user_feedback=gcd_user_feedback.UserFeedback(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = gcd_user_feedback.UserFeedback.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_user_feedback(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{user_feedback.name=projects/*/locations/*/questions/*/userFeedback}" + % client.transport._host, + args[1], + ) + + +def test_update_user_feedback_rest_flattened_error(transport: str = "rest"): + client = QuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_user_feedback( + question_service.UpdateUserFeedbackRequest(), + user_feedback=gcd_user_feedback.UserFeedback(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_user_feedback_rest_error(): + client = QuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.QuestionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = QuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.QuestionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = QuestionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.QuestionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = QuestionServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = QuestionServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.QuestionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = QuestionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.QuestionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = QuestionServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.QuestionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.QuestionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.QuestionServiceGrpcTransport, + transports.QuestionServiceGrpcAsyncIOTransport, + transports.QuestionServiceRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "rest", + ], +) +def test_transport_kind(transport_name): + transport = QuestionServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + 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(core_exceptions.DuplicateCredentialArgs): + transport = transports.QuestionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_question_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.dataqna_v1alpha.services.question_service.transports.QuestionServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.QuestionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "get_question", + "create_question", + "execute_question", + "get_user_feedback", + "update_user_feedback", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_question_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.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( @@ -2207,6 +3837,7 @@ def test_question_service_transport_auth_adc(transport_class): [ transports.QuestionServiceGrpcTransport, transports.QuestionServiceGrpcAsyncIOTransport, + transports.QuestionServiceRestTransport, ], ) def test_question_service_transport_auth_gdch_credentials(transport_class): @@ -2304,11 +3935,23 @@ def test_question_service_grpc_transport_client_cert_source_for_mtls(transport_c ) +def test_question_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.QuestionServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_question_service_host_no_port(transport_name): @@ -2319,7 +3962,11 @@ def test_question_service_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("dataqna.googleapis.com:443") + assert client.transport._host == ( + "dataqna.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dataqna.googleapis.com" + ) @pytest.mark.parametrize( @@ -2327,6 +3974,7 @@ def test_question_service_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_question_service_host_with_port(transport_name): @@ -2337,7 +3985,45 @@ def test_question_service_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("dataqna.googleapis.com:8000") + assert client.transport._host == ( + "dataqna.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dataqna.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_question_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = QuestionServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = QuestionServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_question._session + session2 = client2.transport.get_question._session + assert session1 != session2 + session1 = client1.transport.create_question._session + session2 = client2.transport.create_question._session + assert session1 != session2 + session1 = client1.transport.execute_question._session + session2 = client2.transport.execute_question._session + assert session1 != session2 + session1 = client1.transport.get_user_feedback._session + session2 = client2.transport.get_user_feedback._session + assert session1 != session2 + session1 = client1.transport.update_user_feedback._session + session2 = client2.transport.update_user_feedback._session + assert session1 != session2 def test_question_service_grpc_transport_channel(): @@ -2660,6 +4346,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -2677,6 +4364,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: